From 857eedf379ac2d80d0fb25c25c053357dfce9749 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 06:06:38 -0500 Subject: [PATCH 01/36] =?UTF-8?q?T-134:=20M2.1d=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`search=5Fsymbols`=20tool:=20vault-safe=20security-master?= =?UTF-8?q?=20symbol=20lookup=20via=20an=20injected=20`SymbolSearchPort`?= =?UTF-8?q?=20in=20`libs/research/src/mcp/tools/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/index.ts | 1 + libs/research/src/mcp/tools/search-symbols.ts | 356 +++++++++ libs/research/test/mcp-search-symbols.test.ts | 687 ++++++++++++++++++ 3 files changed, 1044 insertions(+) create mode 100644 libs/research/src/mcp/tools/search-symbols.ts create mode 100644 libs/research/test/mcp-search-symbols.test.ts diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 6a966bc9..2ed5c994 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -4,3 +4,4 @@ export * from './stdio'; export * from './tools/analyze-signal'; export * from './tools/event-study'; export * from './tools/query-data'; +export * from './tools/search-symbols'; diff --git a/libs/research/src/mcp/tools/search-symbols.ts b/libs/research/src/mcp/tools/search-symbols.ts new file mode 100644 index 00000000..9324ee16 --- /dev/null +++ b/libs/research/src/mcp/tools/search-symbols.ts @@ -0,0 +1,356 @@ +import { z } from 'zod'; +import { MarketDataStoreValidationError, type VaultFenceContext } from '../../market-data-store'; +import type { McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool } from '../server'; +import { utcDateOf, validateVaultCutoffTs } from './vault-fenced-input'; + +/** Default maximum number of matching listings returned by `search_symbols`. */ +export const SEARCH_SYMBOLS_DEFAULT_LIMIT = 20; + +/** Hard maximum number of matching listings returned by `search_symbols`. */ +export const SEARCH_SYMBOLS_MAX_LIMIT = 100; + +/** Hard maximum character length of a trimmed `search_symbols` query string. */ +export const SEARCH_SYMBOLS_MAX_QUERY_LENGTH = 64; + +/** Supported exchange country filters for `search_symbols`. */ +export const SEARCH_SYMBOLS_COUNTRIES = ['US', 'CA'] as const; + +export type SymbolSearchCountry = (typeof SEARCH_SYMBOLS_COUNTRIES)[number]; + +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]; + +/** + * Security-master projection returned by {@link SymbolSearchPort} and emitted + * (after Vault fencing) by the `search_symbols` MCP tool. + * + * Field provenance (M1 security master DDL / `design/DATA-CONTRACTS.md`): + * - `listingId`: `listing.listing_id` (`INT32`) + * - `instrumentId`: `listing.instrument_id` / `instrument.instrument_id` (`INT32`) + * - `ticker`: `listing_symbol_history.ticker` valid as of the Vault cutoff + * - `classSuffix`: nullable `listing.class_suffix` + * - `name`: `instrument.canonical_name` + * - `mic`: `listing.mic` + * - `currency`: `listing.currency` + * - `isin`: nullable `instrument.primary_isin` + * - `firstBarDate`: nullable `YYYY-MM-DD` observed bar span start (`listing.listed_from`) + * - `lastBarDate`: nullable `YYYY-MM-DD` observed bar span end (`listing.listed_to`) + * - `delistedAt`: nullable `YYYY-MM-DD` confirmed delisting date (distinct from `lastBarDate`) + */ +export interface SymbolSearchRow { + readonly listingId: number; + readonly instrumentId: number; + readonly ticker: string; + readonly classSuffix: string | null; + readonly name: string; + readonly mic: string; + readonly currency: string; + readonly isin: string | null; + readonly firstBarDate: string | null; + readonly lastBarDate: string | null; + readonly delistedAt: string | null; +} + +/** + * Query passed to {@link SymbolSearchPort.searchSymbols}. + * + * Port contract: + * - Return all matching candidates for tool-side ranking and Vault fencing; + * treat `limit` as a hint only (never truncate ahead of exact-ticker matches). + * - Resolve symbol identities and matches as of `vaultCutoffTs` so future + * renames or delistings do not leak into research queries. + * - Include listings whose `firstBarDate` is unknown (`null`). + * - The tool always passes `includeDelisted: true` to the port so current + * delisting status cannot drop a candidate before Vault cutoff masking. + */ +export interface SymbolSearchQuery { + readonly query: string; + readonly limit: number; + readonly country?: SymbolSearchCountry; + readonly includeDelisted: boolean; + readonly vaultCutoffTs: number; +} + +/** Read-only security-master symbol lookup port injected into `createSearchSymbolsTool`. */ +export interface SymbolSearchPort { + searchSymbols(q: SymbolSearchQuery): Promise; +} + +/** + * Strict Zod input schema for the `search_symbols` MCP tool. + * + * Intentionally omits `scope`, `vault_evaluation_only`, and `vaultCutoffTs`; + * `.strict()` rejects any unknown keys. + */ +export const searchSymbolsInputSchema = z + .object({ + query: z + .string() + .trim() + .min(1) + .max(SEARCH_SYMBOLS_MAX_QUERY_LENGTH) + .describe( + `Ticker symbol or company name search query (trimmed, 1–${SEARCH_SYMBOLS_MAX_QUERY_LENGTH} characters).` + ), + limit: z + .number() + .int() + .min(1) + .max(SEARCH_SYMBOLS_MAX_LIMIT) + .default(SEARCH_SYMBOLS_DEFAULT_LIMIT) + .describe( + `Maximum number of matching listings to return (default ${SEARCH_SYMBOLS_DEFAULT_LIMIT}, max ${SEARCH_SYMBOLS_MAX_LIMIT}).` + ), + country: z + .enum(SEARCH_SYMBOLS_COUNTRIES) + .optional() + .describe('Optional exchange country filter (US or CA).'), + includeDelisted: z + .boolean() + .default(true) + .describe('Include delisted listings as of the Vault cutoff (default true).'), + }) + .strict(); + +export type SearchSymbolsInput = z.infer; + +/** Server-side injected configuration for {@link createSearchSymbolsTool}. */ +export interface SearchSymbolsToolOptions { + readonly port: SymbolSearchPort; + readonly vaultContext: Pick; +} + +/** Structured JSON payload serialized into the `search_symbols` MCP text result. */ +export interface SearchSymbolsResultPayload { + readonly scope: 'vault_fenced'; + readonly vaultCutoffTs: number; + readonly rowCount: number; + readonly truncated: boolean; + readonly rows: readonly SymbolSearchRow[]; +} + +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 validateNullableDate(value: unknown, field: string): string | null { + if (value === null) { + return null; + } + if (!isValidCalendarDate(value)) { + throw new Error(`Invalid port date for "${field}".`); + } + return value; +} + +function validateNullableString(value: unknown, field: string): string | null { + if (value === null) { + return null; + } + if (typeof value !== 'string') { + throw new Error(`Invalid port string for "${field}".`); + } + return value; +} + +function validateRequiredString(value: unknown, field: string): string { + if (typeof value !== 'string') { + throw new Error(`Invalid port string for "${field}".`); + } + return value; +} + +function validateSafeInteger(value: unknown, field: string): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value)) { + throw new Error(`Invalid port integer for "${field}".`); + } + return value; +} + +function fenceAndProjectRow( + raw: SymbolSearchRow, + vaultCutoffDate: string, + includeDelisted: boolean +): SymbolSearchRow | null { + if (typeof raw !== 'object' || raw === null) { + throw new Error('Invalid symbol search row returned by port.'); + } + + const listingId = validateSafeInteger(raw.listingId, 'listingId'); + const instrumentId = validateSafeInteger(raw.instrumentId, 'instrumentId'); + const ticker = validateRequiredString(raw.ticker, 'ticker'); + const classSuffix = validateNullableString(raw.classSuffix, 'classSuffix'); + const name = validateRequiredString(raw.name, 'name'); + const mic = validateRequiredString(raw.mic, 'mic'); + const currency = validateRequiredString(raw.currency, 'currency'); + const isin = validateNullableString(raw.isin, 'isin'); + const firstBarDate = validateNullableDate(raw.firstBarDate, 'firstBarDate'); + const rawLastBarDate = validateNullableDate(raw.lastBarDate, 'lastBarDate'); + const rawDelistedAt = validateNullableDate(raw.delistedAt, 'delistedAt'); + + if (firstBarDate !== null && firstBarDate > vaultCutoffDate) { + return null; + } + + const lastBarDate = + rawLastBarDate !== null && rawLastBarDate > vaultCutoffDate ? vaultCutoffDate : rawLastBarDate; + + const delistedAt = + rawDelistedAt !== null && rawDelistedAt > vaultCutoffDate ? null : rawDelistedAt; + + if (!includeDelisted && delistedAt !== null) { + return null; + } + + return { + listingId, + instrumentId, + ticker, + classSuffix, + name, + mic, + currency, + isin, + firstBarDate, + lastBarDate, + delistedAt, + }; +} + +function matchRank(row: SymbolSearchRow, normalizedQuery: string): number { + const normalizedTicker = row.ticker.toLowerCase(); + if (normalizedTicker === normalizedQuery) { + return 0; + } + if (normalizedTicker.startsWith(normalizedQuery)) { + return 1; + } + if (row.name.toLowerCase().includes(normalizedQuery)) { + return 2; + } + return 3; +} + +function validateFactoryOptions(options: SearchSymbolsToolOptions): number { + if (typeof options !== 'object' || options === null) { + throw new MarketDataStoreValidationError( + 'Invalid `options`: expected a SearchSymbolsToolOptions object.', + 'options' + ); + } + + if ( + typeof options.port !== 'object' || + options.port === null || + typeof options.port.searchSymbols !== 'function' + ) { + throw new MarketDataStoreValidationError( + 'Invalid `port`: expected a SymbolSearchPort implementing `searchSymbols`.', + 'port' + ); + } + + return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); +} + +/** + * Creates the Vault-fenced `search_symbols` MCP tool backed by an injected + * read-only {@link SymbolSearchPort}. + * + * Enforces `scope: 'vault_fenced'`, requests candidates with + * `includeDelisted: true` so current delisting status cannot hide listings that + * were active as of the Vault cutoff, drops post-cutoff listings, clamps + * `lastBarDate` and masks future `delistedAt` against the cutoff UTC calendar + * date, ranks deterministically (exact ticker > ticker prefix > company name, + * breaking ties by ascending `listingId`), and caps results at `limit`. + */ +export function createSearchSymbolsTool(options: SearchSymbolsToolOptions): McpToolEntry { + const vaultCutoffTs = validateFactoryOptions(options); + const vaultCutoffDate = utcDateOf(vaultCutoffTs); + const { port } = options; + + return defineMcpTool({ + name: 'search_symbols', + description: + 'Search Vault-fenced security-master listings by ticker symbol or company name and return numeric listing IDs.', + inputSchema: searchSymbolsInputSchema, + async handler(input: SearchSymbolsInput): Promise { + const candidates = await port.searchSymbols({ + query: input.query, + limit: input.limit, + ...(input.country !== undefined ? { country: input.country } : {}), + includeDelisted: true, + vaultCutoffTs, + }); + + if (!Array.isArray(candidates)) { + throw new Error('Invalid symbol search response returned by port.'); + } + + const normalizedQuery = input.query.toLowerCase(); + const eligible: { readonly row: SymbolSearchRow; readonly rank: number }[] = []; + + for (let i = 0; i < candidates.length; i += 1) { + const fenced = fenceAndProjectRow( + candidates[i] as SymbolSearchRow, + vaultCutoffDate, + input.includeDelisted + ); + if (fenced !== null) { + eligible.push({ row: fenced, rank: matchRank(fenced, normalizedQuery) }); + } + } + + eligible.sort((a, b) => { + if (a.rank !== b.rank) { + return a.rank - b.rank; + } + return a.row.listingId - b.row.listingId; + }); + + const truncated = eligible.length > input.limit; + const limitCount = truncated ? input.limit : eligible.length; + const rows: SymbolSearchRow[] = []; + for (let i = 0; i < limitCount; i += 1) { + rows.push((eligible[i] as { readonly row: SymbolSearchRow }).row); + } + + const payload: SearchSymbolsResultPayload = { + scope: 'vault_fenced', + vaultCutoffTs, + rowCount: rows.length, + truncated, + rows, + }; + + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + }, + }); +} diff --git a/libs/research/test/mcp-search-symbols.test.ts b/libs/research/test/mcp-search-symbols.test.ts new file mode 100644 index 00000000..2e8e8b15 --- /dev/null +++ b/libs/research/test/mcp-search-symbols.test.ts @@ -0,0 +1,687 @@ +import { describe, expect, test } from 'bun:test'; +import { + type MarketDataStore, + MarketDataStoreValidationError, +} from '../src/market-data-store'; +import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; +import { + SEARCH_SYMBOLS_DEFAULT_LIMIT, + SEARCH_SYMBOLS_MAX_LIMIT, + SEARCH_SYMBOLS_MAX_QUERY_LENGTH, + type SearchSymbolsResultPayload, + type SymbolSearchPort, + type SymbolSearchQuery, + type SymbolSearchRow, + createAnalyzeSignalTool, + createEventStudyTool, + createMcpServer, + createQueryDataTool, + createSearchSymbolsTool, +} from '../src/mcp/index'; +import type { TrialLedgerExecutor } from '../src/trial-ledger'; + +const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); // 2025-03-31T00:00:00.000Z +const VAULT_CUTOFF_DATE = '2025-03-31'; + +interface FixtureRow extends SymbolSearchRow { + readonly country?: 'US' | 'CA'; +} + +function makeRow(overrides: Partial & { readonly listingId: number }): SymbolSearchRow { + return { + listingId: overrides.listingId, + instrumentId: overrides.instrumentId ?? overrides.listingId * 10, + ticker: overrides.ticker ?? `T${overrides.listingId}`, + classSuffix: overrides.classSuffix ?? null, + name: overrides.name ?? `Company ${overrides.listingId}`, + mic: overrides.mic ?? 'XNAS', + currency: overrides.currency ?? 'USD', + isin: overrides.isin ?? null, + firstBarDate: overrides.firstBarDate === undefined ? '2020-01-02' : overrides.firstBarDate, + lastBarDate: overrides.lastBarDate === undefined ? '2025-03-28' : overrides.lastBarDate, + delistedAt: overrides.delistedAt === undefined ? null : overrides.delistedAt, + }; +} + +interface FakePortState { + readonly calls: SymbolSearchQuery[]; + readonly port: SymbolSearchPort; +} + +function createFakePort(options?: { + readonly rows?: readonly FixtureRow[]; + readonly filterByCountry?: boolean; + readonly error?: unknown; + readonly rawReturn?: unknown; +}): FakePortState { + const calls: SymbolSearchQuery[] = []; + const rows = options?.rows ?? []; + + const port: SymbolSearchPort = { + async searchSymbols(q: SymbolSearchQuery): Promise { + calls.push({ ...q }); + if (options?.error !== undefined) { + throw options.error; + } + if (options?.rawReturn !== undefined) { + return options.rawReturn as readonly SymbolSearchRow[]; + } + if (options?.filterByCountry && q.country !== undefined) { + return rows.filter(row => row.country === q.country); + } + return [...rows]; + }, + }; + + return { calls, port }; +} + +function createMinimalStore(): MarketDataStore { + return { + bars() { + return { + async *[Symbol.asyncIterator]() { + // empty stream + }, + }; + }, + async universe() { + return []; + }, + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; +} + +function createMinimalLedger(): TrialLedgerExecutor { + return { + async query() { + return { rows: [] }; + }, + }; +} + +async function callSearchSymbols( + fake: FakePortState, + args: Record, + vaultCutoffTs = VAULT_CUTOFF_TS +): Promise<{ + readonly isError: boolean; + readonly text: string; + readonly payload: SearchSymbolsResultPayload | null; +}> { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createSearchSymbolsTool({ + port: fake.port, + vaultContext: { vaultCutoffTs }, + }), + ], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'ss-1', + method: 'tools/call', + params: { + name: 'search_symbols', + arguments: args, + }, + }) + ); + + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw as string) as { + result: { + isError?: boolean; + content: { type: string; text: string }[]; + }; + }; + const isError = parsed.result.isError === true; + const text = parsed.result.content[0]?.text ?? ''; + + return { + isError, + text, + payload: isError ? null : (JSON.parse(text) as SearchSymbolsResultPayload), + }; +} + +describe('MCP search_symbols tool', () => { + test('registers alongside query_data, analyze_signal, and event_study and exposes strict schema via tools/list', async () => { + const store = createMinimalStore(); + const ledger = createMinimalLedger(); + const fake = createFakePort({ + rows: [ + makeRow({ + listingId: 42, + instrumentId: 420, + ticker: 'AAPL', + classSuffix: null, + name: 'Apple Inc.', + mic: 'XNAS', + currency: 'USD', + isin: 'US0378331005', + firstBarDate: '1980-12-12', + lastBarDate: '2025-03-28', + delistedAt: null, + }), + ], + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + createAnalyzeSignalTool({ + store, + ledger, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + principalId: 'operator', + }), + createEventStudyTool({ + store, + ledger, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + principalId: 'operator', + resolveExchangeCalendars: () => ({}), + }), + createSearchSymbolsTool({ + port: fake.port, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + + const listRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/list', + }) + ); + expect(listRaw).not.toBeNull(); + + const listParsed = JSON.parse(listRaw as string) as { + result: { + tools: { + name: string; + description: string; + inputSchema: { + type: string; + properties: Record>; + required?: string[]; + additionalProperties: boolean; + }; + }[]; + }; + }; + + expect(listParsed.result.tools.map(t => t.name)).toEqual([ + 'query_data', + 'analyze_signal', + 'event_study', + 'search_symbols', + ]); + + const searchTool = listParsed.result.tools.find(t => t.name === 'search_symbols'); + expect(searchTool).toBeDefined(); + expect(searchTool?.inputSchema.type).toBe('object'); + expect(searchTool?.inputSchema.additionalProperties).toBe(false); + expect(searchTool?.inputSchema.required).toEqual(['query']); + expect(searchTool?.inputSchema.properties.query).toMatchObject({ + type: 'string', + minLength: 1, + maxLength: SEARCH_SYMBOLS_MAX_QUERY_LENGTH, + }); + expect(searchTool?.inputSchema.properties.limit).toMatchObject({ + type: 'integer', + minimum: 1, + maximum: SEARCH_SYMBOLS_MAX_LIMIT, + default: SEARCH_SYMBOLS_DEFAULT_LIMIT, + }); + expect(searchTool?.inputSchema.properties.country).toMatchObject({ + type: 'string', + enum: ['US', 'CA'], + }); + expect(searchTool?.inputSchema.properties.includeDelisted).toMatchObject({ + type: 'boolean', + default: true, + }); + expect(searchTool?.inputSchema.properties.scope).toBeUndefined(); + expect(searchTool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); + expect(searchTool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); + + // Exercise JSON-RPC tools/call end-to-end on the multi-tool server. + const callRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { + name: 'search_symbols', + arguments: { query: 'AAPL' }, + }, + }) + ); + expect(callRaw).not.toBeNull(); + const callParsed = JSON.parse(callRaw as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(callParsed.result.isError).toBeUndefined(); + const payload = JSON.parse(callParsed.result.content[0]?.text ?? '') as SearchSymbolsResultPayload; + expect(payload).toEqual({ + scope: 'vault_fenced', + vaultCutoffTs: VAULT_CUTOFF_TS, + rowCount: 1, + truncated: false, + rows: [ + { + listingId: 42, + instrumentId: 420, + ticker: 'AAPL', + classSuffix: null, + name: 'Apple Inc.', + mic: 'XNAS', + currency: 'USD', + isin: 'US0378331005', + firstBarDate: '1980-12-12', + lastBarDate: '2025-03-28', + delistedAt: null, + }, + ], + }); + }); + + test('ranks exact ticker > ticker prefix > company name case-insensitively with numeric listingId tie-break', async () => { + const fixture: SymbolSearchRow[] = [ + makeRow({ listingId: 100, ticker: 'XYZ', name: 'Apple Blossom Holdings' }), + makeRow({ listingId: 10, ticker: 'AAPL', name: 'Apple Inc. Secondary' }), + makeRow({ listingId: 25, ticker: 'AAPLE', name: 'Apple Energy Corp' }), + makeRow({ listingId: 2, ticker: 'aapl', name: 'Apple Inc.' }), + makeRow({ listingId: 5, ticker: 'AAPLX', name: 'Apple Extended ETF' }), + makeRow({ listingId: 15, ticker: 'ZZZ', name: 'aapl Partners LP' }), + makeRow({ listingId: 30, ticker: 'OTHER', name: 'Unrelated Name' }), + ]; + + const fakeA = createFakePort({ rows: fixture }); + const fakeB = createFakePort({ rows: [...fixture].reverse() }); + + const resA = await callSearchSymbols(fakeA, { query: ' AaPl ' }); + const resB = await callSearchSymbols(fakeB, { query: ' AaPl ' }); + + expect(resA.isError).toBe(false); + expect(resB.isError).toBe(false); + expect(resA.payload).toEqual(resB.payload); + + // Exact ticker (2, 10) -> prefix (5, 25) -> name substring (15; note 100 has 'Apple' not 'aapl') -> other (30, 100) + expect(resA.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15, 30, 100]); + expect(resA.payload?.rowCount).toBe(7); + expect(resA.payload?.truncated).toBe(false); + + // Verify trimmed query, default limit, includeDelisted: true, and vaultCutoffTs were passed to port. + expect(fakeA.calls).toHaveLength(1); + expect(fakeA.calls[0]).toEqual({ + query: 'AaPl', + limit: SEARCH_SYMBOLS_DEFAULT_LIMIT, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + }); + + test('forwards country filter and returns empty payload when no listings match', async () => { + const fake = createFakePort({ + filterByCountry: true, + rows: [ + { ...makeRow({ listingId: 1, ticker: 'SHOP', mic: 'XNYS', currency: 'USD' }), country: 'US' }, + { ...makeRow({ listingId: 2, ticker: 'SHOP', mic: 'XTSE', currency: 'CAD' }), country: 'CA' }, + ], + }); + + const caRes = await callSearchSymbols(fake, { query: 'SHOP', country: 'CA' }); + expect(caRes.isError).toBe(false); + expect(caRes.payload?.rows.map(r => r.listingId)).toEqual([2]); + expect(fake.calls[0]?.country).toBe('CA'); + + const emptyFake = createFakePort({ rows: [] }); + const emptyRes = await callSearchSymbols(emptyFake, { query: 'NO_SUCH_SYMBOL', country: 'US' }); + expect(emptyRes.isError).toBe(false); + expect(emptyRes.payload).toEqual({ + scope: 'vault_fenced', + vaultCutoffTs: VAULT_CUTOFF_TS, + rowCount: 0, + truncated: false, + rows: [], + }); + expect(emptyFake.calls[0]?.country).toBe('US'); + }); + + test('enforces default limit 20, hard max 100, exact-fit, and over-returning port truncation', async () => { + // 25 eligible rows with default limit (20) -> truncated: true + const rows25: SymbolSearchRow[] = []; + for (let i = 1; i <= 25; i += 1) { + rows25.push(makeRow({ listingId: i, ticker: `SYM${i}`, name: `Symbol ${i}` })); + } + const defaultOver = await callSearchSymbols(createFakePort({ rows: rows25 }), { query: 'SYM' }); + expect(defaultOver.isError).toBe(false); + expect(defaultOver.payload?.rowCount).toBe(20); + expect(defaultOver.payload?.rows).toHaveLength(20); + expect(defaultOver.payload?.truncated).toBe(true); + + // Exact fit of 20 eligible rows -> truncated: false + const defaultExact = await callSearchSymbols(createFakePort({ rows: rows25.slice(0, 20) }), { + query: 'SYM', + }); + expect(defaultExact.isError).toBe(false); + expect(defaultExact.payload?.rowCount).toBe(20); + expect(defaultExact.payload?.truncated).toBe(false); + + // Hard max 100 accepted; port over-returns 115 rows with late exact match at end + const rows115: SymbolSearchRow[] = []; + for (let i = 1; i <= 114; i += 1) { + rows115.push(makeRow({ listingId: i + 10, ticker: `ABC${i}`, name: `ABC Corp ${i}` })); + } + rows115.push(makeRow({ listingId: 999, ticker: 'ABC', name: 'Exact Match Late In Array' })); + + const maxOver = await callSearchSymbols(createFakePort({ rows: rows115 }), { + query: 'ABC', + limit: 100, + }); + expect(maxOver.isError).toBe(false); + expect(maxOver.payload?.rowCount).toBe(100); + expect(maxOver.payload?.rows).toHaveLength(100); + expect(maxOver.payload?.truncated).toBe(true); + // Late exact ticker match must still rank #1 before slicing + expect(maxOver.payload?.rows[0]?.listingId).toBe(999); + + // Exact fit at max 100 -> truncated: false + const maxExact = await callSearchSymbols(createFakePort({ rows: rows115.slice(0, 100) }), { + query: 'ABC', + limit: 100, + }); + expect(maxExact.isError).toBe(false); + expect(maxExact.payload?.rowCount).toBe(100); + expect(maxExact.payload?.truncated).toBe(false); + }); + + test('rows removed by Vault fencing or includeDelisted: false do not count toward truncation', async () => { + const rows: SymbolSearchRow[] = [ + // Post-cutoff listings placed ahead of eligible matches + makeRow({ listingId: 1, ticker: 'ACME', firstBarDate: '2025-04-01' }), + makeRow({ listingId: 2, ticker: 'ACME2', firstBarDate: '2025-05-15' }), + // Historically delisted listings + makeRow({ listingId: 3, ticker: 'ACME3', delistedAt: '2024-06-30', lastBarDate: '2024-06-28' }), + makeRow({ listingId: 4, ticker: 'ACME4', delistedAt: '2025-03-31', lastBarDate: '2025-03-31' }), + // Active as of cutoff (one active forever, one delisted after cutoff) + makeRow({ listingId: 5, ticker: 'ACME5', delistedAt: null }), + makeRow({ listingId: 6, ticker: 'ACME6', delistedAt: '2025-04-15', lastBarDate: '2025-04-14' }), + ]; + + const res = await callSearchSymbols(createFakePort({ rows }), { + query: 'ACME', + limit: 2, + includeDelisted: false, + }); + + expect(res.isError).toBe(false); + expect(res.payload?.rows.map(r => r.listingId)).toEqual([5, 6]); + expect(res.payload?.rowCount).toBe(2); + expect(res.payload?.truncated).toBe(false); + }); + + test('enforces Vault fencing on firstBarDate, lastBarDate, delistedAt, UTC cutoff equality, and null dates', async () => { + const extraFieldRow = { + ...makeRow({ + listingId: 10, + ticker: 'VLT', + classSuffix: 'A', + isin: 'US0000000010', + firstBarDate: '2024-02-29', // valid leap-year date + lastBarDate: '2025-06-01', // after cutoff -> clamp to 2025-03-31 + delistedAt: '2025-05-01', // after cutoff -> mask to null + }), + internalSecretField: 'must-not-leak', + } as unknown as SymbolSearchRow; + + const rows: SymbolSearchRow[] = [ + extraFieldRow, + // firstBarDate strictly after cutoff -> dropped + makeRow({ + listingId: 11, + ticker: 'VLT', + firstBarDate: '2025-04-01', + lastBarDate: '2025-06-01', + delistedAt: null, + }), + // firstBarDate / lastBarDate / delistedAt equal to cutoff -> kept as-is + makeRow({ + listingId: 12, + ticker: 'VLT', + firstBarDate: VAULT_CUTOFF_DATE, + lastBarDate: VAULT_CUTOFF_DATE, + delistedAt: VAULT_CUTOFF_DATE, + }), + // Null dates preserved + makeRow({ + listingId: 13, + ticker: 'VLT', + firstBarDate: null, + lastBarDate: null, + delistedAt: null, + }), + // Historical delisting before cutoff -> preserved by default + makeRow({ + listingId: 14, + ticker: 'VLT', + firstBarDate: '2019-01-03', + lastBarDate: '2023-10-12', + delistedAt: '2023-10-15', + }), + ]; + + const fakeDefault = createFakePort({ rows }); + const resDefault = await callSearchSymbols(fakeDefault, { query: 'VLT' }); + expect(resDefault.isError).toBe(false); + expect(resDefault.payload?.rows).toEqual([ + { + listingId: 10, + instrumentId: 100, + ticker: 'VLT', + classSuffix: 'A', + name: 'Company 10', + mic: 'XNAS', + currency: 'USD', + isin: 'US0000000010', + firstBarDate: '2024-02-29', + lastBarDate: VAULT_CUTOFF_DATE, + delistedAt: null, + }, + { + listingId: 12, + instrumentId: 120, + ticker: 'VLT', + classSuffix: null, + name: 'Company 12', + mic: 'XNAS', + currency: 'USD', + isin: null, + firstBarDate: VAULT_CUTOFF_DATE, + lastBarDate: VAULT_CUTOFF_DATE, + delistedAt: VAULT_CUTOFF_DATE, + }, + { + listingId: 13, + instrumentId: 130, + ticker: 'VLT', + classSuffix: null, + name: 'Company 13', + mic: 'XNAS', + currency: 'USD', + isin: null, + firstBarDate: null, + lastBarDate: null, + delistedAt: null, + }, + { + listingId: 14, + instrumentId: 140, + ticker: 'VLT', + classSuffix: null, + name: 'Company 14', + mic: 'XNAS', + currency: 'USD', + isin: null, + firstBarDate: '2019-01-03', + lastBarDate: '2023-10-12', + delistedAt: '2023-10-15', + }, + ]); + // Extra port property must not be projected + expect('internalSecretField' in (resDefault.payload?.rows[0] ?? {})).toBe(false); + + // With includeDelisted: false, historical delistings (12, 14) are excluded, + // while future delisting (10) remains eligible with delistedAt: null. + const fakeNoDelisted = createFakePort({ rows }); + const resNoDelisted = await callSearchSymbols(fakeNoDelisted, { + query: 'VLT', + includeDelisted: false, + }); + expect(resNoDelisted.isError).toBe(false); + expect(resNoDelisted.payload?.rows.map(r => r.listingId)).toEqual([10, 13]); + expect(resNoDelisted.payload?.rows[0]?.delistedAt).toBeNull(); + // Port must still be called with includeDelisted: true + expect(fakeNoDelisted.calls[0]?.includeDelisted).toBe(true); + }); + + test('rejects invalid port date strings with sanitized isError result', async () => { + const invalidDateCases: Partial[] = [ + { firstBarDate: '2025-02-29' }, // non-leap year Feb 29 + { lastBarDate: '2025-04-31' }, // April has 30 days + { delistedAt: '2025-13-01' }, // invalid month + { firstBarDate: '2025-03-31T00:00:00Z' }, // timestamp instead of YYYY-MM-DD + { lastBarDate: 'not-a-date' }, + { delistedAt: '' }, + ]; + + for (const badFields of invalidDateCases) { + const fake = createFakePort({ + rows: [makeRow({ listingId: 1, ticker: 'BAD', ...badFields })], + }); + const res = await callSearchSymbols(fake, { query: 'BAD' }); + expect(res.isError).toBe(true); + expect(res.text).toBe('Error: Tool execution failed.'); + } + }); + + test('factory throws MarketDataStoreValidationError on missing or invalid port or vaultCutoffTs', () => { + const validPort = createFakePort().port; + + expect(() => + createSearchSymbolsTool(null as unknown as Parameters[0]) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createSearchSymbolsTool({ + port: null as unknown as SymbolSearchPort, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createSearchSymbolsTool({ + port: {} as unknown as SymbolSearchPort, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }) + ).toThrow(MarketDataStoreValidationError); + + const invalidCutoffs: unknown[] = [ + undefined, + null, + '2025-03-31', + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + 123.45, + 8_640_000_000_000_000, + ]; + + for (const badCutoff of invalidCutoffs) { + expect(() => + createSearchSymbolsTool({ + port: validPort, + vaultContext: { vaultCutoffTs: badCutoff as number }, + }) + ).toThrow(MarketDataStoreValidationError); + } + + expect(() => + createSearchSymbolsTool({ + port: validPort, + vaultContext: undefined as unknown as { vaultCutoffTs: number }, + }) + ).toThrow(MarketDataStoreValidationError); + }); + + test('returns structured isError without calling port on invalid arguments', async () => { + const invalidInputs: Record[] = [ + {}, + { query: '' }, + { query: ' \t\n ' }, + { query: 'A'.repeat(SEARCH_SYMBOLS_MAX_QUERY_LENGTH + 1) }, + { query: 'AAPL', limit: 0 }, + { query: 'AAPL', limit: -5 }, + { query: 'AAPL', limit: SEARCH_SYMBOLS_MAX_LIMIT + 1 }, + { query: 'AAPL', limit: 1.5 }, + { query: 'AAPL', country: 'UK' }, + { query: 'AAPL', country: 'us' }, + { query: 'AAPL', includeDelisted: 'true' }, + { query: 'AAPL', scope: 'vault_evaluation_only' }, + { query: 'AAPL', unknownField: 123 }, + ]; + + for (const args of invalidInputs) { + const fake = createFakePort({ rows: [makeRow({ listingId: 1, ticker: 'AAPL' })] }); + const res = await callSearchSymbols(fake, args); + expect(res.isError).toBe(true); + expect(res.text).toContain('Invalid arguments for tool "search_symbols"'); + expect(fake.calls).toHaveLength(0); + } + }); + + test('returns sanitized isError without leaking error message when port rejects', async () => { + const fake = createFakePort({ + error: new Error('postgres://admin:super-secret@10.0.0.51:5432/trading_bot failed'), + }); + + const res = await callSearchSymbols(fake, { query: 'AAPL' }); + expect(res.isError).toBe(true); + expect(res.text).toBe('Error: Tool execution failed.'); + expect(res.text).not.toContain('super-secret'); + expect(res.text).not.toContain('10.0.0.51'); + expect(res.text).not.toContain('trading_bot'); + expect(fake.calls).toHaveLength(1); + }); +}); From 4c810cb24987d5deb06e722fbe7064ec31016f34 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 06:11:53 -0500 Subject: [PATCH 02/36] =?UTF-8?q?T-134:=20M2.1d=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`search=5Fsymbols`=20tool:=20vault-safe=20security-master?= =?UTF-8?q?=20symbol=20lookup=20via=20an=20injected=20`SymbolSearchPort`?= =?UTF-8?q?=20in=20`libs/research/src/mcp/tools/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/search-symbols.ts | 9 ++++-- libs/research/test/mcp-search-symbols.test.ts | 30 +++++++++++++++++-- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/libs/research/src/mcp/tools/search-symbols.ts b/libs/research/src/mcp/tools/search-symbols.ts index 9324ee16..a5bd5882 100644 --- a/libs/research/src/mcp/tools/search-symbols.ts +++ b/libs/research/src/mcp/tools/search-symbols.ts @@ -242,7 +242,7 @@ function fenceAndProjectRow( }; } -function matchRank(row: SymbolSearchRow, normalizedQuery: string): number { +function matchRank(row: SymbolSearchRow, normalizedQuery: string): number | null { const normalizedTicker = row.ticker.toLowerCase(); if (normalizedTicker === normalizedQuery) { return 0; @@ -253,7 +253,7 @@ function matchRank(row: SymbolSearchRow, normalizedQuery: string): number { if (row.name.toLowerCase().includes(normalizedQuery)) { return 2; } - return 3; + return null; } function validateFactoryOptions(options: SearchSymbolsToolOptions): number { @@ -322,7 +322,10 @@ export function createSearchSymbolsTool(options: SearchSymbolsToolOptions): McpT input.includeDelisted ); if (fenced !== null) { - eligible.push({ row: fenced, rank: matchRank(fenced, normalizedQuery) }); + const rank = matchRank(fenced, normalizedQuery); + if (rank !== null) { + eligible.push({ row: fenced, rank }); + } } } diff --git a/libs/research/test/mcp-search-symbols.test.ts b/libs/research/test/mcp-search-symbols.test.ts index 2e8e8b15..1db83564 100644 --- a/libs/research/test/mcp-search-symbols.test.ts +++ b/libs/research/test/mcp-search-symbols.test.ts @@ -337,11 +337,35 @@ describe('MCP search_symbols tool', () => { expect(resB.isError).toBe(false); expect(resA.payload).toEqual(resB.payload); - // Exact ticker (2, 10) -> prefix (5, 25) -> name substring (15; note 100 has 'Apple' not 'aapl') -> other (30, 100) - expect(resA.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15, 30, 100]); - expect(resA.payload?.rowCount).toBe(7); + // Exact ticker (2, 10) -> prefix (5, 25) -> name substring (15); unrelated candidates (30, 100) are excluded + expect(resA.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15]); + expect(resA.payload?.rowCount).toBe(5); expect(resA.payload?.truncated).toBe(false); + // Unrelated candidates must not trigger truncation when all actual matches fit within limit. + const exactFitRes = await callSearchSymbols(createFakePort({ rows: fixture }), { + query: 'AAPL', + limit: 5, + }); + expect(exactFitRes.isError).toBe(false); + expect(exactFitRes.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15]); + expect(exactFitRes.payload?.rowCount).toBe(5); + expect(exactFitRes.payload?.truncated).toBe(false); + + // When none of the port's returned candidates match, return an empty, non-truncated payload. + const noMatchRes = await callSearchSymbols(createFakePort({ rows: fixture }), { + query: 'UNMATCHED', + limit: 2, + }); + expect(noMatchRes.isError).toBe(false); + expect(noMatchRes.payload).toEqual({ + scope: 'vault_fenced', + vaultCutoffTs: VAULT_CUTOFF_TS, + rowCount: 0, + truncated: false, + rows: [], + }); + // Verify trimmed query, default limit, includeDelisted: true, and vaultCutoffTs were passed to port. expect(fakeA.calls).toHaveLength(1); expect(fakeA.calls[0]).toEqual({ From c6bd028dcc1aa0eaeeace9aa0adb926bb9438dd3 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 06:17:13 -0500 Subject: [PATCH 03/36] T-134: tests --- .../test/mcp-search-symbols-qa.test.ts | 354 ++++++++++++++++++ 1 file changed, 354 insertions(+) create mode 100644 libs/research/test/mcp-search-symbols-qa.test.ts diff --git a/libs/research/test/mcp-search-symbols-qa.test.ts b/libs/research/test/mcp-search-symbols-qa.test.ts new file mode 100644 index 00000000..44d15be2 --- /dev/null +++ b/libs/research/test/mcp-search-symbols-qa.test.ts @@ -0,0 +1,354 @@ +import { describe, expect, test } from 'bun:test'; +import { + createMcpServer, + createSearchSymbolsTool, + SEARCH_SYMBOLS_MAX_QUERY_LENGTH, + type SearchSymbolsResultPayload, + type SymbolSearchPort, + type SymbolSearchQuery, + type SymbolSearchRow, +} from '../src/mcp/index'; + +// QA fixture: deterministic in-memory security-master port (no network, no +// Postgres, no MongoDB). Cutoffs are pinned epoch-ms values; no wall clock. +const MIDDAY_CUTOFF_TS = Date.UTC(2025, 2, 31, 15, 30, 0, 0); // 2025-03-31T15:30Z +const LAST_MS_CUTOFF_TS = Date.UTC(2025, 2, 31, 23, 59, 59, 999); // 2025-03-31T23:59:59.999Z +const CUTOFF_DATE = '2025-03-31'; + +function row( + overrides: Partial & { readonly listingId: number } +): SymbolSearchRow { + return { + instrumentId: overrides.listingId * 10, + ticker: `T${overrides.listingId}`, + classSuffix: null, + name: `Company ${overrides.listingId}`, + mic: 'XNAS', + currency: 'USD', + isin: null, + firstBarDate: '2020-01-02', + lastBarDate: '2025-03-28', + delistedAt: null, + ...overrides, + }; +} + +function fakePort(impl: (q: SymbolSearchQuery) => Promise | unknown): { + readonly calls: SymbolSearchQuery[]; + readonly port: SymbolSearchPort; +} { + const calls: SymbolSearchQuery[] = []; + return { + calls, + port: { + async searchSymbols(q) { + calls.push({ ...q }); + return (await impl(q)) as readonly SymbolSearchRow[]; + }, + }, + }; +} + +async function call( + port: SymbolSearchPort, + args: Record, + vaultCutoffTs: number +): Promise<{ isError: boolean; text: string; payload: SearchSymbolsResultPayload | null }> { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [createSearchSymbolsTool({ port, vaultContext: { vaultCutoffTs } })], + }); + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 7, + method: 'tools/call', + params: { name: 'search_symbols', arguments: args }, + }) + ); + const parsed = JSON.parse(raw as string) as { + result: { isError?: boolean; content: { text: string }[] }; + }; + const isError = parsed.result.isError === true; + const text = parsed.result.content[0]?.text ?? ''; + return { + isError, + text, + payload: isError ? null : (JSON.parse(text) as SearchSymbolsResultPayload), + }; +} + +describe('MCP search_symbols QA', () => { + test('intraday cutoff fences against the cutoff UTC calendar date (equal kept, next day dropped/clamped/masked)', async () => { + const rows = [ + row({ + listingId: 1, + ticker: 'QQ', + firstBarDate: CUTOFF_DATE, + lastBarDate: '2025-04-01', + delistedAt: '2025-04-01', + }), + row({ listingId: 2, ticker: 'QQ', firstBarDate: '2025-04-01', lastBarDate: '2025-04-02' }), + row({ listingId: 3, ticker: 'QQ', lastBarDate: CUTOFF_DATE, delistedAt: CUTOFF_DATE }), + ]; + for (const cutoff of [MIDDAY_CUTOFF_TS, LAST_MS_CUTOFF_TS]) { + const { port } = fakePort(() => rows); + const res = await call(port, { query: 'QQ' }, cutoff); + expect(res.isError).toBe(false); + expect(res.payload?.vaultCutoffTs).toBe(cutoff); + expect( + res.payload?.rows.map(r => [r.listingId, r.firstBarDate, r.lastBarDate, r.delistedAt]) + ).toEqual([ + [1, CUTOFF_DATE, CUTOFF_DATE, null], + [3, '2020-01-02', CUTOFF_DATE, CUTOFF_DATE], + ]); + } + }); + + test('cutoff one ms before midnight UTC uses the previous calendar date', async () => { + const cutoff = Date.UTC(2025, 2, 31, 0, 0, 0, 0) - 1; // 2025-03-30T23:59:59.999Z + const { port } = fakePort(() => [ + row({ listingId: 1, ticker: 'EDGE', firstBarDate: CUTOFF_DATE }), + row({ listingId: 2, ticker: 'EDGE', lastBarDate: CUTOFF_DATE, delistedAt: CUTOFF_DATE }), + ]); + const res = await call(port, { query: 'EDGE' }, cutoff); + expect(res.payload?.rows).toHaveLength(1); + expect(res.payload?.rows[0]).toMatchObject({ + listingId: 2, + lastBarDate: '2025-03-30', + delistedAt: null, + }); + }); + + test('a future delisting changes neither membership nor ranking relative to a never-delisted listing', async () => { + const base = [ + row({ listingId: 9, ticker: 'MSFT', name: 'Microsoft Corp' }), + row({ listingId: 4, ticker: 'MSFTX', name: 'Microsoft Tracker' }), + row({ listingId: 7, ticker: 'ZZZ', name: 'Old msft Holdings' }), + ]; + const withFutureDelisting = base.map(r => + r.listingId === 4 ? { ...r, delistedAt: '2026-01-15', lastBarDate: '2026-01-14' } : r + ); + for (const includeDelisted of [true, false]) { + const a = await call( + fakePort(() => base).port, + { query: 'msft', includeDelisted }, + MIDDAY_CUTOFF_TS + ); + const b = await call( + fakePort(() => withFutureDelisting).port, + { query: 'msft', includeDelisted }, + MIDDAY_CUTOFF_TS + ); + expect(a.payload?.rows.map(r => r.listingId)).toEqual([9, 4, 7]); + expect(b.payload?.rows.map(r => r.listingId)).toEqual([9, 4, 7]); + expect(b.payload?.rows[1]).toMatchObject({ delistedAt: null, lastBarDate: CUTOFF_DATE }); + } + }); + + test('truncation with includeDelisted: true ignores post-cutoff rows placed ahead of eligible matches', async () => { + const rows = [ + row({ listingId: 1, ticker: 'NEW', firstBarDate: '2025-06-01' }), + row({ listingId: 2, ticker: 'NEW', firstBarDate: '2025-04-01' }), + row({ listingId: 3, ticker: 'NEWA' }), + row({ listingId: 4, ticker: 'NEWB', delistedAt: '2021-05-05', lastBarDate: '2021-05-04' }), + ]; + const fit = await call(fakePort(() => rows).port, { query: 'new', limit: 2 }, MIDDAY_CUTOFF_TS); + expect(fit.payload).toMatchObject({ rowCount: 2, truncated: false }); + expect(fit.payload?.rows.map(r => r.listingId)).toEqual([3, 4]); + + const over = await call( + fakePort(() => rows).port, + { query: 'new', limit: 1 }, + MIDDAY_CUTOFF_TS + ); + expect(over.payload).toMatchObject({ rowCount: 1, truncated: true }); + expect(over.payload?.rows.map(r => r.listingId)).toEqual([3]); + }); + + test('a row matching both ticker prefix and name ranks by its best (ticker) match; name match is literal substring', async () => { + const rows = [ + row({ listingId: 1, ticker: 'ZED', name: 'A.B Industries' }), + row({ listingId: 2, ticker: 'A.BX', name: 'A.B Prefix Co' }), + row({ listingId: 3, ticker: 'AXB', name: 'Regex Bait AXB' }), + row({ listingId: 4, ticker: 'A.B', name: 'Exact Dot' }), + ]; + const res = await call(fakePort(() => rows).port, { query: 'a.b' }, MIDDAY_CUTOFF_TS); + // "a.b" must not behave like a regex: AXB (3) is not a match. + expect(res.payload?.rows.map(r => r.listingId)).toEqual([4, 2, 1]); + }); + + test('repeated calls on shuffled inputs give byte-identical payloads', async () => { + const rows = Array.from({ length: 30 }, (_, i) => + row({ listingId: 1000 - i * 7, ticker: i % 3 === 0 ? 'RY' : `RY${i}`, name: `Royal ${i}` }) + ); + // Deterministic Fisher-Yates with a fixed LCG seed. + let seed = 12345; + const shuffled = [...rows]; + for (let i = shuffled.length - 1; i > 0; i -= 1) { + seed = (seed * 1103515245 + 12345) % 2147483648; + const j = seed % (i + 1); + [shuffled[i], shuffled[j]] = [shuffled[j] as SymbolSearchRow, shuffled[i] as SymbolSearchRow]; + } + const a = await call(fakePort(() => rows).port, { query: 'RY', limit: 12 }, MIDDAY_CUTOFF_TS); + const b = await call( + fakePort(() => shuffled).port, + { query: 'RY', limit: 12 }, + MIDDAY_CUTOFF_TS + ); + expect(a.text).toBe(b.text); + const ids = a.payload?.rows.map(r => r.listingId) ?? []; + const exact = ids.slice(0, 10); + expect([...exact].sort((x, y) => x - y)).toEqual(exact); // 10 exact RY matches ascending + expect(a.payload?.truncated).toBe(true); + }); + + test('query of exactly 64 chars (and 64 chars after trimming) is accepted; whitespace is trimmed before the length check', async () => { + const q = 'B'.repeat(SEARCH_SYMBOLS_MAX_QUERY_LENGTH); + const fake = fakePort(() => []); + const exact = await call(fake.port, { query: q }, MIDDAY_CUTOFF_TS); + const padded = await call(fake.port, { query: ` ${q} ` }, MIDDAY_CUTOFF_TS); + expect(exact.isError).toBe(false); + expect(padded.isError).toBe(false); + expect(fake.calls.map(c => c.query)).toEqual([q, q]); + }); + + test('limit 1 and 100 accepted and forwarded as hints; non-number limit, null and non-boolean includeDelisted rejected without port call', async () => { + const fake = fakePort(() => []); + expect((await call(fake.port, { query: 'X', limit: 1 }, MIDDAY_CUTOFF_TS)).isError).toBe(false); + expect( + (await call(fake.port, { query: 'X', limit: 100, country: 'US' }, MIDDAY_CUTOFF_TS)).isError + ).toBe(false); + expect(fake.calls).toEqual([ + { query: 'X', limit: 1, includeDelisted: true, vaultCutoffTs: MIDDAY_CUTOFF_TS }, + { + query: 'X', + limit: 100, + country: 'US', + includeDelisted: true, + vaultCutoffTs: MIDDAY_CUTOFF_TS, + }, + ]); + + const bad = fakePort(() => []); + for (const args of [ + { query: 'X', limit: '20' }, + { query: 'X', limit: null }, + { query: 'X', limit: Number.NaN }, + { query: 42 }, + { query: 'X', country: null }, + { query: 'X', includeDelisted: 0 }, + { query: 'X', vaultCutoffTs: Date.UTC(2030, 0, 1) }, + ]) { + const res = await call(bad.port, args, MIDDAY_CUTOFF_TS); + expect(res.isError).toBe(true); + } + expect(bad.calls).toHaveLength(0); + }); + + test('malformed port responses yield a sanitized isError result', async () => { + const malformed: unknown[] = [ + null, + { rows: [] }, + 'not-an-array', + [null], + ['row'], + [{ ...row({ listingId: 1, ticker: 'M' }), listingId: '1' }], + [{ ...row({ listingId: 1, ticker: 'M' }), listingId: 1.5 }], + [{ ...row({ listingId: 1, ticker: 'M' }), instrumentId: undefined }], + [{ ...row({ listingId: 1, ticker: 'M' }), ticker: null }], + [{ ...row({ listingId: 1, ticker: 'M' }), name: undefined }], + [{ ...row({ listingId: 1, ticker: 'M' }), mic: 5 }], + [{ ...row({ listingId: 1, ticker: 'M' }), isin: 123 }], + [{ ...row({ listingId: 1, ticker: 'M' }), classSuffix: undefined }], + [{ ...row({ listingId: 1, ticker: 'M' }), firstBarDate: undefined }], + ]; + for (const response of malformed) { + const res = await call(fakePort(() => response).port, { query: 'M' }, MIDDAY_CUTOFF_TS); + expect(res.isError).toBe(true); + expect(res.text).toBe('Error: Tool execution failed.'); + } + }); + + test('non-Error port rejections are sanitized', async () => { + for (const thrown of ['password=hunter2', { secret: 'x' }, 42]) { + const res = await call( + fakePort(() => { + throw thrown; + }).port, + { query: 'AAPL' }, + MIDDAY_CUTOFF_TS + ); + expect(res.isError).toBe(true); + expect(res.text).toBe('Error: Tool execution failed.'); + expect(res.text).not.toContain('hunter2'); + } + }); + + test('returned rows are fresh projections: mutating port objects after the call does not alter output, and port input is not mutated', async () => { + const source = row({ listingId: 5, ticker: 'FRZ', lastBarDate: '2025-05-05' }); + const snapshot = JSON.stringify(source); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createSearchSymbolsTool({ + port: { searchSymbols: async () => [source] }, + vaultContext: { vaultCutoffTs: MIDDAY_CUTOFF_TS }, + }), + ], + }); + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'search_symbols', arguments: { query: 'FRZ' } }, + }) + ); + expect(JSON.stringify(source)).toBe(snapshot); // clamping did not write back to the port row + const payload = JSON.parse( + (JSON.parse(raw as string) as { result: { content: { text: string }[] } }).result.content[0] + ?.text ?? '' + ) as SearchSymbolsResultPayload; + expect(payload.rows[0]?.lastBarDate).toBe(CUTOFF_DATE); + }); + + test('concurrent calls are independent and each respects its own arguments', async () => { + const rows = [ + row({ listingId: 1, ticker: 'TD', mic: 'XTSE', currency: 'CAD' }), + row({ listingId: 2, ticker: 'TD', mic: 'XNYS' }), + row({ listingId: 3, ticker: 'TDX', delistedAt: '2022-02-02', lastBarDate: '2022-02-01' }), + ]; + const fake = fakePort(q => + q.country === undefined ? rows : rows.filter(r => (q.country === 'CA') === (r.mic === 'XTSE')) + ); + const [all, ca, active] = await Promise.all([ + call(fake.port, { query: 'TD' }, MIDDAY_CUTOFF_TS), + call(fake.port, { query: 'TD', country: 'CA' }, MIDDAY_CUTOFF_TS), + call(fake.port, { query: 'TD', includeDelisted: false, limit: 1 }, MIDDAY_CUTOFF_TS), + ]); + expect(all.payload?.rows.map(r => r.listingId)).toEqual([1, 2, 3]); + expect(ca.payload?.rows.map(r => r.listingId)).toEqual([1]); + expect(active.payload).toMatchObject({ rowCount: 1, truncated: true }); + expect(active.payload?.rows.map(r => r.listingId)).toEqual([1]); + }); + + test('pre-1970 cutoff fences correctly', async () => { + const cutoff = Date.UTC(1965, 5, 30, 12, 0, 0, 0); + const rows = [ + row({ + listingId: 1, + ticker: 'IBM', + firstBarDate: '1962-01-02', + lastBarDate: '2025-03-28', + delistedAt: null, + }), + row({ listingId: 2, ticker: 'IBM', firstBarDate: '1970-01-02' }), + ]; + const res = await call(fakePort(() => rows).port, { query: 'IBM' }, cutoff); + expect(res.payload?.rows).toHaveLength(1); + expect(res.payload?.rows[0]).toMatchObject({ listingId: 1, lastBarDate: '1965-06-30' }); + }); +}); From 35d5de815b6b8fc3547d893284a77c48c3a831ff Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 06:12:25 -0500 Subject: [PATCH 04/36] =?UTF-8?q?T-135:=20M2.3b=20=E2=80=94=20`libs/data/q?= =?UTF-8?q?uestdb`=20query=20layer=20for=20QuestDB=2010.2.0:=20`LATEST=20O?= =?UTF-8?q?N`=20+=20parameterized=20PGWire=20queries=20+=20contract=20DDL?= =?UTF-8?q?=20for=20`bars=5F1m`=20/=20`fx=5F1m`=20/=20`bar=5Frevisions`=20?= =?UTF-8?q?(pure,=20no=20live=20QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/data/questdb/README.md | 217 ++++---- libs/data/questdb/src/client.ts | 283 ++++++++-- libs/data/questdb/src/index.ts | 30 +- libs/data/questdb/src/query-builder.ts | 507 +++++++++++++---- libs/data/questdb/src/schema.ts | 198 +++++-- libs/data/questdb/src/types.ts | 52 +- .../questdb/test/questdb-query-layer.test.ts | 526 ++++++++++++++++++ libs/data/questdb/test/questdb.test.ts | 15 +- 8 files changed, 1523 insertions(+), 305 deletions(-) create mode 100644 libs/data/questdb/test/questdb-query-layer.test.ts diff --git a/libs/data/questdb/README.md b/libs/data/questdb/README.md index 469ab8be..52227c3b 100644 --- a/libs/data/questdb/README.md +++ b/libs/data/questdb/README.md @@ -1,102 +1,115 @@ -# QuestDB Client Library - -A comprehensive QuestDB client library for the Stock Bot trading platform, optimized for time-series data, market analytics, and high-performance queries. - -## Features - -- **Time-Series Optimized**: Built specifically for time-series data patterns -- **Dual Protocol Support**: HTTP REST API and PostgreSQL wire protocol -- **InfluxDB Line Protocol**: High-performance data ingestion -- **SQL Analytics**: Full SQL support for complex analytics -- **Schema Management**: Automatic table creation and partitioning -- **Performance Monitoring**: Query performance tracking and optimization -- **Health Monitoring**: Connection health monitoring and metrics - -## Usage - -```typescript -import { QuestDBClient } from '@stock-bot/questdb'; - -// Initialize client -const questClient = new QuestDBClient(); -await questClient.connect(); - -// Insert market data using InfluxDB Line Protocol -await questClient.insert('ohlcv', { - symbol: 'AAPL', - open: 150.00, - high: 152.00, - low: 149.50, - close: 151.50, - volume: 1000000, - timestamp: new Date() -}); - -// Query with SQL -const prices = await questClient.query(` - SELECT symbol, close, timestamp - FROM ohlcv - WHERE symbol = 'AAPL' - AND timestamp > dateadd('d', -1, now()) - ORDER BY timestamp DESC -`); - -// Time-series aggregations -const dailyStats = await questClient.aggregate('ohlcv') - .select(['symbol', 'avg(close) as avg_price']) - .where('symbol = ?', ['AAPL']) - .groupBy('symbol') - .sampleBy('1d', 'timestamp') - .execute(); -``` - -## Data Types - -The client provides typed access to the following time-series data: - -- **ohlcv**: OHLCV candlestick data -- **trades**: Individual trade executions -- **quotes**: Bid/ask quote data -- **indicators**: Technical indicator values -- **performance**: Portfolio performance metrics -- **risk_metrics**: Risk calculation results - -## Configuration - -Configure using environment variables: - -```env -QUESTDB_HOST=localhost -QUESTDB_HTTP_PORT=9000 -QUESTDB_PG_PORT=8812 -QUESTDB_INFLUX_PORT=9009 -``` - -## Time-Series Features - -QuestDB excels at: - -- **High-frequency data**: Millions of data points per second -- **Time-based partitioning**: Automatic partitioning by time -- **ASOF JOINs**: Time-series specific joins -- **SAMPLE BY**: Time-based aggregations -- **LATEST BY**: Get latest values by key - -## Performance - -The client includes performance optimizations: - -- Connection pooling for HTTP and PostgreSQL protocols -- Batch insertions for high throughput -- Compressed data transfer -- Query result caching -- Automatic schema optimization - -## Health Monitoring - -Built-in health monitoring: - -```typescript -const health = await questClient.getHealth(); -console.log(health.status); // 'healthy' | 'degraded' | 'unhealthy' -``` +# QuestDB Client Library + +A QuestDB 10.2.0 client library for the Stock Bot trading platform, optimized for time-series data, parameterized PGWire queries, and intraday bar storage. + +## Features + +- **Time-Series Optimized**: Built for QuestDB 10.2.0 (`LATEST ON`, `SAMPLE BY`, `ASOF JOIN`) +- **Parameterized PGWire Queries**: All value filters bind `$1..$n` placeholders; structured identifiers and intervals are strictly validated +- **Contract DDL**: Offline DDL generator for M2 intraday tables (`bars_1m`, `fx_1m`, `bar_revisions`) with `SYMBOL CAPACITY ... [NO]CACHE`, `PARTITION BY MONTH WAL`, and `DEDUP UPSERT KEYS` +- **Typed `bars_1m` Range Reader**: `readBars1m()` binds `listing_id` as canonical decimal string and returns `INT32` `listing_id` values with `known_at` preserved +- **InfluxDB Line Protocol**: Batch ingestion writer +- **Health Monitoring**: Connection health monitoring and metrics + +## Usage + +### Parameterized Queries & `LATEST ON` + +```typescript +import { QuestDBClient, QuestDBQueryBuilder } from '@stock-bot/questdb'; + +const questClient = new QuestDBClient({ + host: 'localhost', + httpPort: 9000, + pgPort: 8812, + influxPort: 9009, + database: 'qdb', +}); +await questClient.connect(); + +// Parameterized PGWire query via query builder +const { sql, params } = QuestDBQueryBuilder.create(questClient) + .select('listing_id', 'ts', 'close', 'volume') + .from('bars_1m') + .where('listing_id = $1', ['1042']) + .latestOn('ts', 'listing_id') + .buildParameterized(); +// sql: +// SELECT listing_id, ts, close, volume FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id +// params: ['1042'] + +// Execute directly (forwards both SQL and bound params) +const latestBars = await questClient.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', { + where: 'session = $1', + params: ['RTH'], +}); + +// Override the designated timestamp column explicitly +const latestRevisions = await questClient.latestBy( + 'bar_revisions', + ['listing_id', 'revised_at', 'new_close'], + 'listing_id', + { timestampColumn: 'revised_at' } +); + +// Time-series aggregations with bound filters +const hourlyStats = await questClient + .aggregate('ohlcv_data') + .selectAgg({ avg_close: 'avg(close)' }) + .whereSymbol('AAPL') + .whereLastHours(24) + .groupBy('symbol') + .sampleBy('1h') + .execute(); +``` + +### Reading `bars_1m` Ranges + +```typescript +import { readBars1m } from '@stock-bot/questdb'; + +// Queries `[from, to)` ordered by `ts ASC`, binding listingId as decimal string SYMBOL +// and converting returned `listing_id` back to signed INT32. +const bars = await readBars1m( + questClient, + 1042, + new Date('2024-01-02T14:30:00.000Z'), + new Date('2024-01-02T21:00:00.000Z') +); +``` + +> **Storage-layer read semantics**: `readBars1m` returns all stored bars in `[from, to)` and preserves `known_at` on each row without applying replay cutoffs. Research callers (`MarketDataStore`) remain responsible for as-of availability filtering and Vault fencing. + +### M2 Intraday Contract DDL (Offline) + +```typescript +import { getM2IntradayDDL } from '@stock-bot/questdb'; + +const ddl = getM2IntradayDDL(); +// ddl.bars_1m -> CREATE TABLE IF NOT EXISTS bars_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, listing_id) +// ddl.fx_1m -> CREATE TABLE IF NOT EXISTS fx_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, pair) +// ddl.bar_revisions -> CREATE TABLE IF NOT EXISTS bar_revisions (...) TIMESTAMP(revised_at) PARTITION BY MONTH WAL +``` + +M2 intraday tables are opt-in and are not auto-created during `QuestDBClient.connect()`. + +## Configuration + +Configure using environment variables: + +```env +QUESTDB_HOST=localhost +QUESTDB_HTTP_PORT=9000 +QUESTDB_PG_PORT=8812 +QUESTDB_INFLUX_PORT=9009 +``` + +## Time-Series Features + +QuestDB 10.2.0 supports: + +- **High-frequency data**: Millions of data points per second +- **Time-based partitioning**: Monthly WAL partitions for intraday tables +- **ASOF JOINs**: Time-series specific joins +- **SAMPLE BY**: Time-based aggregations +- **LATEST ON**: Get latest values per partition key (`LATEST ON PARTITION BY `) diff --git a/libs/data/questdb/src/client.ts b/libs/data/questdb/src/client.ts index d4cba976..4cb6a845 100644 --- a/libs/data/questdb/src/client.ts +++ b/libs/data/questdb/src/client.ts @@ -3,15 +3,153 @@ import { Pool } from 'pg'; import type { LoggerLike } from '@stock-bot/logger'; import { QuestDBHealthMonitor } from './health'; import { QuestDBInfluxWriter } from './influx-writer'; -import { QuestDBQueryBuilder } from './query-builder'; +import { + assertIdentifier, + assertSampleInterval, + assertSelectColumn, + QuestDBQueryBuilder, + rebaseWhereCondition, +} from './query-builder'; import { QuestDBSchemaManager } from './schema'; import type { + Bar1mRow, + LatestByOptions, QueryResult, QuestDBClientConfig, QuestDBConnectionOptions, + QuestDBQueryable, TableNames, } from './types'; +const INT32_MIN = -2147483648; +const INT32_MAX = 2147483647; +const CANONICAL_INT_RE = /^-?(?:0|[1-9]\d*)$/; +const ALLOWED_PARTITIONS = new Set(['NONE', 'HOUR', 'DAY', 'MONTH', 'YEAR']); + +function formatInt32ListingId(listingId: number): string { + if (!Number.isInteger(listingId) || listingId < INT32_MIN || listingId > INT32_MAX) { + throw new RangeError( + `Invalid listingId: expected signed INT32 integer, received ${String(listingId)}` + ); + } + return String(listingId === 0 ? 0 : listingId); +} + +function parseInt32ListingSymbol(raw: unknown): number { + if (typeof raw !== 'string' || !CANONICAL_INT_RE.test(raw)) { + throw new Error(`Malformed bars_1m listing_id SYMBOL value: "${String(raw)}"`); + } + const parsed = Number(raw); + if (!Number.isInteger(parsed) || parsed < INT32_MIN || parsed > INT32_MAX) { + throw new RangeError(`Out-of-range bars_1m listing_id SYMBOL value: "${raw}"`); + } + return parsed; +} + +function toUtcIsoString(value: Date | string, label: string): string { + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new Error(`Invalid ${label} timestamp: Date is NaN`); + } + return value.toISOString(); + } + if (typeof value === 'string' && value.trim().length > 0) { + const parsed = new Date(value); + if (!Number.isNaN(parsed.getTime())) { + return parsed.toISOString(); + } + } + throw new Error(`Invalid ${label} timestamp: "${String(value)}"`); +} + +function parseBarTimestamp(raw: unknown, field: string): Date { + if (raw instanceof Date) { + if (Number.isNaN(raw.getTime())) { + throw new Error(`Invalid bars_1m ${field} timestamp: Date is NaN`); + } + return new Date(raw.getTime()); + } + if (typeof raw === 'string' || typeof raw === 'number') { + const parsed = new Date(raw); + if (!Number.isNaN(parsed.getTime())) { + return parsed; + } + } + throw new Error(`Invalid bars_1m ${field} timestamp: "${String(raw)}"`); +} + +function parseRequiredFiniteNumber(raw: unknown, field: string): number { + const value = + typeof raw === 'number' + ? raw + : typeof raw === 'string' && raw.trim().length > 0 + ? Number(raw) + : Number.NaN; + if (!Number.isFinite(value)) { + throw new Error(`Invalid bars_1m ${field} value: "${String(raw)}"`); + } + return value; +} + +function parseNullableFiniteNumber(raw: unknown, field: string): number | null { + if (raw === null || raw === undefined) { + return null; + } + return parseRequiredFiniteNumber(raw, field); +} + +function parseNullableString(raw: unknown, field: string): string | null { + if (raw === null || raw === undefined) { + return null; + } + if (typeof raw === 'string') { + return raw; + } + throw new Error(`Invalid bars_1m ${field} value: expected string or null`); +} + +/** + * Read 1-minute bars for a single listing over `[from, to)` ordered by `ts ASC` from `bars_1m`. + * + * Binds `listingId` as its canonical decimal string (`SYMBOL`) and converts returned `listing_id` + * values back to signed `INT32` numbers at the boundary (`design/DATA-CONTRACTS.md` §3.B). + * + * Storage-layer read: preserves `known_at` on each row without applying replay cutoffs. + * Research callers (`MarketDataStore`) remain responsible for as-of availability and Vault fencing. + */ +export async function readBars1m( + client: QuestDBQueryable, + listingId: number, + from: Date | string, + to: Date | string +): Promise { + const listingIdParam = formatInt32ListingId(listingId); + const fromIso = toUtcIsoString(from, 'from'); + const toIso = toUtcIsoString(to, 'to'); + + const sql = + 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, known_at, ts ' + + 'FROM bars_1m ' + + 'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' + + 'ORDER BY ts ASC'; + + const result = await client.query>(sql, [listingIdParam, fromIso, toIso]); + + return result.rows.map(row => ({ + listing_id: parseInt32ListingSymbol(row.listing_id), + open: parseRequiredFiniteNumber(row.open, 'open'), + high: parseRequiredFiniteNumber(row.high, 'high'), + low: parseRequiredFiniteNumber(row.low, 'low'), + close: parseRequiredFiniteNumber(row.close, 'close'), + volume: parseRequiredFiniteNumber(row.volume, 'volume'), + vwap: parseNullableFiniteNumber(row.vwap, 'vwap'), + session: parseNullableString(row.session, 'session'), + source: parseNullableString(row.source, 'source'), + known_at: parseBarTimestamp(row.known_at, 'known_at'), + ts: parseBarTimestamp(row.ts, 'ts'), + })); +} + /** * QuestDB Client for Stock Bot * @@ -231,72 +369,125 @@ export class QuestDBClient { } /** - * Execute a time-series specific query with SAMPLE BY + * Execute a time-series specific query with SAMPLE BY. + * `where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `params`. */ async sampleBy( - table: TableNames, + table: TableNames | string, columns: string[], interval: string, - _timeColumn: string = 'timestamp', + timeColumn: string = 'timestamp', where?: string, params?: unknown[] ): Promise> { - const columnsStr = columns.join(', '); - const whereClause = where ? `WHERE ${where}` : ''; + const validTable = assertIdentifier(table, 'table name'); + if (columns.length === 0) { + throw new Error('SELECT columns cannot be empty'); + } + const validColumns = columns.map(col => assertSelectColumn(col)); + const validInterval = assertSampleInterval(interval); + assertIdentifier(timeColumn, 'timestamp column'); - const sql = ` - SELECT ${columnsStr} - FROM ${table} - ${whereClause} - SAMPLE BY ${interval} - ALIGN TO CALENDAR - `; + let whereClause = ''; + const boundParams = params ? [...params] : []; + if (where !== undefined) { + const validatedWhere = rebaseWhereCondition(where, boundParams, 0); + whereClause = `WHERE ${validatedWhere}`; + } else if (boundParams.length > 0) { + throw new Error('params provided to sampleBy without a where clause'); + } - return await this.query(sql, params); + const sql = [ + `SELECT ${validColumns.join(', ')}`, + `FROM ${validTable}`, + whereClause, + `SAMPLE BY ${validInterval}`, + 'ALIGN TO CALENDAR', + ] + .filter(Boolean) + .join(' '); + + return await this.query(sql, boundParams.length > 0 ? boundParams : undefined); } /** - * Get latest values by symbol using LATEST BY + * Get latest rows per partition key using QuestDB 10.2.0 `LATEST ON`. + * Defaults to `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` otherwise. + * `options.where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `options.params`. */ async latestBy( - table: TableNames, + table: TableNames | string, columns: string | string[] = '*', - keyColumns: string | string[] = 'symbol' + keyColumns: string | string[] = 'symbol', + options?: LatestByOptions ): Promise> { - const columnsStr = Array.isArray(columns) ? columns.join(', ') : columns; - const keyColumnsStr = Array.isArray(keyColumns) ? keyColumns.join(', ') : keyColumns; + const cols = Array.isArray(columns) ? columns : [columns]; + if (cols.length === 0) { + throw new Error('SELECT columns cannot be empty'); + } + const keys = Array.isArray(keyColumns) ? keyColumns : [keyColumns]; - const sql = ` - SELECT ${columnsStr} - FROM ${table} - LATEST BY ${keyColumnsStr} - `; + const builder = this.queryBuilder().select(...cols).from(table); - return await this.query(sql); + if (options?.where !== undefined) { + builder.where(options.where, options.params); + } else if (options?.params && options.params.length > 0) { + throw new Error('params provided to latestBy without a where clause'); + } + + if (options?.timestampColumn !== undefined) { + builder.latestOn(options.timestampColumn, ...keys); + } else { + builder.latestBy(...keys); + } + + return await builder.execute(); } /** - * Execute ASOF JOIN for time-series correlation + * Execute ASOF JOIN for time-series correlation. + * `joinCondition` and `where` are treated as trusted SQL fragments. */ async asofJoin( - leftTable: TableNames, - rightTable: TableNames, + leftTable: TableNames | string, + rightTable: TableNames | string, joinCondition: string, columns?: string[], where?: string, params?: unknown[] ): Promise> { - const columnsStr = columns ? columns.join(', ') : '*'; - const whereClause = where ? `WHERE ${where}` : ''; + const validLeft = assertIdentifier(leftTable, 'left table name'); + const validRight = assertIdentifier(rightTable, 'right table name'); + if (typeof joinCondition !== 'string' || joinCondition.trim().length === 0) { + throw new Error('ASOF JOIN condition must be a non-empty SQL fragment'); + } + let columnsStr = '*'; + if (columns !== undefined) { + if (columns.length === 0) { + throw new Error('SELECT columns cannot be empty'); + } + columnsStr = columns.map(col => assertSelectColumn(col)).join(', '); + } - const sql = ` - SELECT ${columnsStr} - FROM ${leftTable} - ASOF JOIN ${rightTable} ON ${joinCondition} - ${whereClause} - `; + let whereClause = ''; + const boundParams = params ? [...params] : []; + if (where !== undefined) { + const validatedWhere = rebaseWhereCondition(where, boundParams, 0); + whereClause = `WHERE ${validatedWhere}`; + } else if (boundParams.length > 0) { + throw new Error('params provided to asofJoin without a where clause'); + } - return await this.query(sql, params); + const sql = [ + `SELECT ${columnsStr}`, + `FROM ${validLeft}`, + `ASOF JOIN ${validRight} ON ${joinCondition}`, + whereClause, + ] + .filter(Boolean) + .join(' '); + + return await this.query(sql, boundParams.length > 0 ? boundParams : undefined); } /** @@ -320,7 +511,7 @@ export class QuestDBClient { * Get table information */ async getTableInfo(tableName: string): Promise { - const result = await this.query(`SELECT * FROM table_columns WHERE table_name = ?`, [ + const result = await this.query(`SELECT * FROM table_columns WHERE table_name = $1`, [ tableName, ]); return result.rows; @@ -374,8 +565,9 @@ export class QuestDBClient { * Optimize table by rebuilding partitions */ async optimizeTable(tableName: string): Promise { - await this.query(`VACUUM TABLE ${tableName}`); - this.logger.debug(`Optimized table: ${tableName}`); + const validTable = assertIdentifier(tableName, 'table name'); + await this.query(`VACUUM TABLE ${validTable}`); + this.logger.debug(`Optimized table: ${validTable}`); } /** @@ -387,14 +579,19 @@ export class QuestDBClient { partitionBy: string = 'DAY', timestampColumn: string = 'timestamp' ): Promise { + const validTable = assertIdentifier(tableName, 'table name'); + const validTimestamp = assertIdentifier(timestampColumn, 'timestamp column'); + if (!ALLOWED_PARTITIONS.has(partitionBy)) { + throw new Error(`Invalid PARTITION BY value: "${String(partitionBy)}"`); + } const sql = ` - CREATE TABLE IF NOT EXISTS ${tableName} ( + CREATE TABLE IF NOT EXISTS ${validTable} ( ${columns} - ) TIMESTAMP(${timestampColumn}) PARTITION BY ${partitionBy} + ) TIMESTAMP(${validTimestamp}) PARTITION BY ${partitionBy} `; await this.query(sql); - this.logger.info(`Created table: ${tableName}`); + this.logger.info(`Created table: ${validTable}`); } /** diff --git a/libs/data/questdb/src/index.ts b/libs/data/questdb/src/index.ts index 46ab3687..94841d60 100644 --- a/libs/data/questdb/src/index.ts +++ b/libs/data/questdb/src/index.ts @@ -5,27 +5,39 @@ * InfluxDB Line Protocol, SQL queries, and PostgreSQL wire protocol. */ -export { QuestDBClient } from './client'; +export { QuestDBClient, readBars1m } from './client'; export { QuestDBHealthMonitor } from './health'; export { QuestDBQueryBuilder } from './query-builder'; export { QuestDBInfluxWriter } from './influx-writer'; -export { QuestDBSchemaManager } from './schema'; +export { + formatCreateTableSQL, + getM2IntradayDDL, + M2_INTRADAY_SCHEMAS, + QuestDBSchemaManager, + type M2IntradayTableName, +} from './schema'; // Types export type { + Bar1mRow, + ColumnSchema, + InsertResult, + LatestByOptions, + OHLCVData, + ParameterizedQuery, + PerformanceData, + QueryResult, QuestDBClientConfig, QuestDBConnectionOptions, QuestDBHealthStatus, QuestDBMetrics, - TableNames, - OHLCVData, - TradeData, + QuestDBQueryable, QuoteData, - IndicatorData, - PerformanceData, RiskMetrics, - QueryResult, - InsertResult, + TableNames, + TableSchema, + TradeData, + IndicatorData, } from './types'; // Note: Factory functions removed - instantiate directly with new QuestDBClient() diff --git a/libs/data/questdb/src/query-builder.ts b/libs/data/questdb/src/query-builder.ts index 7ebb56f1..f417ef88 100644 --- a/libs/data/questdb/src/query-builder.ts +++ b/libs/data/questdb/src/query-builder.ts @@ -1,32 +1,252 @@ import type { QueryResultRow } from 'pg'; import { getLogger } from '@stock-bot/logger'; -import type { QueryResult, TableNames, TimeRange } from './types'; +import type { + ParameterizedQuery, + QueryResult, + QuestDBQueryable, + TableNames, + TimeRange, +} from './types'; -// Interface to avoid circular dependency -interface QuestDBClientInterface { - query(sql: string, params?: unknown[]): Promise>; +const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/; +const SAMPLE_INTERVAL_RE = /^\d+[UTsmhdwMy]$/; + +/** + * Validate a SQL identifier (table, column, alias, or timestamp column). + */ +export function assertIdentifier(value: string, label: string): string { + if (typeof value !== 'string' || !IDENTIFIER_RE.test(value)) { + throw new Error(`Invalid ${label}: "${String(value)}"`); + } + return value; +} + +/** + * Validate a projection column (literal `*` or strict SQL identifier). + */ +export function assertSelectColumn(value: string): string { + if (value === '*') { + return value; + } + return assertIdentifier(value, 'SELECT column'); +} + +/** + * Validate a QuestDB SAMPLE BY interval (e.g. `1m`, `5m`, `1h`, `1d`). + */ +export function assertSampleInterval(value: string): string { + if (typeof value !== 'string' || !SAMPLE_INTERVAL_RE.test(value)) { + throw new Error(`Invalid SAMPLE BY interval: "${String(value)}"`); + } + return value; +} + +/** + * Validate a SQL sort direction. + */ +export function assertSortDirection(value: string): 'ASC' | 'DESC' { + if (value !== 'ASC' && value !== 'DESC') { + throw new Error(`Invalid ORDER BY direction: "${String(value)}"`); + } + return value; +} + +/** + * Resolve the default designated timestamp column for a QuestDB table. + */ +export function defaultTimestampColumnForTable(table: string): string { + switch (table) { + case 'bars_1m': + case 'fx_1m': + return 'ts'; + case 'bar_revisions': + return 'revised_at'; + default: + return 'timestamp'; + } +} + +/** + * Offset fragment-local `$1..$k` placeholders in a trusted SQL WHERE fragment by `offset`. + * Preserves repeated references and ignores `$n` inside single/double quotes and SQL comments. + * Rejects `$0`, out-of-range placeholders, and unused parameters. + */ +export function rebaseWhereCondition( + condition: string, + params: readonly unknown[] = [], + offset: number = 0 +): string { + if (typeof condition !== 'string' || condition.trim().length === 0) { + throw new Error('WHERE condition must be a non-empty SQL string'); + } + + const usedIndices = new Set(); + let out = ''; + let i = 0; + + while (i < condition.length) { + const ch = condition.charAt(i); + const next = condition.charAt(i + 1); + + // Single-quoted string literal ('...' with '' escape) + if (ch === "'") { + out += ch; + i += 1; + while (i < condition.length) { + const cur = condition.charAt(i); + out += cur; + i += 1; + if (cur === "'") { + if (condition.charAt(i) === "'") { + out += "'"; + i += 1; + } else { + break; + } + } + } + continue; + } + + // Double-quoted identifier ("..." with "" escape) + if (ch === '"') { + out += ch; + i += 1; + while (i < condition.length) { + const cur = condition.charAt(i); + out += cur; + i += 1; + if (cur === '"') { + if (condition.charAt(i) === '"') { + out += '"'; + i += 1; + } else { + break; + } + } + } + continue; + } + + // Line comment (-- ... \n) + if (ch === '-' && next === '-') { + out += '--'; + i += 2; + while (i < condition.length) { + const cur = condition.charAt(i); + out += cur; + i += 1; + if (cur === '\n') { + break; + } + } + continue; + } + + // Block comment (/* ... */) + if (ch === '/' && next === '*') { + out += '/*'; + i += 2; + while (i < condition.length) { + if (condition.charAt(i) === '*' && condition.charAt(i + 1) === '/') { + out += '*/'; + i += 2; + break; + } + out += condition.charAt(i); + i += 1; + } + continue; + } + + // Parameter placeholder ($1, $2, ..., $10, ...) + if (ch === '$' && next >= '0' && next <= '9') { + const prev = i > 0 ? condition.charAt(i - 1) : ''; + const isPartOfIdentifier = /[A-Za-z0-9_]/.test(prev); + if (!isPartOfIdentifier) { + let j = i + 1; + while (j < condition.length) { + const digit = condition.charAt(j); + if (digit < '0' || digit > '9') { + break; + } + j += 1; + } + const digits = condition.slice(i + 1, j); + const index = Number(digits); + if (!Number.isSafeInteger(index) || index < 1) { + throw new Error(`Invalid parameter placeholder $${digits}: placeholders are 1-based`); + } + if (index > params.length) { + throw new Error( + `Parameter placeholder $${index} is out of range for ${params.length} provided parameter(s)` + ); + } + usedIndices.add(index); + out += `$${offset + index}`; + i = j; + continue; + } + } + + out += ch; + i += 1; + } + + for (let idx = 1; idx <= params.length; idx += 1) { + if (!usedIndices.has(idx)) { + throw new Error(`Unused parameter at index ${idx} in WHERE condition`); + } + } + + return out; +} + +interface WherePredicate { + sql: string; + params: unknown[]; +} + +interface LatestOnClause { + timestampColumn?: string; + partitionBy: string[]; +} + +function assertValidDate(value: Date, label: string): Date { + if (!(value instanceof Date) || Number.isNaN(value.getTime())) { + throw new Error(`Invalid ${label}: expected a valid Date`); + } + return value; +} + +function assertPositiveInteger(value: number, label: string): number { + if (!Number.isInteger(value) || value <= 0) { + throw new Error(`Invalid ${label}: expected a positive integer, received ${String(value)}`); + } + return value; } /** * QuestDB Query Builder * - * Provides a fluent interface for building optimized time-series queries - * with support for QuestDB-specific functions and optimizations. + * Provides a fluent interface for building parameterized PGWire time-series queries + * with support for QuestDB 10.2.0 SQL clauses (`LATEST ON`, `SAMPLE BY`). */ export class QuestDBQueryBuilder { private readonly logger: ReturnType; private query!: { select: string[]; from: string; - where: string[]; + where: WherePredicate[]; groupBy: string[]; orderBy: string[]; limit?: number; sampleBy?: string; - latestBy?: string[]; + latestOn?: LatestOnClause; timeRange?: TimeRange; }; - constructor(private readonly client: QuestDBClientInterface) { + + constructor(private readonly client: QuestDBQueryable) { this.logger = getLogger('questdb-query-builder'); this.reset(); } @@ -41,193 +261,263 @@ export class QuestDBQueryBuilder { where: [], groupBy: [], orderBy: [], + limit: undefined, sampleBy: undefined, - latestBy: undefined, + latestOn: undefined, timeRange: undefined, }; return this; } + /** * Start a new query */ - public static create(client: QuestDBClientInterface): QuestDBQueryBuilder { + public static create(client: QuestDBQueryable): QuestDBQueryBuilder { return new QuestDBQueryBuilder(client); } /** - * Select columns + * Select columns (`*` or validated SQL identifiers) */ public select(...columns: string[]): QuestDBQueryBuilder { - this.query.select.push(...columns); + const validated = columns.map(col => assertSelectColumn(col)); + this.query.select.push(...validated); return this; } /** - * Select with aggregation functions + * Select with aggregation functions. + * Aliases are validated as SQL identifiers; aggregation expressions are treated as trusted SQL fragments. */ public selectAgg(aggregations: Record): QuestDBQueryBuilder { - Object.entries(aggregations).forEach(([alias, expression]) => { - this.query.select.push(`${expression} as ${alias}`); + const validatedEntries = Object.entries(aggregations).map(([alias, expression]) => { + const validAlias = assertIdentifier(alias, 'aggregation alias'); + if (typeof expression !== 'string' || expression.trim().length === 0) { + throw new Error(`Invalid aggregation expression for alias "${validAlias}"`); + } + return `${expression} as ${validAlias}`; + }); + this.query.select.push(...validatedEntries); + return this; + } + + /** + * From table (validated SQL identifier) + */ + public from(table: TableNames | string): QuestDBQueryBuilder { + this.query.from = assertIdentifier(table, 'table name'); + return this; + } + + /** + * Raw WHERE predicate (trusted SQL fragment escape hatch). + * Supports fragment-local `$1..$n` placeholders, which are renumbered automatically during build. + */ + public where(condition: string, params?: unknown[]): QuestDBQueryBuilder { + const boundParams = params ? [...params] : []; + // Validate fragment syntax and parameter indices eagerly before mutating builder state. + rebaseWhereCondition(condition, boundParams, 0); + this.query.where.push({ sql: condition, params: boundParams }); + return this; + } + + /** + * Where symbol equals (bound parameter) + */ + public whereSymbol(symbol: string): QuestDBQueryBuilder { + this.query.where.push({ sql: 'symbol = $1', params: [symbol] }); + return this; + } + + /** + * Where symbols in list (one bound parameter per element; rejects empty lists) + */ + public whereSymbolIn(symbols: string[]): QuestDBQueryBuilder { + if (symbols.length === 0) { + throw new Error('whereSymbolIn requires at least one symbol'); + } + const placeholders = symbols.map((_, index) => `$${index + 1}`).join(', '); + this.query.where.push({ + sql: `symbol IN (${placeholders})`, + params: [...symbols], }); return this; } /** - * From table - */ - public from(table: TableNames | string): QuestDBQueryBuilder { - this.query.from = table; - return this; - } - - /** - * Where condition - */ - public where(condition: string): QuestDBQueryBuilder { - this.query.where.push(condition); - return this; - } - - /** - * Where symbol equals - */ - public whereSymbol(symbol: string): QuestDBQueryBuilder { - this.query.where.push(`symbol = '${symbol}'`); - return this; - } - - /** - * Where symbols in list - */ - public whereSymbolIn(symbols: string[]): QuestDBQueryBuilder { - const symbolList = symbols.map(s => `'${s}'`).join(', '); - this.query.where.push(`symbol IN (${symbolList})`); - return this; - } - - /** - * Where exchange equals + * Where exchange equals (bound parameter) */ public whereExchange(exchange: string): QuestDBQueryBuilder { - this.query.where.push(`exchange = '${exchange}'`); + this.query.where.push({ sql: 'exchange = $1', params: [exchange] }); return this; } /** - * Time range filter + * Time range filter with inclusive bounds (bound UTC ISO-8601 parameters) */ public whereTimeRange(startTime: Date, endTime: Date): QuestDBQueryBuilder { - this.query.timeRange = { startTime, endTime }; - this.query.where.push( - `timestamp >= '${startTime.toISOString()}' AND timestamp <= '${endTime.toISOString()}'` - ); + const validStart = assertValidDate(startTime, 'startTime'); + const validEnd = assertValidDate(endTime, 'endTime'); + this.query.timeRange = { startTime: validStart, endTime: validEnd }; + this.query.where.push({ + sql: 'timestamp >= $1 AND timestamp <= $2', + params: [validStart.toISOString(), validEnd.toISOString()], + }); return this; } /** - * Last N hours + * Last N hours (bound negative hour offset) */ public whereLastHours(hours: number): QuestDBQueryBuilder { - this.query.where.push(`timestamp > dateadd('h', -${hours}, now())`); + const validHours = assertPositiveInteger(hours, 'hours'); + this.query.where.push({ + sql: "timestamp > dateadd('h', $1, now())", + params: [-validHours], + }); return this; } /** - * Last N days + * Last N days (bound negative day offset) */ public whereLastDays(days: number): QuestDBQueryBuilder { - this.query.where.push(`timestamp > dateadd('d', -${days}, now())`); + const validDays = assertPositiveInteger(days, 'days'); + this.query.where.push({ + sql: "timestamp > dateadd('d', $1, now())", + params: [-validDays], + }); return this; } /** - * Group by columns + * Group by columns (validated SQL identifiers) */ public groupBy(...columns: string[]): QuestDBQueryBuilder { - this.query.groupBy.push(...columns); + const validated = columns.map(col => assertIdentifier(col, 'GROUP BY column')); + this.query.groupBy.push(...validated); return this; } /** - * Order by column + * Order by column (validated identifier and direction) */ public orderBy(column: string, direction: 'ASC' | 'DESC' = 'ASC'): QuestDBQueryBuilder { - this.query.orderBy.push(`${column} ${direction}`); + const validColumn = assertIdentifier(column, 'ORDER BY column'); + const validDirection = assertSortDirection(direction); + this.query.orderBy.push(`${validColumn} ${validDirection}`); return this; } /** * Order by timestamp descending (most recent first) */ - public orderByTimeDesc(): QuestDBQueryBuilder { - this.query.orderBy.push('timestamp DESC'); + public orderByTimeDesc(timestampColumn: string = 'timestamp'): QuestDBQueryBuilder { + const validColumn = assertIdentifier(timestampColumn, 'ORDER BY column'); + this.query.orderBy.push(`${validColumn} DESC`); return this; } /** - * Limit results + * Limit results (bound non-negative integer parameter) */ public limit(count: number): QuestDBQueryBuilder { + if (!Number.isInteger(count) || count < 0) { + throw new Error(`Invalid LIMIT count: expected a non-negative integer, received ${String(count)}`); + } this.query.limit = count; return this; } /** - * Sample by time interval (QuestDB specific) + * Sample by time interval (QuestDB specific, validated interval) */ public sampleBy(interval: string): QuestDBQueryBuilder { - this.query.sampleBy = interval; + this.query.sampleBy = assertSampleInterval(interval); return this; } /** - * Latest by columns (QuestDB specific) + * QuestDB 10.2.0 `LATEST ON PARTITION BY ` with explicit timestamp column. */ - public latestBy(...columns: string[]): QuestDBQueryBuilder { - this.query.latestBy = columns; + public latestOn(timestampColumn: string, ...partitionByColumns: string[]): QuestDBQueryBuilder { + const validTs = assertIdentifier(timestampColumn, 'LATEST ON timestamp column'); + if (partitionByColumns.length === 0) { + throw new Error('latestOn requires at least one partition column'); + } + const validKeys = partitionByColumns.map(col => + assertIdentifier(col, 'LATEST ON partition column') + ); + this.query.latestOn = { + timestampColumn: validTs, + partitionBy: validKeys, + }; return this; } /** - * Build and execute the query + * Convenience wrapper emitting `LATEST ON PARTITION BY `. + * Uses `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` for legacy tables. + */ + public latestBy(...partitionByColumns: string[]): QuestDBQueryBuilder { + if (partitionByColumns.length === 0) { + throw new Error('latestBy requires at least one partition column'); + } + const validKeys = partitionByColumns.map(col => + assertIdentifier(col, 'LATEST ON partition column') + ); + this.query.latestOn = { + timestampColumn: undefined, + partitionBy: validKeys, + }; + return this; + } + + /** + * Build and execute the parameterized query */ public async execute(): Promise> { - const sql = this.build(); - this.logger.debug('Executing query', { sql }); - + let built: ParameterizedQuery | undefined; try { - const result = await this.client.query(sql); - this.reset(); // Reset for next query - return result; + built = this.buildParameterized(); + this.logger.debug('Executing query', { sql: built.sql, paramCount: built.params.length }); + return await this.client.query(built.sql, built.params); } catch (error) { - this.logger.error('Query execution failed', { sql, error }); - this.reset(); // Reset even on error + this.logger.error('Query execution failed', { sql: built?.sql, error }); throw error; + } finally { + this.reset(); } } /** - * Build the SQL query string + * Build the parameterized SQL query and ordered parameter list (`$1..$n`). */ - public build(): string { + public buildParameterized(): ParameterizedQuery { if (!this.query.from) { throw new Error('FROM clause is required'); } - if (this.query.select.length === 0) { - this.query.select.push('*'); - } + const selectColumns = this.query.select.length > 0 ? this.query.select : ['*']; + const params: unknown[] = []; - let sql = `SELECT ${this.query.select.join(', ')} FROM ${this.query.from}`; + let sql = `SELECT ${selectColumns.join(', ')} FROM ${this.query.from}`; - // Add WHERE clause + // Add WHERE clause with consecutively renumbered $1..$n placeholders if (this.query.where.length > 0) { - sql += ` WHERE ${this.query.where.join(' AND ')}`; + const renderedPredicates = this.query.where.map(predicate => { + const rebased = rebaseWhereCondition(predicate.sql, predicate.params, params.length); + params.push(...predicate.params); + return rebased; + }); + sql += ` WHERE ${renderedPredicates.join(' AND ')}`; } - // Add LATEST BY (QuestDB specific - must come before GROUP BY) - if (this.query.latestBy && this.query.latestBy.length > 0) { - sql += ` LATEST BY ${this.query.latestBy.join(', ')}`; + // Add LATEST ON (QuestDB 10.2.0 - placed after WHERE, before SAMPLE BY / GROUP BY) + if (this.query.latestOn && this.query.latestOn.partitionBy.length > 0) { + const tsColumn = + this.query.latestOn.timestampColumn ?? defaultTimestampColumnForTable(this.query.from); + sql += ` LATEST ON ${tsColumn} PARTITION BY ${this.query.latestOn.partitionBy.join(', ')}`; } // Add SAMPLE BY (QuestDB specific) @@ -245,27 +535,36 @@ export class QuestDBQueryBuilder { sql += ` ORDER BY ${this.query.orderBy.join(', ')}`; } - // Add LIMIT - if (this.query.limit) { - sql += ` LIMIT ${this.query.limit}`; + // Add LIMIT (bound parameter) + if (this.query.limit !== undefined) { + params.push(this.query.limit); + sql += ` LIMIT $${params.length}`; } - return sql; + return { sql, params }; } /** - * Get the built query without executing + * Build the SQL query string (placeholder view of `buildParameterized().sql`) + */ + public build(): string { + return this.buildParameterized().sql; + } + + /** + * Get the built query string without executing */ public toSQL(): string { return this.build(); } // Predefined query methods for common use cases + /** * Get latest OHLCV data for symbols */ public static latestOHLCV( - client: QuestDBClientInterface, + client: QuestDBQueryable, symbols: string[], exchange?: string ): QuestDBQueryBuilder { @@ -282,11 +581,12 @@ export class QuestDBQueryBuilder { return builder; } + /** * Get OHLCV data with time sampling */ public static ohlcvTimeSeries( - client: QuestDBClientInterface, + client: QuestDBQueryable, symbol: string, interval: string, hours: number = 24 @@ -305,11 +605,12 @@ export class QuestDBQueryBuilder { .sampleBy(interval) .orderByTimeDesc(); } + /** * Get market analytics data */ public static marketAnalytics( - client: QuestDBClientInterface, + client: QuestDBQueryable, symbols: string[], hours: number = 1 ): QuestDBQueryBuilder { @@ -329,11 +630,12 @@ export class QuestDBQueryBuilder { .orderBy('symbol') .orderByTimeDesc(); } + /** * Get performance metrics for a time range */ public static performanceMetrics( - client: QuestDBClientInterface, + client: QuestDBQueryable, startTime: Date, endTime: Date ): QuestDBQueryBuilder { @@ -348,11 +650,12 @@ export class QuestDBQueryBuilder { .whereTimeRange(startTime, endTime) .sampleBy('1m'); } + /** * Get trade execution data */ public static tradeExecutions( - client: QuestDBClientInterface, + client: QuestDBQueryable, symbol?: string, hours: number = 24 ): QuestDBQueryBuilder { diff --git a/libs/data/questdb/src/schema.ts b/libs/data/questdb/src/schema.ts index 55ca7e81..6e8458d2 100644 --- a/libs/data/questdb/src/schema.ts +++ b/libs/data/questdb/src/schema.ts @@ -1,11 +1,147 @@ import type { QueryResultRow } from 'pg'; import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; -import type { QueryResult, TableSchema } from './types'; +import { assertIdentifier } from './query-builder'; +import type { ColumnSchema, QuestDBQueryable, TableSchema } from './types'; -// Interface to avoid circular dependency -interface QuestDBClientInterface { - query(sql: string, params?: unknown[]): Promise>; +export type M2IntradayTableName = 'bars_1m' | 'fx_1m' | 'bar_revisions'; + +/** + * Contract schemas for M2 QuestDB 10.2.0 intraday tables (`design/DATA-CONTRACTS.md` §3.B). + * Kept opt-in (outside `QuestDBSchemaManager.initializeDatabase()`). + */ +export const M2_INTRADAY_SCHEMAS: Readonly> = { + bars_1m: { + tableName: 'bars_1m', + columns: [ + { name: 'listing_id', type: 'SYMBOL', capacity: 65536, cache: false }, + { name: 'open', type: 'DOUBLE' }, + { name: 'high', type: 'DOUBLE' }, + { name: 'low', type: 'DOUBLE' }, + { name: 'close', type: 'DOUBLE' }, + { name: 'volume', type: 'DOUBLE' }, + { name: 'vwap', type: 'DOUBLE' }, + { name: 'session', type: 'SYMBOL', capacity: 8, cache: true }, + { name: 'source', type: 'SYMBOL', capacity: 8, cache: true }, + { name: 'known_at', type: 'TIMESTAMP' }, + { name: 'ts', type: 'TIMESTAMP', designated: true }, + ], + partitionBy: 'MONTH', + wal: true, + dedupUpsertKeys: ['ts', 'listing_id'], + }, + fx_1m: { + tableName: 'fx_1m', + columns: [ + { name: 'pair', type: 'SYMBOL', capacity: 32, cache: true }, + { name: 'open', type: 'DOUBLE' }, + { name: 'high', type: 'DOUBLE' }, + { name: 'low', type: 'DOUBLE' }, + { name: 'close', type: 'DOUBLE' }, + { name: 'source', type: 'SYMBOL', capacity: 8, cache: true }, + { name: 'ts', type: 'TIMESTAMP', designated: true }, + ], + partitionBy: 'MONTH', + wal: true, + dedupUpsertKeys: ['ts', 'pair'], + }, + bar_revisions: { + tableName: 'bar_revisions', + columns: [ + { name: 'listing_id', type: 'SYMBOL', capacity: 65536, cache: false }, + { name: 'timeframe', type: 'SYMBOL', capacity: 8, cache: true }, + { name: 'bar_ts', type: 'TIMESTAMP' }, + { name: 'prev_close', type: 'DOUBLE' }, + { name: 'new_close', type: 'DOUBLE' }, + { name: 'prev_volume', type: 'DOUBLE' }, + { name: 'new_volume', type: 'DOUBLE' }, + { name: 'revised_at', type: 'TIMESTAMP', designated: true }, + ], + partitionBy: 'MONTH', + wal: true, + }, +}; + +function formatColumnDDL(col: ColumnSchema): string { + const name = assertIdentifier(col.name, 'column name'); + let def = `${name} ${col.type}`; + + if (col.type === 'SYMBOL') { + if (col.capacity !== undefined) { + if (!Number.isInteger(col.capacity) || col.capacity <= 0) { + throw new Error( + `Invalid SYMBOL capacity for column "${name}": expected positive integer, received ${String(col.capacity)}` + ); + } + def += ` CAPACITY ${col.capacity}`; + } + if (col.cache === true) { + def += ' CACHE'; + } else if (col.cache === false) { + def += ' NOCACHE'; + } + } + + return def; +} + +/** + * Pure QuestDB CREATE TABLE DDL formatter shared by legacy schemas and M2 contract tables. + */ +export function formatCreateTableSQL(schema: TableSchema): string { + const tableName = assertIdentifier(schema.tableName, 'table name'); + if (!schema.columns || schema.columns.length === 0) { + throw new Error('At least one column is required'); + } + + const columnNames = new Set(schema.columns.map(col => assertIdentifier(col.name, 'column name'))); + // QuestDB's column grammar has no PostgreSQL-style NOT NULL constraint. + // nullable remains descriptive metadata; the designated timestamp is declared below. + const columns = schema.columns.map(formatColumnDDL).join(', '); + + let sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns})`; + + const timestampColumns = schema.columns.filter(col => col.designated); + if (timestampColumns.length > 1) { + throw new Error('Only one designated timestamp column is allowed'); + } + const timestampColumn = timestampColumns[0]; + if (timestampColumn) { + sql += ` TIMESTAMP(${assertIdentifier(timestampColumn.name, 'designated timestamp column')})`; + } + + if (schema.partitionBy) { + sql += ` PARTITION BY ${schema.partitionBy}`; + } + + if (schema.wal) { + sql += ' WAL'; + } + + if (schema.dedupUpsertKeys && schema.dedupUpsertKeys.length > 0) { + const keys = schema.dedupUpsertKeys.map(key => { + const validKey = assertIdentifier(key, 'DEDUP UPSERT key'); + if (!columnNames.has(validKey)) { + throw new Error(`DEDUP UPSERT key "${validKey}" does not exist on table "${tableName}"`); + } + return validKey; + }); + sql += ` DEDUP UPSERT KEYS(${keys.join(', ')})`; + } + + return sql; +} + +/** + * Return the QuestDB 10.2.0 DDL statements for `bars_1m`, `fx_1m`, and `bar_revisions`. + * Pure offline helper; requires no database connection. + */ +export function getM2IntradayDDL(): Record { + return { + bars_1m: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.bars_1m), + fx_1m: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.fx_1m), + bar_revisions: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.bar_revisions), + }; } /** @@ -17,7 +153,7 @@ interface QuestDBClientInterface { export class QuestDBSchemaManager { private readonly logger: ReturnType; private readonly schemas: Map = new Map(); - constructor(private readonly client: QuestDBClientInterface) { + constructor(private readonly client: QuestDBQueryable) { this.logger = getLogger('questdb-schema-manager'); this.initializeSchemas(); } @@ -195,13 +331,14 @@ export class QuestDBSchemaManager { * Drop a table */ public async dropTable(tableName: string): Promise { - const sql = `DROP TABLE IF EXISTS ${tableName}`; + const validTable = assertIdentifier(tableName, 'table name'); + const sql = `DROP TABLE IF EXISTS ${validTable}`; try { await this.client.query(sql); - this.logger.warn(`Table ${tableName} dropped`); + this.logger.warn(`Table ${validTable} dropped`); } catch (error) { - this.logger.error(`Failed to drop table ${tableName}`, error); + this.logger.error(`Failed to drop table ${validTable}`, error); throw error; } } @@ -211,13 +348,12 @@ export class QuestDBSchemaManager { */ public async tableExists(tableName: string): Promise { try { - const result = await this.client.query(` - SELECT COUNT(*) as count - FROM information_schema.tables - WHERE table_name = '${tableName}' - `); + const result = await this.client.query<{ count: number | string }>( + 'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1', + [tableName] + ); - return result.rows.length > 0 && at(result.rows, 0).count > 0; + return result.rows.length > 0 && Number(at(result.rows, 0).count) > 0; } catch (error) { this.logger.error(`Error checking if table exists: ${tableName}`, error); return false; @@ -269,18 +405,19 @@ export class QuestDBSchemaManager { * Get table statistics */ public async getTableStats(tableName: string): Promise { + const validTable = assertIdentifier(tableName, 'table name'); try { const result = await this.client.query(` SELECT COUNT(*) as row_count, MIN(timestamp) as min_timestamp, MAX(timestamp) as max_timestamp - FROM ${tableName} + FROM ${validTable} `); return result.rows[0] || {}; } catch (error) { - this.logger.error(`Failed to get table stats for ${tableName}`, error); + this.logger.error(`Failed to get table stats for ${validTable}`, error); throw error; } } @@ -289,11 +426,12 @@ export class QuestDBSchemaManager { * Truncate table (remove all data but keep structure) */ public async truncateTable(tableName: string): Promise { + const validTable = assertIdentifier(tableName, 'table name'); try { - await this.client.query(`TRUNCATE TABLE ${tableName}`); - this.logger.warn(`Table ${tableName} truncated`); + await this.client.query(`TRUNCATE TABLE ${validTable}`); + this.logger.warn(`Table ${validTable} truncated`); } catch (error) { - this.logger.error(`Failed to truncate table ${tableName}`, error); + this.logger.error(`Failed to truncate table ${validTable}`, error); throw error; } } @@ -311,27 +449,7 @@ export class QuestDBSchemaManager { * Build CREATE TABLE SQL statement */ private buildCreateTableSQL(schema: TableSchema): string { - // QuestDB's column grammar has no PostgreSQL-style NOT NULL constraint. - // nullable remains descriptive metadata; the designated timestamp is declared - // below. See https://questdb.com/docs/query/sql/create-table/. - const columns = schema.columns - .map(col => `${col.name} ${col.type}`) - .join(', '); - - let sql = `CREATE TABLE IF NOT EXISTS ${schema.tableName} (${columns})`; - - // Add designated timestamp - const timestampColumn = schema.columns.find(col => col.designated); - if (timestampColumn) { - sql += ` TIMESTAMP(${timestampColumn.name})`; - } - - // Add partition by - if (schema.partitionBy) { - sql += ` PARTITION BY ${schema.partitionBy}`; - } - - return sql; + return formatCreateTableSQL(schema); } /** diff --git a/libs/data/questdb/src/types.ts b/libs/data/questdb/src/types.ts index 5aec03c7..67a2f4eb 100644 --- a/libs/data/questdb/src/types.ts +++ b/libs/data/questdb/src/types.ts @@ -62,7 +62,52 @@ export type TableNames = | 'risk_metrics' | 'market_events' | 'strategy_signals' - | 'portfolio_snapshots'; + | 'portfolio_snapshots' + | 'bars_1m' + | 'fx_1m' + | 'bar_revisions'; + +/** + * Shared minimal query executor interface for QuestDB helpers. + */ +export interface QuestDBQueryable { + query(sql: string, params?: unknown[]): Promise>; +} + +/** + * Parameterized PGWire SQL query and ordered bound parameters ($1..$n). + */ +export interface ParameterizedQuery { + sql: string; + params: unknown[]; +} + +/** + * Options for QuestDBClient.latestBy(). + */ +export interface LatestByOptions { + timestampColumn?: string; + where?: string; + params?: unknown[]; +} + +/** + * Typed 1-minute bar row returned from QuestDB `bars_1m`. + * `listing_id` is stored as decimal string SYMBOL in QuestDB and converted to INT32 at read boundary. + */ +export interface Bar1mRow { + listing_id: number; + open: number; + high: number; + low: number; + close: number; + volume: number; + vwap: number | null; + session: string | null; + source: string | null; + known_at: Date; + ts: Date; +} /** * Time-Series Data Types @@ -214,12 +259,14 @@ export interface TableSchema { tableName: string; columns: ColumnSchema[]; partitionBy?: 'NONE' | 'HOUR' | 'DAY' | 'MONTH' | 'YEAR'; + wal?: boolean; + dedupUpsertKeys?: string[]; orderBy?: string[]; indices?: IndexDefinition[]; dedup?: boolean; } -interface ColumnSchema { +export interface ColumnSchema { name: string; type: | 'SYMBOL' @@ -235,6 +282,7 @@ interface ColumnSchema { nullable?: boolean; designated?: boolean; // For designated timestamp column capacity?: number; // For SYMBOL type + cache?: boolean; // For SYMBOL type: true -> CACHE, false -> NOCACHE indexed?: boolean; } diff --git a/libs/data/questdb/test/questdb-query-layer.test.ts b/libs/data/questdb/test/questdb-query-layer.test.ts new file mode 100644 index 00000000..886c0f2a --- /dev/null +++ b/libs/data/questdb/test/questdb-query-layer.test.ts @@ -0,0 +1,526 @@ +import { describe, expect, it } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { QueryResultRow } from 'pg'; +import { + formatCreateTableSQL, + getM2IntradayDDL, + QuestDBClient, + QuestDBQueryBuilder, + QuestDBSchemaManager, + readBars1m, + type QueryResult, + type QuestDBQueryable, +} from '../src'; + +interface RecordedQuery { + sql: string; + params: unknown[] | undefined; +} + +class FakeQuestDBClient implements QuestDBQueryable { + public readonly calls: RecordedQuery[] = []; + private nextRows: unknown[] = []; + private nextError: Error | null = null; + + public setRows(rows: unknown[]): void { + this.nextRows = rows; + } + + public failNext(error: Error): void { + this.nextError = error; + } + + public async query( + sql: string, + params?: unknown[] + ): Promise> { + this.calls.push({ sql, params }); + if (this.nextError) { + const err = this.nextError; + this.nextError = null; + throw err; + } + return { + rows: this.nextRows as T[], + rowCount: this.nextRows.length, + executionTime: 1, + }; + } +} + +function createClientWithFakeQuery(fake: FakeQuestDBClient): QuestDBClient { + const client = new QuestDBClient( + { + host: 'questdb.test.local', + httpPort: 9000, + pgPort: 8812, + influxPort: 9009, + database: 'qdb', + }, + { + info: () => {}, + warn: () => {}, + error: () => {}, + debug: () => {}, + } + ); + // Route PGWire query execution to the recording fake without opening a network socket. + (client as unknown as { query: QuestDBQueryable['query'] }).query = fake.query.bind(fake); + return client; +} + +function normalizeSql(sql: string): string { + return sql + .replace(/--[^\n]*/g, '') + .replace(/;/g, '') + .replace(/\s+/g, ' ') + .replace(/\(\s+/g, '(') + .replace(/\s+\)/g, ')') + .replace(/\s+,/g, ',') + .trim(); +} + +describe('QuestDB 10.2.0 query layer', () => { + describe('LATEST ON clause generation', () => { + it('emits LATEST ON after WHERE with explicit timestamp and partition key', async () => { + const fake = new FakeQuestDBClient(); + const builder = QuestDBQueryBuilder.create(fake) + .select('listing_id', 'ts', 'close') + .from('bars_1m') + .where('listing_id = $1', ['1042']) + .latestOn('ts', 'listing_id'); + + const built = builder.buildParameterized(); + expect(built.sql).toBe( + 'SELECT listing_id, ts, close FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id' + ); + expect(built.params).toEqual(['1042']); + expect(builder.build()).toBe(built.sql); + expect(builder.toSQL()).toBe(built.sql); + + await builder.execute(); + expect(fake.calls).toHaveLength(1); + expect(fake.calls[0]).toEqual({ + sql: built.sql, + params: ['1042'], + }); + }); + + it('preserves multi-key PARTITION BY ordering', () => { + const fake = new FakeQuestDBClient(); + const sql = QuestDBQueryBuilder.create(fake) + .select('listing_id', 'session', 'ts', 'close') + .from('bars_1m') + .latestOn('ts', 'listing_id', 'session') + .build(); + + expect(sql).toBe( + 'SELECT listing_id, session, ts, close FROM bars_1m LATEST ON ts PARTITION BY listing_id, session' + ); + }); + + it('resolves table-appropriate default timestamps for latestBy()', () => { + const fake = new FakeQuestDBClient(); + + expect(QuestDBQueryBuilder.create(fake).from('bars_1m').latestBy('listing_id').build()).toBe( + 'SELECT * FROM bars_1m LATEST ON ts PARTITION BY listing_id' + ); + expect(QuestDBQueryBuilder.create(fake).from('fx_1m').latestBy('pair').build()).toBe( + 'SELECT * FROM fx_1m LATEST ON ts PARTITION BY pair' + ); + expect( + QuestDBQueryBuilder.create(fake).from('bar_revisions').latestBy('listing_id').build() + ).toBe('SELECT * FROM bar_revisions LATEST ON revised_at PARTITION BY listing_id'); + expect(QuestDBQueryBuilder.create(fake).from('ohlcv_data').latestBy('symbol').build()).toBe( + 'SELECT * FROM ohlcv_data LATEST ON timestamp PARTITION BY symbol' + ); + }); + + it('routes QuestDBClient.latestBy() through the builder with timestamp override and bound filters', async () => { + const fake = new FakeQuestDBClient(); + const client = createClientWithFakeQuery(fake); + + await client.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', { + where: 'session = $1', + params: ['RTH'], + }); + await client.latestBy('bar_revisions', '*', ['listing_id', 'timeframe']); + await client.latestBy('bars_1m', 'close', 'listing_id', { + timestampColumn: 'known_at', + }); + + expect(fake.calls).toEqual([ + { + sql: 'SELECT listing_id, ts, close FROM bars_1m WHERE session = $1 LATEST ON ts PARTITION BY listing_id', + params: ['RTH'], + }, + { + sql: 'SELECT * FROM bar_revisions LATEST ON revised_at PARTITION BY listing_id, timeframe', + params: [], + }, + { + sql: 'SELECT close FROM bars_1m LATEST ON known_at PARTITION BY listing_id', + params: [], + }, + ]); + }); + }); + + describe('parameterized predicates and placeholder renumbering', () => { + it('binds all filter values and keeps hostile input out of SQL', () => { + const fake = new FakeQuestDBClient(); + const hostile = "x' OR '1'='1"; + const start = new Date('2024-01-02T14:30:00.000Z'); + const end = new Date('2024-01-02T15:30:00.000Z'); + + const { sql, params } = QuestDBQueryBuilder.create(fake) + .select('symbol', 'exchange', 'timestamp', 'close') + .from('ohlcv_data') + .whereSymbol(hostile) + .whereSymbolIn(['AAPL', 'MSFT']) + .whereExchange('NASDAQ') + .whereTimeRange(start, end) + .whereLastHours(6) + .whereLastDays(2) + .limit(25) + .buildParameterized(); + + expect(sql).toBe( + 'SELECT symbol, exchange, timestamp, close FROM ohlcv_data ' + + "WHERE symbol = $1 AND symbol IN ($2, $3) AND exchange = $4 AND timestamp >= $5 AND timestamp <= $6 AND timestamp > dateadd('h', $7, now()) AND timestamp > dateadd('d', $8, now()) " + + 'LIMIT $9' + ); + expect(sql).not.toContain(hostile); + expect(sql).not.toContain('AAPL'); + expect(sql).not.toContain('NASDAQ'); + expect(params).toEqual([ + hostile, + 'AAPL', + 'MSFT', + 'NASDAQ', + '2024-01-02T14:30:00.000Z', + '2024-01-02T15:30:00.000Z', + -6, + -2, + 25, + ]); + }); + + it('renumbers raw where() fragments consecutively across repeated, multi-digit, quoted, and commented placeholders', () => { + const fake = new FakeQuestDBClient(); + const tenParams = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p10']; + const tenPred = + 'c1=$1 AND c2=$2 AND c3=$3 AND c4=$4 AND c5=$5 AND c6=$6 AND c7=$7 AND c8=$8 AND c9=$9 AND c10=$10'; + + const { sql, params } = QuestDBQueryBuilder.create(fake) + .from('ohlcv_data') + .limit(10) + .whereSymbol('SPY') + .where( + "note = '$1' AND \"col_$2\" = $1 AND close >= $1 -- ignore $3\n/* ignore $4 */ AND volume > $2", + [100.5, 5000] + ) + .where(tenPred, tenParams) + .buildParameterized(); + + expect(sql).toBe( + 'SELECT * FROM ohlcv_data WHERE symbol = $1 ' + + 'AND note = \'$1\' AND "col_$2" = $2 AND close >= $2 -- ignore $3\n/* ignore $4 */ AND volume > $3 ' + + 'AND c1=$4 AND c2=$5 AND c3=$6 AND c4=$7 AND c5=$8 AND c6=$9 AND c7=$10 AND c8=$11 AND c9=$12 AND c10=$13 ' + + 'LIMIT $14' + ); + expect(params).toHaveLength(14); + expect(params).toEqual(['SPY', 100.5, 5000, ...tenParams, 10]); + }); + + it('rejects empty IN lists and malformed/mismatched where() placeholders before querying', () => { + const fake = new FakeQuestDBClient(); + + expect(() => QuestDBQueryBuilder.create(fake).whereSymbolIn([])).toThrow( + /at least one symbol/i + ); + expect(() => QuestDBQueryBuilder.create(fake).where('close > $0', [1])).toThrow(/1-based/i); + expect(() => QuestDBQueryBuilder.create(fake).where('close > $2', [1])).toThrow( + /out of range/i + ); + expect(() => QuestDBQueryBuilder.create(fake).where('close > $1', [1, 2])).toThrow( + /Unused parameter/i + ); + expect(() => QuestDBQueryBuilder.create(fake).where('close > 10', [1])).toThrow( + /Unused parameter/i + ); + expect(() => QuestDBQueryBuilder.create(fake).where(' ')).toThrow(/non-empty/i); + + expect(fake.calls).toHaveLength(0); + }); + + it('resets builder cleanly for reuse after execution and after rejection', async () => { + const fake = new FakeQuestDBClient(); + const builder = QuestDBQueryBuilder.create(fake); + + fake.failNext(new Error('simulated wire failure')); + await expect(builder.from('ohlcv_data').whereSymbol('AAPL').execute()).rejects.toThrow( + 'simulated wire failure' + ); + + // Builder must be reset after failed execute() + const nextBuilt = builder.select('close').from('bars_1m').where('listing_id = $1', ['7']).buildParameterized(); + expect(nextBuilt).toEqual({ + sql: 'SELECT close FROM bars_1m WHERE listing_id = $1', + params: ['7'], + }); + + await builder.execute(); + expect(fake.calls).toHaveLength(2); + expect(fake.calls[1]).toEqual(nextBuilt); + // Builder is reset again after successful execute() + expect(() => builder.build()).toThrow('FROM clause is required'); + }); + }); + + describe('identifier and interval validation', () => { + it('rejects hostile table, column, alias, latestOn, sort, and sampleBy inputs before querying', async () => { + const fake = new FakeQuestDBClient(); + const client = createClientWithFakeQuery(fake); + + expect(() => QuestDBQueryBuilder.create(fake).from('bars_1m; DROP TABLE x')).toThrow( + /Invalid table name/i + ); + expect(() => QuestDBQueryBuilder.create(fake).select('close; --')).toThrow( + /Invalid SELECT column/i + ); + expect(() => + QuestDBQueryBuilder.create(fake).selectAgg({ 'bad alias': 'avg(close)' }) + ).toThrow(/Invalid aggregation alias/i); + expect(() => QuestDBQueryBuilder.create(fake).latestOn('ts; --', 'listing_id')).toThrow( + /Invalid LATEST ON timestamp column/i + ); + expect(() => QuestDBQueryBuilder.create(fake).latestOn('ts', 'listing_id; DROP')).toThrow( + /Invalid LATEST ON partition column/i + ); + expect(() => QuestDBQueryBuilder.create(fake).orderBy('ts', 'UP' as 'ASC')).toThrow( + /Invalid ORDER BY direction/i + ); + expect(() => QuestDBQueryBuilder.create(fake).sampleBy('1h; DROP TABLE x')).toThrow( + /Invalid SAMPLE BY interval/i + ); + expect(() => QuestDBQueryBuilder.create(fake).sampleBy('1x')).toThrow( + /Invalid SAMPLE BY interval/i + ); + + await expect( + client.sampleBy('bars_1m', ['ts', 'close'], 'bad_interval') + ).rejects.toThrow(/Invalid SAMPLE BY interval/i); + await expect( + client.latestBy('bars_1m; DROP TABLE x', '*', 'listing_id') + ).rejects.toThrow(/Invalid table name/i); + await expect( + client.asofJoin('bars_1m', 'fx_1m; DROP', 'bars_1m.ts = fx_1m.ts') + ).rejects.toThrow(/Invalid right table name/i); + + expect(fake.calls).toHaveLength(0); + }); + + it('binds table name in QuestDBSchemaManager.tableExists() via tables()', async () => { + const fake = new FakeQuestDBClient(); + fake.setRows([{ count: 1 }]); + const manager = new QuestDBSchemaManager(fake); + + const hostileTable = "bars_1m' OR '1'='1"; + const exists = await manager.tableExists(hostileTable); + + expect(exists).toBe(true); + expect(fake.calls).toHaveLength(1); + expect(fake.calls[0]).toEqual({ + sql: 'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1', + params: [hostileTable], + }); + }); + }); + + describe('M2 intraday contract DDL', () => { + it('matches design/DATA-CONTRACTS.md §3.B exactly after whitespace and comment normalization', () => { + const contractPath = resolve(import.meta.dir, '../../../../design/DATA-CONTRACTS.md'); + const contractDoc = readFileSync(contractPath, 'utf8'); + const sectionMatch = contractDoc.match( + /### B\. QuestDB `10\.2\.0`[\s\S]*?```sql\n([\s\S]*?)```/ + ); + expect(sectionMatch).not.toBeNull(); + + const contractStatements = sectionMatch![1]! + .split(';') + .map(normalizeSql) + .filter(Boolean); + expect(contractStatements).toHaveLength(3); + + const generated = getM2IntradayDDL(); + expect(normalizeSql(generated.bars_1m)).toBe(contractStatements[0]!); + expect(normalizeSql(generated.fx_1m)).toBe(contractStatements[1]!); + expect(normalizeSql(generated.bar_revisions)).toBe(contractStatements[2]!); + + expect(generated.bars_1m).toContain('listing_id SYMBOL CAPACITY 65536 NOCACHE'); + expect(generated.bars_1m).toContain('session SYMBOL CAPACITY 8 CACHE'); + expect(generated.bars_1m).toContain('source SYMBOL CAPACITY 8 CACHE'); + expect(generated.bars_1m).toContain('TIMESTAMP(ts) PARTITION BY MONTH WAL'); + expect(generated.bars_1m).toContain('DEDUP UPSERT KEYS(ts, listing_id)'); + + expect(generated.fx_1m).toContain('pair SYMBOL CAPACITY 32 CACHE'); + expect(generated.fx_1m).toContain('TIMESTAMP(ts) PARTITION BY MONTH WAL'); + expect(generated.fx_1m).toContain('DEDUP UPSERT KEYS(ts, pair)'); + + expect(generated.bar_revisions).toContain('listing_id SYMBOL CAPACITY 65536 NOCACHE'); + expect(generated.bar_revisions).toContain('TIMESTAMP(revised_at) PARTITION BY MONTH WAL'); + expect(generated.bar_revisions).not.toContain('DEDUP'); + }); + + it('keeps M2 intraday tables opt-in outside legacy startup initialization', () => { + const fake = new FakeQuestDBClient(); + const manager = new QuestDBSchemaManager(fake); + const startupNames = manager.getSchemaNames(); + + expect(startupNames).not.toContain('bars_1m'); + expect(startupNames).not.toContain('fx_1m'); + expect(startupNames).not.toContain('bar_revisions'); + + // Shared formatter also validates dedup keys exist on the table + expect(() => + formatCreateTableSQL({ + tableName: 'bad_table', + columns: [{ name: 'ts', type: 'TIMESTAMP', designated: true }], + dedupUpsertKeys: ['ts', 'missing_col'], + }) + ).toThrow(/does not exist/i); + }); + }); + + describe('readBars1m storage reader', () => { + it('sends one parameterized [from, to) query and converts decimal-string listing_id to INT32', async () => { + const fake = new FakeQuestDBClient(); + const fixtureRows = [ + { + listing_id: '1042', + open: 185.1, + high: 185.5, + low: 184.9, + close: 185.4, + volume: 12500, + vwap: 185.28, + session: 'RTH', + source: 'eod_unadj', + known_at: new Date('2024-01-02T14:31:00.000Z'), + ts: new Date('2024-01-02T14:30:00.000Z'), + }, + { + listing_id: '1042', + open: 185.4, + high: 185.6, + low: 185.3, + close: 185.55, + volume: 0, + vwap: null, + session: 'RTH', + source: 'ib_live', + known_at: '2024-01-02T14:32:00.000Z', + ts: '2024-01-02T14:31:00.000Z', + }, + ]; + fake.setRows(fixtureRows); + + const from = new Date('2024-01-02T14:30:00.000Z'); + const to = new Date('2024-01-02T14:32:00.000Z'); + + const firstRead = await readBars1m(fake, 1042, from, to); + const secondRead = await readBars1m(fake, 1042, from, to); + + expect(fake.calls).toHaveLength(2); + expect(fake.calls[0]).toEqual({ + sql: + 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, known_at, ts ' + + 'FROM bars_1m ' + + 'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' + + 'ORDER BY ts ASC', + params: ['1042', '2024-01-02T14:30:00.000Z', '2024-01-02T14:32:00.000Z'], + }); + + expect(firstRead).toEqual(secondRead); + expect(firstRead).toEqual([ + { + listing_id: 1042, + open: 185.1, + high: 185.5, + low: 184.9, + close: 185.4, + volume: 12500, + vwap: 185.28, + session: 'RTH', + source: 'eod_unadj', + known_at: new Date('2024-01-02T14:31:00.000Z'), + ts: new Date('2024-01-02T14:30:00.000Z'), + }, + { + listing_id: 1042, + open: 185.4, + high: 185.6, + low: 185.3, + close: 185.55, + volume: 0, + vwap: null, + session: 'RTH', + source: 'ib_live', + known_at: new Date('2024-01-02T14:32:00.000Z'), + ts: new Date('2024-01-02T14:31:00.000Z'), + }, + ]); + expect(typeof firstRead[0]!.listing_id).toBe('number'); + }); + + it('returns empty array when no bars exist in range', async () => { + const fake = new FakeQuestDBClient(); + fake.setRows([]); + + const rows = await readBars1m( + fake, + 0, + '2024-01-02T14:30:00.000Z', + '2024-01-02T14:35:00.000Z' + ); + + expect(rows).toEqual([]); + expect(fake.calls[0]?.params).toEqual([ + '0', + '2024-01-02T14:30:00.000Z', + '2024-01-02T14:35:00.000Z', + ]); + }); + + it('rejects invalid input listingIds and malformed returned SYMBOL listing_id values', async () => { + const fake = new FakeQuestDBClient(); + const from = new Date('2024-01-02T14:30:00.000Z'); + const to = new Date('2024-01-02T14:35:00.000Z'); + + await expect(readBars1m(fake, 1.5, from, to)).rejects.toThrow(/INT32/i); + await expect(readBars1m(fake, 2147483648, from, to)).rejects.toThrow(/INT32/i); + expect(fake.calls).toHaveLength(0); + + for (const badSymbol of ['abc', '007', '12.5', '2147483648', null]) { + fake.setRows([ + { + listing_id: badSymbol, + open: 1, + high: 2, + low: 1, + close: 2, + volume: 10, + vwap: 1.5, + session: 'RTH', + source: 'eod_unadj', + known_at: from, + ts: from, + }, + ]); + await expect(readBars1m(fake, 42, from, to)).rejects.toThrow(/listing_id SYMBOL/i); + } + }); + }); +}); diff --git a/libs/data/questdb/test/questdb.test.ts b/libs/data/questdb/test/questdb.test.ts index 09c5377d..80a682f3 100644 --- a/libs/data/questdb/test/questdb.test.ts +++ b/libs/data/questdb/test/questdb.test.ts @@ -252,19 +252,20 @@ describe('QuestDB', () => { const builder = new QuestDBQueryBuilder(mockClient); - const query = builder + const { sql, params } = builder .select('symbol', 'close', 'volume') .from('ohlcv_data') .whereSymbol('AAPL') .orderBy('timestamp', 'DESC') .limit(100) - .build(); + .buildParameterized(); - expect(query).toContain('SELECT symbol, close, volume'); - expect(query).toContain('FROM ohlcv_data'); - expect(query).toContain("symbol = 'AAPL'"); - expect(query).toContain('ORDER BY timestamp DESC'); - expect(query).toContain('LIMIT 100'); + expect(sql).toContain('SELECT symbol, close, volume'); + expect(sql).toContain('FROM ohlcv_data'); + expect(sql).toContain('symbol = $1'); + expect(sql).toContain('ORDER BY timestamp DESC'); + expect(sql).toContain('LIMIT $2'); + expect(params).toEqual(['AAPL', 100]); }); it('should build query with time range', () => { From a67d9c164467c31fb180e0476bdd39ad2c4a3ef2 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 06:26:06 -0500 Subject: [PATCH 05/36] =?UTF-8?q?T-135:=20M2.3b=20=E2=80=94=20`libs/data/q?= =?UTF-8?q?uestdb`=20query=20layer=20for=20QuestDB=2010.2.0:=20`LATEST=20O?= =?UTF-8?q?N`=20+=20parameterized=20PGWire=20queries=20+=20contract=20DDL?= =?UTF-8?q?=20for=20`bars=5F1m`=20/=20`fx=5F1m`=20/=20`bar=5Frevisions`=20?= =?UTF-8?q?(pure,=20no=20live=20QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/data/questdb/README.md | 4 +- libs/data/questdb/src/client.ts | 82 ++++++--- libs/data/questdb/src/query-builder.ts | 22 ++- libs/data/questdb/src/types.ts | 8 +- .../questdb/test/questdb-query-layer.test.ts | 156 ++++++++++++++++-- 5 files changed, 232 insertions(+), 40 deletions(-) diff --git a/libs/data/questdb/README.md b/libs/data/questdb/README.md index 52227c3b..55476969 100644 --- a/libs/data/questdb/README.md +++ b/libs/data/questdb/README.md @@ -7,7 +7,7 @@ A QuestDB 10.2.0 client library for the Stock Bot trading platform, optimized fo - **Time-Series Optimized**: Built for QuestDB 10.2.0 (`LATEST ON`, `SAMPLE BY`, `ASOF JOIN`) - **Parameterized PGWire Queries**: All value filters bind `$1..$n` placeholders; structured identifiers and intervals are strictly validated - **Contract DDL**: Offline DDL generator for M2 intraday tables (`bars_1m`, `fx_1m`, `bar_revisions`) with `SYMBOL CAPACITY ... [NO]CACHE`, `PARTITION BY MONTH WAL`, and `DEDUP UPSERT KEYS` -- **Typed `bars_1m` Range Reader**: `readBars1m()` binds `listing_id` as canonical decimal string and returns `INT32` `listing_id` values with `known_at` preserved +- **Typed `bars_1m` Range Reader**: `readBars1m()` binds `listing_id` as canonical decimal string, returns `INT32` `listing_id` values, and projects `ts` and `known_at` as lossless UTC epoch microseconds (`bigint`) - **InfluxDB Line Protocol**: Batch ingestion writer - **Health Monitoring**: Connection health monitoring and metrics @@ -78,7 +78,7 @@ const bars = await readBars1m( ); ``` -> **Storage-layer read semantics**: `readBars1m` returns all stored bars in `[from, to)` and preserves `known_at` on each row without applying replay cutoffs. Research callers (`MarketDataStore`) remain responsible for as-of availability filtering and Vault fencing. +> **Storage-layer read semantics**: `readBars1m` returns all stored bars in `[from, to)` with `ts` and `known_at` projected via `CAST(... AS LONG)` as UTC epoch microseconds (`bigint`, preserving all 6 fractional digits independent of host timezone) without applying replay cutoffs. Research callers (`MarketDataStore`) remain responsible for as-of availability filtering and Vault fencing. ### M2 Intraday Contract DDL (Offline) diff --git a/libs/data/questdb/src/client.ts b/libs/data/questdb/src/client.ts index 4cb6a845..84e63f43 100644 --- a/libs/data/questdb/src/client.ts +++ b/libs/data/questdb/src/client.ts @@ -24,6 +24,8 @@ import type { const INT32_MIN = -2147483648; const INT32_MAX = 2147483647; const CANONICAL_INT_RE = /^-?(?:0|[1-9]\d*)$/; +const ISO_UTC_OR_OFFSET_RE = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|([+-])(\d{2}):(\d{2}))$/; const ALLOWED_PARTITIONS = new Set(['NONE', 'HOUR', 'DAY', 'MONTH', 'YEAR']); function formatInt32ListingId(listingId: number): string { @@ -53,29 +55,67 @@ function toUtcIsoString(value: Date | string, label: string): string { } return value.toISOString(); } - if (typeof value === 'string' && value.trim().length > 0) { - const parsed = new Date(value); - if (!Number.isNaN(parsed.getTime())) { - return parsed.toISOString(); + if (typeof value === 'string') { + const trimmed = value.trim(); + const match = ISO_UTC_OR_OFFSET_RE.exec(trimmed); + if (!match) { + throw new Error( + `Invalid ${label} timestamp: expected ISO-8601 string with explicit UTC or offset timezone, received "${value}"` + ); } + + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const hour = Number(match[4]); + const minute = Number(match[5]); + const second = Number(match[6]); + const frac = match[7]; + const tz = match[8]; + + const baseUtcMs = Date.UTC(year, month - 1, day, hour, minute, second); + const check = new Date(baseUtcMs); + if ( + check.getUTCFullYear() !== year || + check.getUTCMonth() !== month - 1 || + check.getUTCDate() !== day || + check.getUTCHours() !== hour || + check.getUTCMinutes() !== minute || + check.getUTCSeconds() !== second + ) { + throw new Error(`Invalid ${label} timestamp calendar date/time: "${value}"`); + } + + if (tz === 'Z') { + return trimmed; + } + + const sign = match[9] === '+' ? 1 : -1; + const offsetHours = Number(match[10]); + const offsetMinutes = Number(match[11]); + if (offsetHours > 23 || offsetMinutes > 59) { + throw new Error(`Invalid ${label} timestamp timezone offset: "${value}"`); + } + + const adjustedUtcMs = baseUtcMs - sign * (offsetHours * 60 + offsetMinutes) * 60_000; + const utcDate = new Date(adjustedUtcMs); + const isoSeconds = utcDate.toISOString().slice(0, 19); + return frac ? `${isoSeconds}.${frac}Z` : `${isoSeconds}Z`; } throw new Error(`Invalid ${label} timestamp: "${String(value)}"`); } -function parseBarTimestamp(raw: unknown, field: string): Date { - if (raw instanceof Date) { - if (Number.isNaN(raw.getTime())) { - throw new Error(`Invalid bars_1m ${field} timestamp: Date is NaN`); - } - return new Date(raw.getTime()); +function parseUtcEpochMicros(raw: unknown, field: string): bigint { + if (typeof raw === 'bigint') { + return raw; } - if (typeof raw === 'string' || typeof raw === 'number') { - const parsed = new Date(raw); - if (!Number.isNaN(parsed.getTime())) { - return parsed; - } + if (typeof raw === 'string' && CANONICAL_INT_RE.test(raw)) { + return BigInt(raw); } - throw new Error(`Invalid bars_1m ${field} timestamp: "${String(raw)}"`); + if (typeof raw === 'number' && Number.isSafeInteger(raw)) { + return BigInt(raw); + } + throw new Error(`Invalid bars_1m ${field} UTC epoch microseconds: "${String(raw)}"`); } function parseRequiredFiniteNumber(raw: unknown, field: string): number { @@ -128,7 +168,7 @@ export async function readBars1m( const toIso = toUtcIsoString(to, 'to'); const sql = - 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, known_at, ts ' + + 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' + 'FROM bars_1m ' + 'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' + 'ORDER BY ts ASC'; @@ -145,8 +185,8 @@ export async function readBars1m( vwap: parseNullableFiniteNumber(row.vwap, 'vwap'), session: parseNullableString(row.session, 'session'), source: parseNullableString(row.source, 'source'), - known_at: parseBarTimestamp(row.known_at, 'known_at'), - ts: parseBarTimestamp(row.ts, 'ts'), + known_at: parseUtcEpochMicros(row.known_at_us, 'known_at'), + ts: parseUtcEpochMicros(row.ts_us, 'ts'), })); } @@ -511,9 +551,7 @@ export class QuestDBClient { * Get table information */ async getTableInfo(tableName: string): Promise { - const result = await this.query(`SELECT * FROM table_columns WHERE table_name = $1`, [ - tableName, - ]); + const result = await this.query('SELECT * FROM table_columns($1)', [tableName]); return result.rows; } diff --git a/libs/data/questdb/src/query-builder.ts b/libs/data/questdb/src/query-builder.ts index f417ef88..652c75a3 100644 --- a/libs/data/questdb/src/query-builder.ts +++ b/libs/data/questdb/src/query-builder.ts @@ -92,6 +92,7 @@ export function rebaseWhereCondition( if (ch === "'") { out += ch; i += 1; + let closed = false; while (i < condition.length) { const cur = condition.charAt(i); out += cur; @@ -101,10 +102,14 @@ export function rebaseWhereCondition( out += "'"; i += 1; } else { + closed = true; break; } } } + if (!closed) { + throw new Error('Unterminated string literal in WHERE condition'); + } continue; } @@ -112,6 +117,7 @@ export function rebaseWhereCondition( if (ch === '"') { out += ch; i += 1; + let closed = false; while (i < condition.length) { const cur = condition.charAt(i); out += cur; @@ -121,25 +127,34 @@ export function rebaseWhereCondition( out += '"'; i += 1; } else { + closed = true; break; } } } + if (!closed) { + throw new Error('Unterminated quoted identifier in WHERE condition'); + } continue; } - // Line comment (-- ... \n) + // Line comment (-- ... \n); terminate at EOF so subsequent clauses are never swallowed if (ch === '-' && next === '-') { out += '--'; i += 2; + let sawNewline = false; while (i < condition.length) { const cur = condition.charAt(i); out += cur; i += 1; if (cur === '\n') { + sawNewline = true; break; } } + if (!sawNewline) { + out += '\n'; + } continue; } @@ -147,15 +162,20 @@ export function rebaseWhereCondition( if (ch === '/' && next === '*') { out += '/*'; i += 2; + let closed = false; while (i < condition.length) { if (condition.charAt(i) === '*' && condition.charAt(i + 1) === '/') { out += '*/'; i += 2; + closed = true; break; } out += condition.charAt(i); i += 1; } + if (!closed) { + throw new Error('Unterminated block comment in WHERE condition'); + } continue; } diff --git a/libs/data/questdb/src/types.ts b/libs/data/questdb/src/types.ts index 67a2f4eb..f52d6192 100644 --- a/libs/data/questdb/src/types.ts +++ b/libs/data/questdb/src/types.ts @@ -93,7 +93,9 @@ export interface LatestByOptions { /** * Typed 1-minute bar row returned from QuestDB `bars_1m`. - * `listing_id` is stored as decimal string SYMBOL in QuestDB and converted to INT32 at read boundary. + * - `listing_id` is stored as decimal string SYMBOL in QuestDB and converted to INT32 at read boundary. + * - `known_at` and `ts` are lossless UTC epoch microseconds (`bigint`) projected via `CAST(... AS LONG)` + * to preserve all 6 fractional digits and avoid PGWire local-timezone `Date` coercion. */ export interface Bar1mRow { listing_id: number; @@ -105,8 +107,8 @@ export interface Bar1mRow { vwap: number | null; session: string | null; source: string | null; - known_at: Date; - ts: Date; + known_at: bigint; + ts: bigint; } /** diff --git a/libs/data/questdb/test/questdb-query-layer.test.ts b/libs/data/questdb/test/questdb-query-layer.test.ts index 886c0f2a..ce587670 100644 --- a/libs/data/questdb/test/questdb-query-layer.test.ts +++ b/libs/data/questdb/test/questdb-query-layer.test.ts @@ -277,6 +277,57 @@ describe('QuestDB 10.2.0 query layer', () => { // Builder is reset again after successful execute() expect(() => builder.build()).toThrow('FROM clause is required'); }); + + it('terminates trailing line comments with a newline before subsequent predicates, LATEST ON, and SAMPLE BY', async () => { + const fake = new FakeQuestDBClient(); + const client = createClientWithFakeQuery(fake); + + const builderResult = QuestDBQueryBuilder.create(fake) + .select('listing_id', 'ts', 'close') + .from('bars_1m') + .where('session = $1 -- regular session', ['RTH']) + .where('close > $1 -- minimum price', [100]) + .latestOn('ts', 'listing_id') + .buildParameterized(); + + expect(builderResult.sql).toBe( + 'SELECT listing_id, ts, close FROM bars_1m ' + + 'WHERE session = $1 -- regular session\n ' + + 'AND close > $2 -- minimum price\n ' + + 'LATEST ON ts PARTITION BY listing_id' + ); + expect(builderResult.params).toEqual(['RTH', 100]); + + await client.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', { + where: 'session = $1 -- regular session', + params: ['RTH'], + }); + await client.sampleBy( + 'bars_1m', + ['ts', 'close'], + '1h', + 'ts', + 'session = $1 -- regular session', + ['RTH'] + ); + + expect(fake.calls).toEqual([ + { + sql: + 'SELECT listing_id, ts, close FROM bars_1m ' + + 'WHERE session = $1 -- regular session\n ' + + 'LATEST ON ts PARTITION BY listing_id', + params: ['RTH'], + }, + { + sql: + 'SELECT ts, close FROM bars_1m ' + + 'WHERE session = $1 -- regular session\n ' + + 'SAMPLE BY 1h ALIGN TO CALENDAR', + params: ['RTH'], + }, + ]); + }); }); describe('identifier and interval validation', () => { @@ -337,6 +388,22 @@ describe('QuestDB 10.2.0 query layer', () => { params: [hostileTable], }); }); + + it('binds table name in QuestDBClient.getTableInfo() via table_columns($1)', async () => { + const fake = new FakeQuestDBClient(); + const client = createClientWithFakeQuery(fake); + fake.setRows([{ column: 'ts', type: 'TIMESTAMP' }]); + + const rows = await client.getTableInfo('bars_1m'); + + expect(rows).toEqual([{ column: 'ts', type: 'TIMESTAMP' }]); + expect(fake.calls).toEqual([ + { + sql: 'SELECT * FROM table_columns($1)', + params: ['bars_1m'], + }, + ]); + }); }); describe('M2 intraday contract DDL', () => { @@ -395,8 +462,12 @@ describe('QuestDB 10.2.0 query layer', () => { }); describe('readBars1m storage reader', () => { - it('sends one parameterized [from, to) query and converts decimal-string listing_id to INT32', async () => { + it('sends one parameterized [from, to) query with UTC epoch-microsecond projection and converts listing_id to INT32', async () => { const fake = new FakeQuestDBClient(); + // 2024-01-02T14:30:00.000000Z = 1704205800000000 us + // 2024-01-02T14:31:00.000700Z = 1704205860000700 us (6 fractional digits preserved) + // 2024-01-02T14:31:00.000000Z = 1704205860000000 us + // 2024-01-02T14:32:00.123456Z = 1704205920123456 us const fixtureRows = [ { listing_id: '1042', @@ -408,8 +479,8 @@ describe('QuestDB 10.2.0 query layer', () => { vwap: 185.28, session: 'RTH', source: 'eod_unadj', - known_at: new Date('2024-01-02T14:31:00.000Z'), - ts: new Date('2024-01-02T14:30:00.000Z'), + known_at_us: '1704205860000700', + ts_us: '1704205800000000', }, { listing_id: '1042', @@ -421,8 +492,8 @@ describe('QuestDB 10.2.0 query layer', () => { vwap: null, session: 'RTH', source: 'ib_live', - known_at: '2024-01-02T14:32:00.000Z', - ts: '2024-01-02T14:31:00.000Z', + known_at_us: 1704205920123456n, + ts_us: 1704205860000000, }, ]; fake.setRows(fixtureRows); @@ -436,7 +507,7 @@ describe('QuestDB 10.2.0 query layer', () => { expect(fake.calls).toHaveLength(2); expect(fake.calls[0]).toEqual({ sql: - 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, known_at, ts ' + + 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' + 'FROM bars_1m ' + 'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' + 'ORDER BY ts ASC', @@ -455,8 +526,8 @@ describe('QuestDB 10.2.0 query layer', () => { vwap: 185.28, session: 'RTH', source: 'eod_unadj', - known_at: new Date('2024-01-02T14:31:00.000Z'), - ts: new Date('2024-01-02T14:30:00.000Z'), + known_at: 1704205860000700n, + ts: 1704205800000000n, }, { listing_id: 1042, @@ -468,11 +539,72 @@ describe('QuestDB 10.2.0 query layer', () => { vwap: null, session: 'RTH', source: 'ib_live', - known_at: new Date('2024-01-02T14:32:00.000Z'), - ts: new Date('2024-01-02T14:31:00.000Z'), + known_at: 1704205920123456n, + ts: 1704205860000000n, }, ]); expect(typeof firstRead[0]!.listing_id).toBe('number'); + // Verify sub-millisecond ordering is preserved (14:31:00.000700Z > 14:31:00.000000Z) + expect(firstRead[0]!.known_at > 1704205860000000n).toBe(true); + }); + + it('preserves 6-digit microsecond bounds and produces identical results under non-UTC TZ', async () => { + const fake = new FakeQuestDBClient(); + fake.setRows([ + { + listing_id: '1042', + open: 185.1, + high: 185.5, + low: 184.9, + close: 185.4, + volume: 12500, + vwap: 185.28, + session: 'RTH', + source: 'eod_unadj', + known_at_us: '1704205860000700', + ts_us: '1704205800000000', + }, + ]); + + const previousTz = process.env.TZ; + try { + process.env.TZ = 'UTC'; + const utcRows = await readBars1m( + fake, + 1042, + '2024-01-02T14:30:00.000000Z', + '2024-01-02T14:31:00.000700Z' + ); + + process.env.TZ = 'America/Toronto'; + const torontoRows = await readBars1m( + fake, + 1042, + '2024-01-02T14:30:00.000000Z', + '2024-01-02T14:31:00.000700Z' + ); + + expect(torontoRows).toEqual(utcRows); + expect(torontoRows[0]!.known_at).toBe(1704205860000700n); + expect(torontoRows[0]!.ts).toBe(1704205800000000n); + expect(fake.calls[0]?.params).toEqual([ + '1042', + '2024-01-02T14:30:00.000000Z', + '2024-01-02T14:31:00.000700Z', + ]); + expect(fake.calls[1]?.params).toEqual(fake.calls[0]?.params); + } finally { + if (previousTz === undefined) { + delete process.env.TZ; + } else { + process.env.TZ = previousTz; + } + } + + // Reject timezone-naive string bounds that would depend on host local timezone + await expect( + readBars1m(fake, 1042, '2024-01-02T14:30:00', '2024-01-02T14:35:00Z') + ).rejects.toThrow(/timezone/i); }); it('returns empty array when no bars exist in range', async () => { @@ -515,8 +647,8 @@ describe('QuestDB 10.2.0 query layer', () => { vwap: 1.5, session: 'RTH', source: 'eod_unadj', - known_at: from, - ts: from, + known_at_us: '1704205800000000', + ts_us: '1704205800000000', }, ]); await expect(readBars1m(fake, 42, from, to)).rejects.toThrow(/listing_id SYMBOL/i); From bcf2067c8dc4b6576ed9cdbdda96831b6347a8c4 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 06:39:23 -0500 Subject: [PATCH 06/36] T-135: tests --- .../test/questdb-query-layer-edges.test.ts | 305 ++++++++++++++++++ 1 file changed, 305 insertions(+) create mode 100644 libs/data/questdb/test/questdb-query-layer-edges.test.ts diff --git a/libs/data/questdb/test/questdb-query-layer-edges.test.ts b/libs/data/questdb/test/questdb-query-layer-edges.test.ts new file mode 100644 index 00000000..e8089acd --- /dev/null +++ b/libs/data/questdb/test/questdb-query-layer-edges.test.ts @@ -0,0 +1,305 @@ +import { describe, expect, it } from 'bun:test'; +import type { QueryResultRow } from 'pg'; +import { + formatCreateTableSQL, + QuestDBClient, + QuestDBQueryBuilder, + QuestDBSchemaManager, + readBars1m, + type QueryResult, + type QuestDBQueryable, +} from '../src'; + +interface RecordedQuery { + sql: string; + params: unknown[] | undefined; +} + +class RecordingClient implements QuestDBQueryable { + public readonly calls: RecordedQuery[] = []; + + public async query( + sql: string, + params?: unknown[] + ): Promise> { + this.calls.push({ sql, params }); + return { rows: [] as T[], rowCount: 0, executionTime: 0 }; + } +} + +function clientRoutedTo(fake: RecordingClient): QuestDBClient { + const client = new QuestDBClient( + { host: 'questdb.test.local', httpPort: 9000, pgPort: 8812, influxPort: 9009, database: 'qdb' }, + { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} } + ); + (client as unknown as { query: QuestDBQueryable['query'] }).query = fake.query.bind(fake); + return client; +} + +describe('QuestDB query layer edge cases (QA)', () => { + describe('predefined builders', () => { + it('latestOHLCV binds symbols and exchange and emits LATEST ON timestamp after WHERE', () => { + const fake = new RecordingClient(); + const hostile = "AAPL' OR '1'='1"; + + const { sql, params } = QuestDBQueryBuilder.latestOHLCV( + fake, + [hostile, 'MSFT'], + 'NASDAQ' + ).buildParameterized(); + + expect(sql).toBe( + 'SELECT symbol, timestamp, open, high, low, close, volume FROM ohlcv_data ' + + 'WHERE symbol IN ($1, $2) AND exchange = $3 ' + + 'LATEST ON timestamp PARTITION BY symbol ORDER BY timestamp DESC' + ); + expect(params).toEqual([hostile, 'MSFT', 'NASDAQ']); + expect(sql).not.toContain(hostile); + }); + + it('ohlcvTimeSeries and tradeExecutions bind values in placeholder order', () => { + const fake = new RecordingClient(); + + const series = QuestDBQueryBuilder.ohlcvTimeSeries(fake, 'AAPL', '5m', 12).buildParameterized(); + expect(series.sql).toBe( + 'SELECT first(open) as first_open, max(high) as max_high, min(low) as min_low, ' + + 'last(close) as last_close, sum(volume) as sum_volume FROM ohlcv_data ' + + "WHERE symbol = $1 AND timestamp > dateadd('h', $2, now()) SAMPLE BY 5m ORDER BY timestamp DESC" + ); + expect(series.params).toEqual(['AAPL', -12]); + + const trades = QuestDBQueryBuilder.tradeExecutions(fake, 'AAPL', 3).buildParameterized(); + expect(trades.sql).toBe( + 'SELECT symbol, timestamp, side, quantity, price, execution_time FROM trade_executions ' + + "WHERE timestamp > dateadd('h', $1, now()) AND symbol = $2 ORDER BY timestamp DESC" + ); + expect(trades.params).toEqual([-3, 'AAPL']); + }); + + it('ohlcvTimeSeries rejects a hostile SAMPLE BY interval at build time', () => { + const fake = new RecordingClient(); + expect(() => QuestDBQueryBuilder.ohlcvTimeSeries(fake, 'AAPL', '1h; DROP TABLE x')).toThrow( + /Invalid SAMPLE BY interval/ + ); + expect(fake.calls).toHaveLength(0); + }); + }); + + describe('builder input validation', () => { + it('binds LIMIT 0 instead of silently dropping it and rejects negative or fractional limits', () => { + const fake = new RecordingClient(); + expect(QuestDBQueryBuilder.create(fake).from('t').limit(0).buildParameterized()).toEqual({ + sql: 'SELECT * FROM t LIMIT $1', + params: [0], + }); + expect(() => QuestDBQueryBuilder.create(fake).limit(-1)).toThrow(/LIMIT/); + expect(() => QuestDBQueryBuilder.create(fake).limit(1.5)).toThrow(/LIMIT/); + }); + + it('rejects non-positive relative windows and invalid dates', () => { + const fake = new RecordingClient(); + expect(() => QuestDBQueryBuilder.create(fake).whereLastHours(0)).toThrow(/hours/); + expect(() => QuestDBQueryBuilder.create(fake).whereLastDays(-2)).toThrow(/days/); + expect(() => + QuestDBQueryBuilder.create(fake).whereTimeRange(new Date('nope'), new Date()) + ).toThrow(/startTime/); + }); + + it('rejects unterminated quotes and block comments in raw where() before mutating state', () => { + const fake = new RecordingClient(); + const builder = QuestDBQueryBuilder.create(fake).from('bars_1m'); + + expect(() => builder.where("session = 'RTH", [])).toThrow(/Unterminated string/); + expect(() => builder.where('"session = $1', ['RTH'])).toThrow(/Unterminated quoted/); + expect(() => builder.where('session = $1 /* open', ['RTH'])).toThrow(/Unterminated block/); + + // Rejected fragments must not leak into the next build. + expect(builder.where('session = $1', ['RTH']).buildParameterized()).toEqual({ + sql: 'SELECT * FROM bars_1m WHERE session = $1', + params: ['RTH'], + }); + }); + + it('keeps doubled quotes inside literals and still rebases the following placeholder', () => { + const fake = new RecordingClient(); + const { sql, params } = QuestDBQueryBuilder.create(fake) + .from('bars_1m') + .whereSymbol('X') + .where("note = 'it''s $1' AND close > $1", [10]) + .buildParameterized(); + + expect(sql).toBe("SELECT * FROM bars_1m WHERE symbol = $1 AND note = 'it''s $1' AND close > $2"); + expect(params).toEqual(['X', 10]); + }); + }); + + describe('QuestDBClient helpers', () => { + it('reject params without a where fragment before sending a query', async () => { + const fake = new RecordingClient(); + const client = clientRoutedTo(fake); + + await expect( + client.sampleBy('bars_1m', ['ts', 'close'], '1h', 'ts', undefined, ['RTH']) + ).rejects.toThrow(/without a where/); + await expect( + client.asofJoin('bars_1m', 'fx_1m', 'bars_1m.ts = fx_1m.ts', undefined, undefined, [1]) + ).rejects.toThrow(/without a where/); + await expect( + client.latestBy('bars_1m', '*', 'listing_id', { params: ['RTH'] }) + ).rejects.toThrow(/without a where/); + await expect(client.sampleBy('bars_1m', ['ts'], '1h', 'ts; --')).rejects.toThrow( + /Invalid timestamp column/ + ); + await expect( + client.createTable('bars_1m', 'ts TIMESTAMP', 'DAY; DROP TABLE x', 'ts') + ).rejects.toThrow(/PARTITION BY/); + await expect(client.optimizeTable('bars_1m; DROP TABLE x')).rejects.toThrow( + /Invalid table name/ + ); + + expect(fake.calls).toHaveLength(0); + }); + + it('asofJoin binds where params and keeps SQL on validated identifiers', async () => { + const fake = new RecordingClient(); + const client = clientRoutedTo(fake); + + await client.asofJoin( + 'bars_1m', + 'fx_1m', + 'bars_1m.ts = fx_1m.ts', + ['close'], + 'listing_id = $1 AND pair = $2', + ['1042', 'USDCAD'] + ); + + expect(fake.calls).toEqual([ + { + sql: + 'SELECT close FROM bars_1m ASOF JOIN fx_1m ON bars_1m.ts = fx_1m.ts ' + + 'WHERE listing_id = $1 AND pair = $2', + params: ['1042', 'USDCAD'], + }, + ]); + }); + }); + + describe('schema DDL', () => { + it('leaves legacy startup DDL unchanged (no CAPACITY, CACHE, WAL or DEDUP)', async () => { + const fake = new RecordingClient(); + await new QuestDBSchemaManager(fake).createAllTables(); + + const ddl = fake.calls.map(call => call.sql); + expect(ddl).toHaveLength(6); + expect(ddl[0]).toBe( + 'CREATE TABLE IF NOT EXISTS ohlcv_data (symbol SYMBOL, exchange SYMBOL, timestamp TIMESTAMP, ' + + 'open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume LONG, data_source SYMBOL) ' + + 'TIMESTAMP(timestamp) PARTITION BY DAY' + ); + for (const statement of ddl) { + expect(statement).not.toMatch(/CAPACITY|CACHE|WAL|DEDUP|bars_1m|fx_1m|bar_revisions/); + } + }); + + it('formatCreateTableSQL rejects hostile identifiers, bad capacities and multiple designated timestamps', () => { + expect(() => + formatCreateTableSQL({ + tableName: 'bars_1m; DROP TABLE x', + columns: [{ name: 'ts', type: 'TIMESTAMP', designated: true }], + }) + ).toThrow(/Invalid table name/); + expect(() => + formatCreateTableSQL({ + tableName: 't', + columns: [{ name: 'ts TIMESTAMP); --', type: 'TIMESTAMP' }], + }) + ).toThrow(/Invalid column name/); + expect(() => + formatCreateTableSQL({ + tableName: 't', + columns: [{ name: 's', type: 'SYMBOL', capacity: 0 }], + }) + ).toThrow(/capacity/); + expect(() => + formatCreateTableSQL({ + tableName: 't', + columns: [ + { name: 'a', type: 'TIMESTAMP', designated: true }, + { name: 'b', type: 'TIMESTAMP', designated: true }, + ], + }) + ).toThrow(/Only one designated/); + }); + }); + + describe('readBars1m bound normalisation', () => { + it('converts offset bounds to UTC with fractional digits intact, across a day boundary', async () => { + const fake = new RecordingClient(); + + await readBars1m(fake, -0, '2024-01-01T23:30:00.5-05:00', '2024-01-02T09:30:00.000123+05:30'); + + expect(fake.calls).toHaveLength(1); + expect(fake.calls[0]?.params).toEqual([ + '0', + '2024-01-02T04:30:00.5Z', + '2024-01-02T04:00:00.000123Z', + ]); + }); + + it('binds negative INT32 listing ids and parses negative SYMBOL values back', async () => { + const fake = new RecordingClient(); + (fake as unknown as { query: QuestDBQueryable['query'] }).query = async ( + sql: string, + params?: unknown[] + ) => { + fake.calls.push({ sql, params }); + return { + rows: [ + { + listing_id: '-2147483648', + open: 1, + high: 1, + low: 1, + close: 1, + volume: 1, + vwap: null, + session: null, + source: null, + known_at_us: '1704205800000000', + ts_us: '1704205800000000', + }, + ] as T[], + rowCount: 1, + executionTime: 0, + }; + }; + + const rows = await readBars1m( + fake, + -2147483648, + '2024-01-02T14:30:00Z', + '2024-01-02T14:31:00Z' + ); + + expect(fake.calls[0]?.params?.[0]).toBe('-2147483648'); + expect(rows[0]?.listing_id).toBe(-2147483648); + expect(rows[0]?.vwap).toBeNull(); + }); + + it('rejects impossible calendar dates, out-of-range offsets and NaN dates before querying', async () => { + const fake = new RecordingClient(); + const to = '2024-03-01T00:00:00Z'; + + await expect(readBars1m(fake, 1, '2024-02-30T00:00:00Z', to)).rejects.toThrow(/calendar/); + await expect(readBars1m(fake, 1, '2024-02-01T00:00:00+24:00', to)).rejects.toThrow( + /offset/ + ); + await expect(readBars1m(fake, 1, new Date('nope'), to)).rejects.toThrow(/NaN/); + await expect(readBars1m(fake, 1, '2024-02-01T00:00:00.1234567Z', to)).rejects.toThrow( + /timezone/ + ); + + expect(fake.calls).toHaveLength(0); + }); + }); +}); From c6e6b796a482127aa05ca2243ffb7c1940e3e5ee Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 06:55:43 -0500 Subject: [PATCH 07/36] =?UTF-8?q?T-137:=20M2.3c=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20QuestDB=20ILP=20v2=20encoder=20+=20sharded=20b?= =?UTF-8?q?atch=20writer=20for=20`bars=5F1m`=20/=20`fx=5F1m`=20over=20inje?= =?UTF-8?q?cted=20`Write`=20sinks=20(no=20new=20crates,=20no=20live=20Ques?= =?UTF-8?q?tDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/bench.rs | 141 +++++- tools/curate-etl/src/cli.rs | 27 +- tools/curate-etl/src/ilp.rs | 567 ++++++++++++++++++++++ tools/curate-etl/src/ilp_tests.rs | 765 ++++++++++++++++++++++++++++++ tools/curate-etl/src/lib.rs | 7 + tools/curate-etl/src/main.rs | 30 +- tools/curate-etl/tests/cli.rs | 32 ++ 7 files changed, 1565 insertions(+), 4 deletions(-) create mode 100644 tools/curate-etl/src/ilp.rs create mode 100644 tools/curate-etl/src/ilp_tests.rs diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 6fea2441..d76fb2a8 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -17,8 +17,8 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; use crate::bars_1m::{ - build_bars_1m, check_session_closes, Bars1mError, Bars1mStats, DailySessionClose, - EodIntradayBar, IntradaySession, SessionCloseStats, + build_bars_1m, check_session_closes, Bar1mRow, Bars1mError, Bars1mStats, DailySessionClose, + EodIntradayBar, IntradaySession, SessionCloseStats, BARS_1M_SOURCE_EOD, }; use crate::bson_eod_prices::{decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats}; use crate::bson_qm_actions::{ @@ -39,6 +39,7 @@ use crate::events::{ KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, }; use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar, FxSource, FX_PAIR_USDCAD}; +use crate::ilp::{IlpShardedWriter, IlpWriterError, IlpWriterOptions}; use crate::parquet_adj::{ write_adj_factors_dataset, AdjFactorsParquetRow, AdjFactorsWriteOptions, ParquetAdjError, }; @@ -72,6 +73,8 @@ pub const DEFAULT_ADJ_BENCH_EVENTS: usize = 1_000_000; pub const DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 1_000_000; pub const DEFAULT_BARS_BENCH_ROWS: usize = 10_000_000; pub const DEFAULT_BARS_1M_BENCH_ROWS: usize = 10_000_000; +pub const DEFAULT_ILP_BARS_1M_BENCH_ROWS: usize = DEFAULT_BARS_1M_BENCH_ROWS; +pub const ILP_BARS_1M_BENCH_SHARDS: usize = 4; pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000; pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000; pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000; @@ -112,6 +115,7 @@ const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70; const CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C049_AC71; const BARS_BENCH_SEED: u64 = 0x570C_4B07_BA45_1D00; const BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_BA45_0100; +const ILP_BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_119B_A451; const BARS_1M_BENCH_KEY_COUNT: usize = 2_000; const BARS_1M_BENCH_EVENT_COUNT: usize = 2_000; const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE; @@ -1168,6 +1172,108 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result, +} + +/// Runs the fixed-seed QuestDB ILP v2 `bars_1m` encoding + sharded batching benchmark for `rows` +/// curated 1-minute equity bars across four `std::io::sink()` shards. +/// +/// Generates `rows` deterministic curated [`Bar1mRow`] records and `known_at` timestamps +/// across `2_000` `i32` listing IDs spanning `2024-01-02..=2025-12-31` (`PRE`/`RTH`/`POST`), then +/// times encoding and batching through [`IlpShardedWriter`] including [`IlpShardedWriter::finish`]. +pub fn run_ilp_bars_1m_benchmark(rows: usize) -> Result { + let min_date = ymd_to_epoch_days(2024, 1, 2).unwrap_or(19_724); + let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); + let date_span = (max_date - min_date + 1) as u64; + + let mut rng = SplitMix64::new(ILP_BARS_1M_BENCH_SEED); + let mut input_rows: Vec<(Bar1mRow, i64)> = Vec::with_capacity(rows); + + for _ in 0..rows { + let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1; + let session_date = min_date + (rng.next_u64() % date_span) as i32; + let et_minute = (480 + (rng.next_u64() % 720)) as u16; + let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0); + let ts = close_1600_utc + (i64::from(et_minute) - 960) * 60_000_000; + let known_at = ts + 60_000_000; + + let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01; + let spread = ((rng.next_u64() % 300) + 5) as f64 * 0.01; + let high = low + spread; + let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); + let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); + let volume = ((rng.next_u64() % 500_000) + 10) as f64; + + input_rows.push(( + Bar1mRow { + key, + ts, + session_date, + open, + high, + low, + close, + volume, + session: IntradaySession::from_et_minute(et_minute), + source: BARS_1M_SOURCE_EOD, + }, + known_at, + )); + } + + let sinks: Vec = (0..ILP_BARS_1M_BENCH_SHARDS).map(|_| io::sink()).collect(); + let mut writer = IlpShardedWriter::new(sinks, IlpWriterOptions::default())?; + + let start = Instant::now(); + for (row, known_at) in &input_rows { + writer.write_bar_1m(row, *known_at)?; + } + let stats = black_box(writer.finish()?); + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + let (rows_per_sec, ns_per_row) = compute_rates(stats.rows, elapsed_secs); + let bytes_per_row = if stats.rows == 0 { + 0.0 + } else { + stats.bytes as f64 / stats.rows as f64 + }; + let mb_per_sec = if elapsed_secs <= 0.0 || !elapsed_secs.is_finite() { + 0.0 + } else { + (stats.bytes as f64 / 1_000_000.0) / elapsed_secs + }; + + Ok(IlpBars1mBenchReport { + rows, + rows_encoded: stats.rows, + key_count: BARS_1M_BENCH_KEY_COUNT, + shards: ILP_BARS_1M_BENCH_SHARDS, + bytes: stats.bytes, + flushes: stats.flushes, + elapsed_ms, + rows_per_sec, + ns_per_row, + bytes_per_row, + mb_per_sec, + per_shard_rows: stats.per_shard_rows, + }) +} + /// Summary metrics produced by [`run_fx_benchmark`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct FxBenchReport { @@ -13077,4 +13183,35 @@ mod tests { assert_eq!(report.rows_per_sec, 0.0); assert_eq!(report.ns_per_row, 0.0); } + + #[test] + fn ilp_bars_1m_benchmark_small_run_is_deterministic_and_conserves_counts() { + let a = run_ilp_bars_1m_benchmark(5_000).unwrap(); + let b = run_ilp_bars_1m_benchmark(5_000).unwrap(); + + assert_eq!(a.rows, 5_000); + assert_eq!(a.rows_encoded, a.rows); + assert_eq!(a.shards, ILP_BARS_1M_BENCH_SHARDS); + assert_eq!(a.bytes, b.bytes); + assert_eq!(a.flushes, b.flushes); + assert_eq!(a.per_shard_rows, b.per_shard_rows); + assert_eq!(a.per_shard_rows.len(), ILP_BARS_1M_BENCH_SHARDS); + assert_eq!(a.per_shard_rows.iter().sum::(), a.rows_encoded); + assert!(a.bytes > 0); + assert!(a.bytes_per_row > 100.0); + assert!(a.flushes >= ILP_BARS_1M_BENCH_SHARDS); + } + + #[test] + fn ilp_bars_1m_benchmark_zero_rows_handles_cleanly() { + let report = run_ilp_bars_1m_benchmark(0).unwrap(); + assert_eq!(report.rows, 0); + assert_eq!(report.rows_encoded, 0); + assert_eq!(report.bytes, 0); + assert_eq!(report.flushes, 0); + assert_eq!(report.bytes_per_row, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.ns_per_row, 0.0); + assert_eq!(report.per_shard_rows, vec![0; ILP_BARS_1M_BENCH_SHARDS]); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 64a26b81..7f399ac9 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -19,7 +19,7 @@ use crate::bench::{ DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_FX_CMD_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, - DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, + DEFAULT_ILP_BARS_1M_BENCH_ROWS, DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, @@ -72,6 +72,7 @@ pub enum CliAction { BenchCorporateActions(usize), BenchBars(usize), BenchBars1m(usize), + BenchIlpBars1m(usize), BenchFx(usize), BenchShorts(usize), BenchEvents(usize), @@ -131,6 +132,7 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\ {name} bench-bars [rows] Run fixed-seed bars_1d build + cross-check benchmark (default: {DEFAULT_BARS_BENCH_ROWS})\n\ {name} bench-bars-1m [rows] Run fixed-seed bars_1m build + session-close cross-check benchmark (default: {DEFAULT_BARS_1M_BENCH_ROWS})\n\ + {name} bench-ilp-bars-1m [rows] Run fixed-seed QuestDB ILP v2 bars_1m encode + sharded batch benchmark (default: {DEFAULT_ILP_BARS_1M_BENCH_ROWS})\n\ {name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\ {name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\ {name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\ @@ -177,6 +179,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-corporate-actions [events]\n\ {name} bench-bars [rows]\n\ {name} bench-bars-1m [rows]\n\ + {name} bench-ilp-bars-1m [rows]\n\ {name} bench-fx [rows]\n\ {name} bench-shorts [rows]\n\ {name} bench-events [rows]\n\ @@ -1474,6 +1477,14 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-bars-1m", _, ..] => Err("too many arguments for bench-bars-1m".to_string()), + ["bench-ilp-bars-1m"] => Ok(CliAction::BenchIlpBars1m(DEFAULT_ILP_BARS_1M_BENCH_ROWS)), + ["bench-ilp-bars-1m", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchIlpBars1m(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-ilp-bars-1m", _, ..] => Err("too many arguments for bench-ilp-bars-1m".to_string()), ["bench-fx"] => Ok(CliAction::BenchFx(DEFAULT_FX_BENCH_ROWS)), ["bench-fx", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchFx(n)), @@ -3404,5 +3415,19 @@ mod tests { assert!(parse_args(&to_args(&["bench-curate-events-cmd", "0"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-events-cmd", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-events-cmd", "1", "2"])).is_err()); + + // bench-ilp-bars-1m + assert_eq!( + parse_args(&to_args(&["bench-ilp-bars-1m"])), + Ok(CliAction::BenchIlpBars1m(DEFAULT_ILP_BARS_1M_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-ilp-bars-1m", "2500"])), + Ok(CliAction::BenchIlpBars1m(2_500)) + ); + assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "1", "2"])).is_err()); } } diff --git a/tools/curate-etl/src/ilp.rs b/tools/curate-etl/src/ilp.rs new file mode 100644 index 00000000..54a5691e --- /dev/null +++ b/tools/curate-etl/src/ilp.rs @@ -0,0 +1,567 @@ +//! Pure, socket-free QuestDB ILP v2 line encoder and sharded batch writer for +//! `bars_1m` and `fx_1m`. +//! +//! # Wire format (QuestDB ILP Protocol Version 2) +//! +//! Verified against the official `questdb-rs` client source in +//! `questdb/c-questdb-client` (`main` branch, `questdb-rs`): +//! - Binary `DOUBLE` type tag (`DOUBLE_TYPE = 16` / `0x10`): +//! `questdb-rs/src/ingress.rs` lines 157–159. +//! - Tag/field separators and binary `f64` field encoding (`==\x10<8 LE IEEE-754 bytes>`): +//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 569–713. +//! - ILP escaping for `SYMBOL` values (space, `,`, `=`, `\n`, `\r`, and `\` prefixed with `\`): +//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 36–84. +//! - Timestamp column microsecond suffix (`=t`): +//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1026–1047. +//! - Designated timestamp microsecond suffix (` t\n`, non-negative): +//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1087–1116. +//! +//! # Table contracts +//! +//! Column names and types match `M2_INTRADAY_SCHEMAS` in `libs/data/questdb/src/schema.ts` +//! and `design/DATA-CONTRACTS.md` §3.B: +//! - `bars_1m`: symbols `listing_id`, `session`, `source`; binary doubles `open`, `high`, `low`, +//! `close`, `volume` (`vwap` is omitted / NULL); timestamp column `known_at`; designated +//! timestamp `ts` (UTC microseconds). +//! - `fx_1m`: symbols `pair`, `source`; binary doubles `open`, `high`, `low`, `close`; +//! designated timestamp `ts` (UTC microseconds). +//! +//! # Deterministic sharding +//! +//! [`IlpShardedWriter`] routes rows deterministically using 64-bit FNV-1a modulo shard count +//! (`fnv1a_64(key_bytes) % shard_count`): +//! - `bars_1m` hashes `listing_id` as its 4-byte little-endian representation +//! (`listing_id.to_le_bytes()`). +//! - `fx_1m` hashes `pair` as its raw UTF-8 bytes (`pair.as_bytes()`). +//! +//! All rows for a given key always land on the same shard in their exact input order, preserving +//! the per-key ordering required by `DEDUP UPSERT KEYS(ts, listing_id)` / `KEYS(ts, pair)`. + +use std::error::Error; +use std::fmt; +use std::io::{self, Write}; + +use crate::bars_1m::Bar1mRow; + +/// QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`). +pub const ILP_V2_DOUBLE_TYPE: u8 = 0x10; + +/// Canonical QuestDB table name for 1-minute equity bars. +pub const TABLE_BARS_1M: &str = "bars_1m"; + +/// Canonical QuestDB table name for 1-minute FX bars. +pub const TABLE_FX_1M: &str = "fx_1m"; + +/// 64-bit FNV-1a offset basis used for deterministic shard routing. +pub const FNV1A_64_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + +/// 64-bit FNV-1a prime used for deterministic shard routing. +pub const FNV1A_64_PRIME: u64 = 0x0000_0100_0000_01b3; + +/// Default maximum buffered bytes per shard before flushing a batch (1 MiB). +pub const DEFAULT_ILP_MAX_BATCH_BYTES: usize = 1_048_576; + +/// Default maximum buffered rows per shard before flushing a batch. +pub const DEFAULT_ILP_MAX_BATCH_ROWS: usize = 10_000; + +/// A single `fx_1m` 1-minute FX bar input for QuestDB ILP v2 encoding. +/// +/// Matches `M2_INTRADAY_SCHEMAS.fx_1m` in `libs/data/questdb/src/schema.ts`: +/// `pair` (SYMBOL), `open`/`high`/`low`/`close` (DOUBLE), `source` (SYMBOL), `ts` (TIMESTAMP). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Fx1mRow<'a> { + pub pair: &'a str, + /// Bar start timestamp in UTC microseconds since the Unix epoch (must be `>= 0`). + pub ts: i64, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub source: &'a str, +} + +/// Typed validation errors returned by [`encode_bar_1m`] and [`encode_fx_1m`]. +/// +/// Encoding is atomic: when an error is returned, the caller's destination buffer is left +/// completely unmodified. +#[derive(Debug, Clone, PartialEq)] +pub enum IlpEncodeError { + /// A `DOUBLE` field was non-finite (`NaN`, `+inf`, or `-inf`). + NonFiniteDouble { field: &'static str, value: f64 }, + /// The designated timestamp `ts` was negative (QuestDB ILP requires `ts >= 0`). + NegativeTimestamp { field: &'static str, value: i64 }, + /// A required `SYMBOL` column value was empty. + EmptySymbol { field: &'static str }, +} + +impl fmt::Display for IlpEncodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::NonFiniteDouble { field, value } => { + write!(f, "non-finite ILP double field '{field}': {value}") + } + Self::NegativeTimestamp { field, value } => { + write!( + f, + "negative ILP designated timestamp '{field}': {value} (must be >= 0)" + ) + } + Self::EmptySymbol { field } => { + write!(f, "empty ILP symbol field '{field}'") + } + } + } +} + +impl Error for IlpEncodeError {} + +/// Batching limits for [`IlpShardedWriter`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct IlpWriterOptions { + /// Maximum buffered bytes per shard before flushing (must be `>= 1`). + pub max_batch_bytes: usize, + /// Maximum buffered rows per shard before flushing (must be `>= 1`). + pub max_batch_rows: usize, +} + +impl Default for IlpWriterOptions { + fn default() -> Self { + Self { + max_batch_bytes: DEFAULT_ILP_MAX_BATCH_BYTES, + max_batch_rows: DEFAULT_ILP_MAX_BATCH_ROWS, + } + } +} + +/// Summary statistics returned by [`IlpShardedWriter::finish`]. +/// +/// Conservation invariants: +/// - `per_shard_rows.iter().sum::() == rows` +/// - `bytes` equals the exact sum of bytes written across all successful shard `write_all` calls. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IlpWriteStats { + pub rows: usize, + pub bytes: usize, + pub flushes: usize, + pub per_shard_rows: Vec, +} + +/// Typed errors returned by [`IlpShardedWriter`]. +#[derive(Debug)] +pub enum IlpWriterError { + /// No sinks were provided to [`IlpShardedWriter::new`]. + EmptySinks, + /// [`IlpWriterOptions::max_batch_bytes`] was `0`. + ZeroMaxBatchBytes, + /// [`IlpWriterOptions::max_batch_rows`] was `0`. + ZeroMaxBatchRows, + /// Row encoding failed before mutating any shard buffer. + Encode(IlpEncodeError), + /// A sink `write_all` or `flush` call failed on `shard`. + Io { shard: usize, source: io::Error }, + /// A previous I/O failure on `failed_shard` poisoned the writer; no further writes are allowed. + Poisoned { failed_shard: usize }, +} + +impl fmt::Display for IlpWriterError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptySinks => write!(f, "ILP sharded writer requires at least one sink"), + Self::ZeroMaxBatchBytes => { + write!(f, "ILP writer max_batch_bytes must be >= 1") + } + Self::ZeroMaxBatchRows => { + write!(f, "ILP writer max_batch_rows must be >= 1") + } + Self::Encode(err) => write!(f, "ILP encode error: {err}"), + Self::Io { shard, source } => { + write!(f, "ILP writer I/O error on shard {shard}: {source}") + } + Self::Poisoned { failed_shard } => write!( + f, + "ILP writer is poisoned after prior I/O error on shard {failed_shard}" + ), + } + } +} + +impl Error for IlpWriterError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Encode(err) => Some(err), + Self::Io { source, .. } => Some(source), + Self::EmptySinks + | Self::ZeroMaxBatchBytes + | Self::ZeroMaxBatchRows + | Self::Poisoned { .. } => None, + } + } +} + +impl From for IlpWriterError { + fn from(err: IlpEncodeError) -> Self { + Self::Encode(err) + } +} + +/// Computes the 64-bit FNV-1a hash of `bytes`. +#[inline] +pub fn fnv1a_64(bytes: &[u8]) -> u64 { + let mut hash = FNV1A_64_OFFSET_BASIS; + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(FNV1A_64_PRIME); + } + hash +} + +/// Deterministic shard index for an equity `listing_id` (`i32` hashed as 4 little-endian bytes). +#[inline] +pub fn shard_for_listing_id(listing_id: i32, shard_count: usize) -> usize { + debug_assert!(shard_count > 0); + (fnv1a_64(&listing_id.to_le_bytes()) % (shard_count as u64)) as usize +} + +/// Deterministic shard index for an FX `pair` (hashed as raw UTF-8 bytes). +#[inline] +pub fn shard_for_fx_pair(pair: &str, shard_count: usize) -> usize { + debug_assert!(shard_count > 0); + (fnv1a_64(pair.as_bytes()) % (shard_count as u64)) as usize +} + +#[inline] +fn validate_finite(field: &'static str, value: f64) -> Result<(), IlpEncodeError> { + if value.is_finite() { + Ok(()) + } else { + Err(IlpEncodeError::NonFiniteDouble { field, value }) + } +} + +#[inline] +fn validate_non_negative_ts(field: &'static str, value: i64) -> Result<(), IlpEncodeError> { + if value >= 0 { + Ok(()) + } else { + Err(IlpEncodeError::NegativeTimestamp { field, value }) + } +} + +/// Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`. +#[inline] +fn write_escaped_symbol(buf: &mut Vec, value: &str) { + let bytes = value.as_bytes(); + let mut last = 0usize; + for (i, &b) in bytes.iter().enumerate() { + if matches!(b, b' ' | b',' | b'=' | b'\n' | b'\r' | b'\\') { + if last < i { + buf.extend_from_slice(&bytes[last..i]); + } + buf.push(b'\\'); + buf.push(b); + last = i + 1; + } + } + if last < bytes.len() { + buf.extend_from_slice(&bytes[last..]); + } +} + +#[inline] +fn write_i64_decimal(buf: &mut Vec, value: i64) { + let mut tmp = [0u8; 20]; + let negative = value < 0; + let mut mag = value.unsigned_abs(); + let mut pos = tmp.len(); + if mag == 0 { + pos -= 1; + tmp[pos] = b'0'; + } else { + while mag > 0 { + pos -= 1; + tmp[pos] = b'0' + (mag % 10) as u8; + mag /= 10; + } + } + if negative { + pos -= 1; + tmp[pos] = b'-'; + } + buf.extend_from_slice(&tmp[pos..]); +} + +#[inline] +fn write_binary_f64(buf: &mut Vec, name: &str, value: f64) { + buf.extend_from_slice(name.as_bytes()); + buf.extend_from_slice(&[b'=', b'=', ILP_V2_DOUBLE_TYPE]); + buf.extend_from_slice(&value.to_le_bytes()); +} + +/// Encodes one curated `bars_1m` row in QuestDB ILP v2 format into `buf`. +/// +/// Emits: +/// - Table `bars_1m` +/// - Symbols `listing_id` (decimal `row.key`), `session` (`PRE`/`RTH`/`POST`), `source` +/// - Binary `f64` columns `open`, `high`, `low`, `close`, `volume` (`vwap` omitted / NULL) +/// - Timestamp column `known_at=t` +/// - Designated timestamp ` t\n` +/// +/// Validates all doubles, `source`, and non-negative `row.ts` before appending any bytes so +/// `buf` is left untouched on error. +pub fn encode_bar_1m( + buf: &mut Vec, + row: &Bar1mRow, + known_at_micros: i64, +) -> Result<(), IlpEncodeError> { + if row.source.is_empty() { + return Err(IlpEncodeError::EmptySymbol { field: "source" }); + } + validate_finite("open", row.open)?; + validate_finite("high", row.high)?; + validate_finite("low", row.low)?; + validate_finite("close", row.close)?; + validate_finite("volume", row.volume)?; + validate_non_negative_ts("ts", row.ts)?; + + buf.extend_from_slice(TABLE_BARS_1M.as_bytes()); + buf.extend_from_slice(b",listing_id="); + write_i64_decimal(buf, i64::from(row.key)); + buf.extend_from_slice(b",session="); + buf.extend_from_slice(row.session.as_str().as_bytes()); + buf.extend_from_slice(b",source="); + write_escaped_symbol(buf, row.source); + + buf.push(b' '); + write_binary_f64(buf, "open", row.open); + buf.push(b','); + write_binary_f64(buf, "high", row.high); + buf.push(b','); + write_binary_f64(buf, "low", row.low); + buf.push(b','); + write_binary_f64(buf, "close", row.close); + buf.push(b','); + write_binary_f64(buf, "volume", row.volume); + buf.extend_from_slice(b",known_at="); + write_i64_decimal(buf, known_at_micros); + buf.extend_from_slice(b"t "); + + write_i64_decimal(buf, row.ts); + buf.extend_from_slice(b"t\n"); + Ok(()) +} + +/// Encodes one `fx_1m` row in QuestDB ILP v2 format into `buf`. +/// +/// Emits: +/// - Table `fx_1m` +/// - Symbols `pair`, `source` +/// - Binary `f64` columns `open`, `high`, `low`, `close` +/// - Designated timestamp ` t\n` +/// +/// Validates `pair`, `source`, all doubles, and non-negative `row.ts` before appending any bytes +/// so `buf` is left untouched on error. +pub fn encode_fx_1m(buf: &mut Vec, row: &Fx1mRow<'_>) -> Result<(), IlpEncodeError> { + if row.pair.is_empty() { + return Err(IlpEncodeError::EmptySymbol { field: "pair" }); + } + if row.source.is_empty() { + return Err(IlpEncodeError::EmptySymbol { field: "source" }); + } + validate_finite("open", row.open)?; + validate_finite("high", row.high)?; + validate_finite("low", row.low)?; + validate_finite("close", row.close)?; + validate_non_negative_ts("ts", row.ts)?; + + buf.extend_from_slice(TABLE_FX_1M.as_bytes()); + buf.extend_from_slice(b",pair="); + write_escaped_symbol(buf, row.pair); + buf.extend_from_slice(b",source="); + write_escaped_symbol(buf, row.source); + + buf.push(b' '); + write_binary_f64(buf, "open", row.open); + buf.push(b','); + write_binary_f64(buf, "high", row.high); + buf.push(b','); + write_binary_f64(buf, "low", row.low); + buf.push(b','); + write_binary_f64(buf, "close", row.close); + + buf.push(b' '); + write_i64_decimal(buf, row.ts); + buf.extend_from_slice(b"t\n"); + Ok(()) +} + +struct ShardState { + sink: W, + buf: Vec, + pending_rows: usize, + written_rows: usize, +} + +/// Deterministic, sink-agnostic sharded QuestDB ILP v2 batch writer. +/// +/// Buffers complete ILP lines per shard and flushes whole-line batches to injected [`Write`] +/// sinks when either `max_batch_rows` or `max_batch_bytes` is reached, or on [`Self::finish`]. +pub struct IlpShardedWriter { + shards: Vec>, + options: IlpWriterOptions, + scratch: Vec, + rows_written: usize, + bytes_written: usize, + flushes: usize, + poisoned_shard: Option, +} + +impl IlpShardedWriter { + /// Creates a new sharded writer over `sinks` with the given batching `options`. + /// + /// Returns an error if `sinks` is empty or either batch limit is zero. + pub fn new(sinks: Vec, options: IlpWriterOptions) -> Result { + if sinks.is_empty() { + return Err(IlpWriterError::EmptySinks); + } + if options.max_batch_bytes == 0 { + return Err(IlpWriterError::ZeroMaxBatchBytes); + } + if options.max_batch_rows == 0 { + return Err(IlpWriterError::ZeroMaxBatchRows); + } + + let initial_buf_cap = options.max_batch_bytes.min(DEFAULT_ILP_MAX_BATCH_BYTES); + let shards = sinks + .into_iter() + .map(|sink| ShardState { + sink, + buf: Vec::with_capacity(initial_buf_cap), + pending_rows: 0, + written_rows: 0, + }) + .collect(); + + Ok(Self { + shards, + options, + scratch: Vec::with_capacity(256), + rows_written: 0, + bytes_written: 0, + flushes: 0, + poisoned_shard: None, + }) + } + + /// Returns the number of configured shards. + #[inline] + pub fn shard_count(&self) -> usize { + self.shards.len() + } + + /// Encodes and buffers one `bars_1m` row on the shard determined by `row.key`. + pub fn write_bar_1m( + &mut self, + row: &Bar1mRow, + known_at_micros: i64, + ) -> Result<(), IlpWriterError> { + if let Some(failed_shard) = self.poisoned_shard { + return Err(IlpWriterError::Poisoned { failed_shard }); + } + self.scratch.clear(); + encode_bar_1m(&mut self.scratch, row, known_at_micros)?; + let shard_idx = shard_for_listing_id(row.key, self.shards.len()); + self.enqueue_scratch_row(shard_idx) + } + + /// Encodes and buffers one `fx_1m` row on the shard determined by `row.pair`. + pub fn write_fx_1m(&mut self, row: &Fx1mRow<'_>) -> Result<(), IlpWriterError> { + if let Some(failed_shard) = self.poisoned_shard { + return Err(IlpWriterError::Poisoned { failed_shard }); + } + self.scratch.clear(); + encode_fx_1m(&mut self.scratch, row)?; + let shard_idx = shard_for_fx_pair(row.pair, self.shards.len()); + self.enqueue_scratch_row(shard_idx) + } + + /// Flushes all remaining buffered batches and underlying sinks, returning write statistics. + pub fn finish(mut self) -> Result { + if let Some(failed_shard) = self.poisoned_shard { + return Err(IlpWriterError::Poisoned { failed_shard }); + } + + for shard_idx in 0..self.shards.len() { + if !self.shards[shard_idx].buf.is_empty() { + self.flush_shard(shard_idx)?; + } + if let Err(source) = self.shards[shard_idx].sink.flush() { + self.poisoned_shard = Some(shard_idx); + return Err(IlpWriterError::Io { + shard: shard_idx, + source, + }); + } + } + + let per_shard_rows = self.shards.iter().map(|s| s.written_rows).collect(); + Ok(IlpWriteStats { + rows: self.rows_written, + bytes: self.bytes_written, + flushes: self.flushes, + per_shard_rows, + }) + } + + fn enqueue_scratch_row(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> { + let row_len = self.scratch.len(); + let needs_preflush = { + let shard = &self.shards[shard_idx]; + !shard.buf.is_empty() + && shard.buf.len().saturating_add(row_len) > self.options.max_batch_bytes + }; + if needs_preflush { + self.flush_shard(shard_idx)?; + } + + let needs_postflush = { + let shard = &mut self.shards[shard_idx]; + shard.buf.extend_from_slice(&self.scratch); + shard.pending_rows += 1; + shard.pending_rows >= self.options.max_batch_rows + || shard.buf.len() >= self.options.max_batch_bytes + }; + if needs_postflush { + self.flush_shard(shard_idx)?; + } + + Ok(()) + } + + fn flush_shard(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> { + let shard = &mut self.shards[shard_idx]; + if shard.buf.is_empty() { + return Ok(()); + } + if let Err(source) = shard.sink.write_all(&shard.buf) { + self.poisoned_shard = Some(shard_idx); + return Err(IlpWriterError::Io { + shard: shard_idx, + source, + }); + } + + let bytes = shard.buf.len(); + let rows = shard.pending_rows; + shard.buf.clear(); + shard.pending_rows = 0; + shard.written_rows += rows; + self.rows_written += rows; + self.bytes_written += bytes; + self.flushes += 1; + Ok(()) + } +} + +#[cfg(test)] +#[path = "ilp_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/ilp_tests.rs b/tools/curate-etl/src/ilp_tests.rs new file mode 100644 index 00000000..5ff705ed --- /dev/null +++ b/tools/curate-etl/src/ilp_tests.rs @@ -0,0 +1,765 @@ +use std::collections::HashMap; +use std::io::{self, Write}; +use std::sync::{Arc, Mutex}; + +use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD}; + +use super::{ + encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Fx1mRow, + IlpEncodeError, IlpShardedWriter, IlpWriterError, IlpWriterOptions, ILP_V2_DOUBLE_TYPE, +}; + +fn sample_bar(listing_id: i32, ts: i64) -> Bar1mRow { + Bar1mRow { + key: listing_id, + ts, + session_date: 20_100, + open: 123.45, + high: 125.75, + low: 122.125, + close: 124.5, + volume: 98_765.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_EOD, + } +} + +fn sample_fx(pair: &'static str, ts: i64) -> Fx1mRow<'static> { + Fx1mRow { + pair, + ts, + open: 1.3625, + high: 1.3650, + low: 1.3610, + close: 1.3642, + source: "eod", + } +} + +/// Minimal ILP v2 frame splitter that respects escaped symbols and fixed-width 8-byte binary +/// `DOUBLE` payloads (`==\x10<8 bytes>`), so embedded `0x0a` bytes inside binary doubles or +/// escaped `\n` in symbols never falsely split a row. +fn split_ilp_v2_rows(data: &[u8]) -> Vec<&[u8]> { + let mut rows = Vec::new(); + let mut i = 0usize; + let len = data.len(); + + while i < len { + let start = i; + // 1. Tag set (table + symbols) ends at unescaped ASCII space. + while i < len { + match data[i] { + b'\\' => { + assert!(i + 1 < len, "dangling backslash in ILP tag set"); + i += 2; + } + b' ' => { + i += 1; + break; + } + _ => i += 1, + } + } + assert!(i < len, "unexpected EOF after ILP tag set"); + + // 2. Field set ends at ASCII space; skip fixed 8-byte binary double payloads after `==\x10`. + while i < len { + if data[i] == b' ' { + i += 1; + break; + } + if data[i] == b'=' && i + 2 < len && data[i + 1] == b'=' && data[i + 2] == ILP_V2_DOUBLE_TYPE + { + assert!( + i + 3 + 8 <= len, + "truncated binary DOUBLE payload in ILP field set" + ); + i += 3 + 8; + } else { + i += 1; + } + } + assert!(i < len, "unexpected EOF after ILP field set"); + + // 3. Designated timestamp runs to unescaped LF. + while i < len && data[i] != b'\n' { + i += 1; + } + assert!(i < len && data[i] == b'\n', "ILP row missing trailing LF"); + i += 1; + rows.push(&data[start..i]); + } + + rows +} + +fn extract_tag_value<'a>(row: &'a [u8], tag_prefix: &[u8]) -> &'a [u8] { + let mut i = 0usize; + let tag_end = loop { + assert!(i < row.len(), "missing space after tag set"); + match row[i] { + b'\\' => i += 2, + b' ' => break i, + _ => i += 1, + } + }; + let tag_section = &row[..tag_end]; + let pos = tag_section + .windows(tag_prefix.len()) + .position(|w| w == tag_prefix) + .expect("expected tag prefix in row"); + let val_start = pos + tag_prefix.len(); + let mut j = val_start; + while j < tag_end { + match tag_section[j] { + b'\\' => j += 2, + b',' => break, + _ => j += 1, + } + } + &tag_section[val_start..j] +} + +#[derive(Clone, Default)] +struct RecordingSink { + writes: Arc>>>, + flush_calls: Arc>, + fail_on_write_call: Option, + fail_on_flush: bool, +} + +impl RecordingSink { + fn new() -> Self { + Self::default() + } + + fn failing_on_write(call_index: usize) -> Self { + Self { + fail_on_write_call: Some(call_index), + ..Self::default() + } + } + + fn failing_on_flush() -> Self { + Self { + fail_on_flush: true, + ..Self::default() + } + } + + fn captured_writes(&self) -> Vec> { + self.writes.lock().unwrap().clone() + } + + fn captured_flushes(&self) -> usize { + *self.flush_calls.lock().unwrap() + } +} + +impl Write for RecordingSink { + fn write(&mut self, buf: &[u8]) -> io::Result { + let mut writes = self.writes.lock().unwrap(); + let call_idx = writes.len(); + if self.fail_on_write_call == Some(call_idx) { + return Err(io::Error::new( + io::ErrorKind::BrokenPipe, + format!("injected write failure on call {call_idx}"), + )); + } + writes.push(buf.to_vec()); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + let mut flushes = self.flush_calls.lock().unwrap(); + *flushes += 1; + if self.fail_on_flush { + return Err(io::Error::new( + io::ErrorKind::ConnectionReset, + "injected flush failure", + )); + } + Ok(()) + } +} + +#[test] +fn golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract() { + let row = Bar1mRow { + key: 42, + ts: 1_736_951_400_000_000, + session_date: 20_103, + open: 150.25, + high: 151.75, + low: 149.5, + close: 151.125, + volume: 12_345.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_EOD, + }; + let known_at_micros = 1_736_951_460_123_456_i64; + + let mut actual = Vec::new(); + encode_bar_1m(&mut actual, &row, known_at_micros).expect("encode bar_1m"); + + let mut expected = Vec::new(); + expected.extend_from_slice(b"bars_1m,listing_id=42,session=RTH,source=eod_unadj "); + expected.extend_from_slice(b"open==\x10"); + expected.extend_from_slice(&150.25_f64.to_le_bytes()); + expected.extend_from_slice(b",high==\x10"); + expected.extend_from_slice(&151.75_f64.to_le_bytes()); + expected.extend_from_slice(b",low==\x10"); + expected.extend_from_slice(&149.5_f64.to_le_bytes()); + expected.extend_from_slice(b",close==\x10"); + expected.extend_from_slice(&151.125_f64.to_le_bytes()); + expected.extend_from_slice(b",volume==\x10"); + expected.extend_from_slice(&12_345.0_f64.to_le_bytes()); + expected.extend_from_slice(b",known_at=1736951460123456t 1736951400000000t\n"); + + assert_eq!(actual, expected); + assert!( + !actual.windows(4).any(|w| w == b"vwap"), + "vwap must be omitted for bars_1m" + ); + + // Round-trip every binary DOUBLE payload bit-exactly via f64::from_le_bytes. + for (prefix, expected_val) in [ + (&b"open==\x10"[..], row.open), + (&b",high==\x10"[..], row.high), + (&b",low==\x10"[..], row.low), + (&b",close==\x10"[..], row.close), + (&b",volume==\x10"[..], row.volume), + ] { + let pos = actual + .windows(prefix.len()) + .position(|w| w == prefix) + .expect("binary double column present"); + let raw: [u8; 8] = actual[pos + prefix.len()..pos + prefix.len() + 8] + .try_into() + .unwrap(); + let decoded = f64::from_le_bytes(raw); + assert_eq!(decoded.to_bits(), expected_val.to_bits()); + } + + // Verify PRE and POST session tags as well. + let mut pre_buf = Vec::new(); + let mut pre_row = row.clone(); + pre_row.session = IntradaySession::Pre; + encode_bar_1m(&mut pre_buf, &pre_row, known_at_micros).unwrap(); + assert!(pre_buf.starts_with(b"bars_1m,listing_id=42,session=PRE,source=eod_unadj ")); + + let mut post_buf = Vec::new(); + let mut post_row = row; + post_row.session = IntradaySession::Post; + encode_bar_1m(&mut post_buf, &post_row, known_at_micros).unwrap(); + assert!(post_buf.starts_with(b"bars_1m,listing_id=42,session=POST,source=eod_unadj ")); +} + +#[test] +fn golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract() { + let row = Fx1mRow { + pair: "USD.CAD", + ts: 1_736_951_400_000_000, + open: 1.3625, + high: 1.365, + low: 1.36125, + close: 1.364375, + source: "eod", + }; + + let mut actual = Vec::new(); + encode_fx_1m(&mut actual, &row).expect("encode fx_1m"); + + let mut expected = Vec::new(); + expected.extend_from_slice(b"fx_1m,pair=USD.CAD,source=eod "); + expected.extend_from_slice(b"open==\x10"); + expected.extend_from_slice(&1.3625_f64.to_le_bytes()); + expected.extend_from_slice(b",high==\x10"); + expected.extend_from_slice(&1.365_f64.to_le_bytes()); + expected.extend_from_slice(b",low==\x10"); + expected.extend_from_slice(&1.36125_f64.to_le_bytes()); + expected.extend_from_slice(b",close==\x10"); + expected.extend_from_slice(&1.364375_f64.to_le_bytes()); + expected.extend_from_slice(b" 1736951400000000t\n"); + + assert_eq!(actual, expected); + assert!(!actual.windows(8).any(|w| w == b"known_at")); + assert!(!actual.windows(6).any(|w| w == b"volume")); + + for (prefix, expected_val) in [ + (&b"open==\x10"[..], row.open), + (&b",high==\x10"[..], row.high), + (&b",low==\x10"[..], row.low), + (&b",close==\x10"[..], row.close), + ] { + let pos = actual + .windows(prefix.len()) + .position(|w| w == prefix) + .expect("binary double column present"); + let raw: [u8; 8] = actual[pos + prefix.len()..pos + prefix.len() + 8] + .try_into() + .unwrap(); + assert_eq!(f64::from_le_bytes(raw).to_bits(), expected_val.to_bits()); + } +} + +#[test] +fn symbol_escaping_and_non_finite_or_negative_ts_atomic_rejection() { + // Escaping: space, comma, '=', backslash, LF, CR, and UTF-8. + let raw_sym = "a b,c=d\\e\nf\rg caf\u{00e9}"; + let expected_escaped = b"a\\ b\\,c\\=d\\\\e\\\nf\\\rg\\ caf\xc3\xa9"; + + let mut bar = sample_bar(7, 0); + bar.source = raw_sym; + let mut bar_buf = Vec::new(); + encode_bar_1m(&mut bar_buf, &bar, -500).expect("encode escaped bar_1m"); + let mut expected_prefix = b"bars_1m,listing_id=7,session=RTH,source=".to_vec(); + expected_prefix.extend_from_slice(expected_escaped); + expected_prefix.push(b' '); + assert!(bar_buf.starts_with(&expected_prefix)); + assert!(bar_buf.ends_with(b",known_at=-500t 0t\n")); + + let fx = Fx1mRow { + pair: raw_sym, + source: "src=1,2 3\\4\n\r", + ..sample_fx("USD.CAD", 123) + }; + let mut fx_buf = Vec::new(); + encode_fx_1m(&mut fx_buf, &fx).expect("encode escaped fx_1m"); + let mut expected_fx_prefix = b"fx_1m,pair=".to_vec(); + expected_fx_prefix.extend_from_slice(expected_escaped); + expected_fx_prefix.extend_from_slice(b",source=src\\=1\\,2\\ 3\\\\4\\\n\\\r "); + assert!(fx_buf.starts_with(&expected_fx_prefix)); + assert!(fx_buf.ends_with(b" 123t\n")); + + // Non-finite doubles in a late field must fail atomically and preserve existing buffer bytes. + let sentinel = b"EXISTING_PREFIX_BYTES".to_vec(); + for bad_val in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut buf = sentinel.clone(); + let mut bad_bar = sample_bar(1, 100); + bad_bar.volume = bad_val; + let err = encode_bar_1m(&mut buf, &bad_bar, 200).unwrap_err(); + assert!(matches!( + err, + IlpEncodeError::NonFiniteDouble { + field: "volume", + .. + } + )); + assert_eq!(buf, sentinel, "buffer must be untouched on bars_1m error"); + + let mut fx_buf = sentinel.clone(); + let mut bad_fx = sample_fx("USD.CAD", 100); + bad_fx.close = bad_val; + let err = encode_fx_1m(&mut fx_buf, &bad_fx).unwrap_err(); + assert!(matches!( + err, + IlpEncodeError::NonFiniteDouble { field: "close", .. } + )); + assert_eq!(fx_buf, sentinel, "buffer must be untouched on fx_1m error"); + } + + // Negative designated timestamp fails atomically. + let mut buf = sentinel.clone(); + let bad_ts_bar = sample_bar(1, -1); + assert_eq!( + encode_bar_1m(&mut buf, &bad_ts_bar, 500), + Err(IlpEncodeError::NegativeTimestamp { + field: "ts", + value: -1 + }) + ); + assert_eq!(buf, sentinel); + + let mut fx_buf = sentinel.clone(); + let bad_ts_fx = sample_fx("USD.CAD", -42); + assert_eq!( + encode_fx_1m(&mut fx_buf, &bad_ts_fx), + Err(IlpEncodeError::NegativeTimestamp { + field: "ts", + value: -42 + }) + ); + assert_eq!(fx_buf, sentinel); + + // Empty symbol fails atomically. + let mut buf = sentinel.clone(); + let mut empty_src = sample_bar(1, 100); + empty_src.source = ""; + assert_eq!( + encode_bar_1m(&mut buf, &empty_src, 100), + Err(IlpEncodeError::EmptySymbol { field: "source" }) + ); + assert_eq!(buf, sentinel); + + let mut fx_buf = sentinel.clone(); + let empty_pair = sample_fx("", 100); + assert_eq!( + encode_fx_1m(&mut fx_buf, &empty_pair), + Err(IlpEncodeError::EmptySymbol { field: "pair" }) + ); + assert_eq!(fx_buf, sentinel); +} + +#[test] +fn sharded_writer_routes_deterministically_preserves_per_key_order_and_handles_embedded_lf() { + // Build a finite double whose IEEE-754 little-endian representation contains 0x0a (LF). + let double_with_lf = f64::from_le_bytes([0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x24, 0x40]); + assert!(double_with_lf.is_finite()); + + let num_shards = 4usize; + let num_listings = 64i32; + let rows_per_listing = 20usize; // 64 * 20 = 1,280 interleaved rows >= 1,000 + + let mut input_rows: Vec<(Bar1mRow, i64)> = + Vec::with_capacity(num_listings as usize * rows_per_listing + 2); + for step in 0..rows_per_listing { + for listing_id in 1..=num_listings { + let ts = 1_700_000_000_000_000 + (step as i64) * 60_000_000 + i64::from(listing_id); + let known_at = ts + 60_000_000; + let mut row = sample_bar(listing_id, ts); + row.open = double_with_lf; + row.close = 100.0 + (step as f64) * 0.25 + f64::from(listing_id) * 0.01; + row.volume = (step as f64 + 1.0) * 100.0; + if step == 5 && listing_id == 10 { + row.source = "eod\nwith_lf"; + } + input_rows.push((row, known_at)); + } + } + // Append a second version of an existing (ts, listing_id) to verify DEDUP UPSERT ordering. + let (mut revision, rev_known_at) = input_rows[0].clone(); + revision.close += 0.5; + input_rows.push((revision, rev_known_at + 120_000_000)); + + // Expected per-listing byte sequences in input order. + let mut expected_by_listing: HashMap>> = HashMap::new(); + for (row, known_at) in &input_rows { + let mut line = Vec::new(); + encode_bar_1m(&mut line, row, *known_at).unwrap(); + expected_by_listing.entry(row.key).or_default().push(line); + } + + let opts = IlpWriterOptions { + max_batch_bytes: 2048, + max_batch_rows: 17, + }; + + let run_once = || { + let mut sinks: Vec> = (0..num_shards).map(|_| Vec::new()).collect(); + let stats = { + let sink_refs: Vec<&mut Vec> = sinks.iter_mut().collect(); + let mut writer = IlpShardedWriter::new(sink_refs, opts).unwrap(); + for (row, known_at) in &input_rows { + writer.write_bar_1m(row, *known_at).unwrap(); + } + writer.finish().unwrap() + }; + (sinks, stats) + }; + + let (sinks_a, stats_a) = run_once(); + let (sinks_b, stats_b) = run_once(); + + // Byte-for-byte determinism across runs. + assert_eq!(sinks_a, sinks_b); + assert_eq!(stats_a, stats_b); + + // Conservation invariants. + assert_eq!(stats_a.rows, input_rows.len()); + assert_eq!( + stats_a.per_shard_rows.iter().sum::(), + stats_a.rows + ); + let total_sink_bytes: usize = sinks_a.iter().map(Vec::len).sum(); + assert_eq!(stats_a.bytes, total_sink_bytes); + + // Parse every shard with the binary-aware ILP v2 splitter and verify routing + order. + let mut seen_shard_for_listing: HashMap = HashMap::new(); + let mut observed_by_listing: HashMap>> = HashMap::new(); + let mut total_parsed_rows = 0usize; + + for (shard_idx, shard_bytes) in sinks_a.iter().enumerate() { + let parsed = split_ilp_v2_rows(shard_bytes); + assert_eq!(parsed.len(), stats_a.per_shard_rows[shard_idx]); + total_parsed_rows += parsed.len(); + + for row_bytes in parsed { + let id_bytes = extract_tag_value(row_bytes, b",listing_id="); + let listing_id: i32 = std::str::from_utf8(id_bytes).unwrap().parse().unwrap(); + assert_eq!( + shard_idx, + shard_for_listing_id(listing_id, num_shards), + "listing_id {listing_id} routed to unexpected shard" + ); + if let Some(&prev_shard) = seen_shard_for_listing.get(&listing_id) { + assert_eq!(prev_shard, shard_idx); + } else { + seen_shard_for_listing.insert(listing_id, shard_idx); + } + observed_by_listing + .entry(listing_id) + .or_default() + .push(row_bytes.to_vec()); + } + } + + assert_eq!(total_parsed_rows, input_rows.len()); + assert_eq!(seen_shard_for_listing.len(), num_listings as usize); + assert_eq!(observed_by_listing, expected_by_listing); + + // Repeated FX pairs across batches route by `pair` and preserve order. + let pairs = ["USD.CAD", "EUR.USD", "GBP.USD", "USD.JPY", "AUD.USD", "USD.CHF"]; + let mut fx_sinks: Vec> = (0..num_shards).map(|_| Vec::new()).collect(); + let mut expected_by_pair: HashMap<&str, Vec>> = HashMap::new(); + let fx_stats = { + let refs: Vec<&mut Vec> = fx_sinks.iter_mut().collect(); + let mut writer = IlpShardedWriter::new( + refs, + IlpWriterOptions { + max_batch_bytes: 512, + max_batch_rows: 3, + }, + ) + .unwrap(); + for step in 0..10 { + for &pair in &pairs { + let mut row = sample_fx(pair, 1_700_000_000_000_000 + step * 60_000_000); + row.close += (step as f64) * 0.0001; + let mut line = Vec::new(); + encode_fx_1m(&mut line, &row).unwrap(); + expected_by_pair.entry(pair).or_default().push(line); + writer.write_fx_1m(&row).unwrap(); + } + } + writer.finish().unwrap() + }; + assert_eq!(fx_stats.rows, pairs.len() * 10); + assert_eq!(fx_stats.per_shard_rows.iter().sum::(), fx_stats.rows); + assert_eq!(fx_stats.bytes, fx_sinks.iter().map(Vec::len).sum::()); + + let mut observed_by_pair: HashMap>> = HashMap::new(); + for (shard_idx, shard_bytes) in fx_sinks.iter().enumerate() { + for row_bytes in split_ilp_v2_rows(shard_bytes) { + let pair_str = + std::str::from_utf8(extract_tag_value(row_bytes, b",pair=")).unwrap(); + assert_eq!(shard_idx, shard_for_fx_pair(pair_str, num_shards)); + observed_by_pair + .entry(pair_str.to_string()) + .or_default() + .push(row_bytes.to_vec()); + } + } + for (pair, expected) in expected_by_pair { + assert_eq!(observed_by_pair.get(pair).unwrap(), &expected); + } +} + +#[test] +fn batching_limits_oversized_lines_remainder_and_whole_line_boundaries() { + let row = sample_bar(42, 1_736_951_400_000_000); + let known_at = 1_736_951_460_000_000; + let mut one_line = Vec::new(); + encode_bar_1m(&mut one_line, &row, known_at).unwrap(); + let row_len = one_line.len(); + + // 1. Exact row limit (max_batch_rows = 3) + 1 remainder row. + let sink = RecordingSink::new(); + let mut writer = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { + max_batch_bytes: 100_000, + max_batch_rows: 3, + }, + ) + .unwrap(); + for _ in 0..7 { + writer.write_bar_1m(&row, known_at).unwrap(); + } + let stats = writer.finish().unwrap(); + let writes = sink.captured_writes(); + assert_eq!(writes.len(), 3); + assert_eq!(stats.flushes, 3); + assert_eq!(stats.rows, 7); + assert_eq!(stats.bytes, 7 * row_len); + assert_eq!(sink.captured_flushes(), 1); + assert_eq!(split_ilp_v2_rows(&writes[0]).len(), 3); + assert_eq!(split_ilp_v2_rows(&writes[1]).len(), 3); + assert_eq!(split_ilp_v2_rows(&writes[2]).len(), 1); + assert!(writes.iter().all(|w| w.ends_with(b"\n"))); + + // 2. Exact byte limit (2 * row_len): flushes after every 2 rows. + let sink = RecordingSink::new(); + let mut writer = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { + max_batch_bytes: 2 * row_len, + max_batch_rows: 100, + }, + ) + .unwrap(); + for _ in 0..5 { + writer.write_bar_1m(&row, known_at).unwrap(); + } + let stats = writer.finish().unwrap(); + let writes = sink.captured_writes(); + assert_eq!(writes.len(), 3); + assert_eq!(stats.flushes, 3); + assert_eq!(split_ilp_v2_rows(&writes[0]).len(), 2); + assert_eq!(split_ilp_v2_rows(&writes[1]).len(), 2); + assert_eq!(split_ilp_v2_rows(&writes[2]).len(), 1); + + // 3. Next line would exceed remaining capacity (2 * row_len - 1): flushes before appending. + let sink = RecordingSink::new(); + let mut writer = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { + max_batch_bytes: 2 * row_len - 1, + max_batch_rows: 100, + }, + ) + .unwrap(); + for _ in 0..3 { + writer.write_bar_1m(&row, known_at).unwrap(); + } + let stats = writer.finish().unwrap(); + let writes = sink.captured_writes(); + assert_eq!(writes.len(), 3); + assert_eq!(stats.flushes, 3); + for w in &writes { + assert_eq!(w.len(), row_len); + assert_eq!(split_ilp_v2_rows(w).len(), 1); + } + + // 4. Individually oversized line (max_batch_bytes = 16 < row_len) sent alone, never split. + let sink = RecordingSink::new(); + let mut writer = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { + max_batch_bytes: 16, + max_batch_rows: 100, + }, + ) + .unwrap(); + writer.write_bar_1m(&row, known_at).unwrap(); + writer.write_bar_1m(&row, known_at).unwrap(); + let stats = writer.finish().unwrap(); + let writes = sink.captured_writes(); + assert_eq!(writes.len(), 2); + assert_eq!(stats.flushes, 2); + assert_eq!(writes[0], one_line); + assert_eq!(writes[1], one_line); +} + +#[test] +fn writer_validates_options_handles_zero_rows_and_poisons_on_io_error() { + assert!(matches!( + IlpShardedWriter::>::new(Vec::new(), IlpWriterOptions::default()), + Err(IlpWriterError::EmptySinks) + )); + assert!(matches!( + IlpShardedWriter::new( + vec![Vec::new()], + IlpWriterOptions { + max_batch_bytes: 0, + max_batch_rows: 10, + } + ), + Err(IlpWriterError::ZeroMaxBatchBytes) + )); + assert!(matches!( + IlpShardedWriter::new( + vec![Vec::new()], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 0, + } + ), + Err(IlpWriterError::ZeroMaxBatchRows) + )); + + // Zero rows written -> clean stats and sink flush still called. + let s0 = RecordingSink::new(); + let s1 = RecordingSink::new(); + let writer = IlpShardedWriter::new(vec![s0.clone(), s1.clone()], IlpWriterOptions::default()) + .unwrap(); + let stats = writer.finish().unwrap(); + assert_eq!(stats.rows, 0); + assert_eq!(stats.bytes, 0); + assert_eq!(stats.flushes, 0); + assert_eq!(stats.per_shard_rows, vec![0, 0]); + assert_eq!(s0.captured_flushes(), 1); + assert_eq!(s1.captured_flushes(), 1); + + // Find a listing_id that routes to shard 2 out of 4. + let target_listing = (1..1000) + .find(|&id| shard_for_listing_id(id, 4) == 2) + .expect("listing for shard 2"); + + // Failing write_all on shard 2 after 1 successful batch: returns Io { shard: 2 } and poisons. + let failing_sink = RecordingSink::failing_on_write(1); + let mut writer = IlpShardedWriter::new( + vec![ + RecordingSink::new(), + RecordingSink::new(), + failing_sink.clone(), + RecordingSink::new(), + ], + IlpWriterOptions { + max_batch_bytes: 100_000, + max_batch_rows: 1, + }, + ) + .unwrap(); + let row = sample_bar(target_listing, 1_700_000_000_000_000); + writer.write_bar_1m(&row, 1_700_000_060_000_000).unwrap(); + let err = writer + .write_bar_1m(&row, 1_700_000_120_000_000) + .unwrap_err(); + assert!(matches!(err, IlpWriterError::Io { shard: 2, .. })); + + // Subsequent writes and finish fail with Poisoned { failed_shard: 2 }. + let err2 = writer + .write_bar_1m(&row, 1_700_000_180_000_000) + .unwrap_err(); + assert!(matches!(err2, IlpWriterError::Poisoned { failed_shard: 2 })); + let err3 = writer.write_fx_1m(&sample_fx("USD.CAD", 100)).unwrap_err(); + assert!(matches!(err3, IlpWriterError::Poisoned { failed_shard: 2 })); + let err4 = writer.finish().unwrap_err(); + assert!(matches!(err4, IlpWriterError::Poisoned { failed_shard: 2 })); + assert_eq!(failing_sink.captured_writes().len(), 1); + + // Failing flush() during finish() reports shard index. + let mut writer = IlpShardedWriter::new( + vec![RecordingSink::new(), RecordingSink::failing_on_flush()], + IlpWriterOptions::default(), + ) + .unwrap(); + writer.write_bar_1m(&row, 1_700_000_060_000_000).unwrap(); + let flush_err = writer.finish().unwrap_err(); + assert!(matches!(flush_err, IlpWriterError::Io { shard: 1, .. })); + + // Encode error does not poison the writer. + let mut sinks = [Vec::new(), Vec::new()]; + let stats = { + let refs: Vec<&mut Vec> = sinks.iter_mut().collect(); + let mut writer = IlpShardedWriter::new(refs, IlpWriterOptions::default()).unwrap(); + let mut bad = sample_bar(42, 100); + bad.close = f64::NAN; + assert!(matches!( + writer.write_bar_1m(&bad, 200), + Err(IlpWriterError::Encode(IlpEncodeError::NonFiniteDouble { + field: "close", + .. + })) + )); + writer + .write_bar_1m(&sample_bar(42, 100), 200) + .expect("writer still healthy after encode error"); + writer.finish().unwrap() + }; + assert_eq!(stats.rows, 1); + + // Sanity check FNV-1a 64-bit known test vector ("foobar" -> 0x85944171f73967e8). + assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index eaefb854..cd76c47d 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -15,6 +15,7 @@ pub mod cli; pub mod corporate_actions; pub mod events; pub mod fx; +pub mod ilp; pub mod mongo_safety; pub mod mongo_stream; pub mod parquet_adj; @@ -104,6 +105,12 @@ pub use fx::{ build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource, FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD, }; +pub use ilp::{ + encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Fx1mRow, + IlpEncodeError, IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, + DEFAULT_ILP_MAX_BATCH_BYTES, DEFAULT_ILP_MAX_BATCH_ROWS, FNV1A_64_OFFSET_BASIS, + FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M, +}; pub use mongo_safety::{ assert_read_only_mongo_uri, is_qa_mongo_target, parse_mongo_target, LocalHosts, MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index aa9acace..1c66d48e 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -11,7 +11,8 @@ use curate_etl::bench::{ run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark, run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark, - run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark, + run_fx_benchmark, run_ilp_bars_1m_benchmark, run_mongo_stream_benchmark, + run_parquet_adj_benchmark, run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, @@ -378,6 +379,33 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchIlpBars1m(rows)) => { + let report = match run_ilp_bars_1m_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: ilp bars_1m benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-ilp-bars-1m"); + println!( + " input: rows={} keys={} shards={}", + report.rows, report.key_count, report.shards + ); + println!( + " output: rows_encoded={} bytes={} flushes={} per_shard_rows={:?}", + report.rows_encoded, report.bytes, report.flushes, report.per_shard_rows + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row size={:.2} bytes/row write={:.2} MB/s", + report.elapsed_ms, + report.rows_per_sec, + report.ns_per_row, + report.bytes_per_row, + report.mb_per_sec + ); + ExitCode::SUCCESS + } Ok(CliAction::BenchFx(rows)) => { let report = run_fx_benchmark(rows); println!("curate-etl bench-fx"); diff --git a/tools/curate-etl/tests/cli.rs b/tools/curate-etl/tests/cli.rs index 055232fc..8902eb10 100644 --- a/tools/curate-etl/tests/cli.rs +++ b/tools/curate-etl/tests/cli.rs @@ -46,6 +46,7 @@ fn no_args_and_help_print_usage_and_succeed() { "{args:?}: {text}" ); assert!(text.contains("bench-split"), "{args:?}: {text}"); + assert!(text.contains("bench-ilp-bars-1m"), "{args:?}: {text}"); assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}"); assert!(text.contains("bench-fx"), "{args:?}: {text}"); assert!(text.contains("bench-events"), "{args:?}: {text}"); @@ -90,6 +91,10 @@ fn invalid_invocations_exit_nonzero_with_usage_on_stderr() { &["bench-curate-fx", "0"][..], &["bench-curate-fx", "-5"][..], &["bench-curate-fx", "10", "20"][..], + &["bench-ilp-bars-1m", "abc"][..], + &["bench-ilp-bars-1m", "0"][..], + &["bench-ilp-bars-1m", "-5"][..], + &["bench-ilp-bars-1m", "10", "20"][..], &["--unknown"][..], &["export"][..], ] { @@ -260,6 +265,33 @@ fn bench_curate_fx_small_run_is_headless_deterministic_and_reports_rates() { assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes=")); } +#[test] +fn bench_ilp_bars_1m_small_run_is_headless_deterministic_and_reports_rates() { + let a = run(&["bench-ilp-bars-1m", "2000"]); + let b = run(&["bench-ilp-bars-1m", "2000"]); + assert!(a.status.success(), "{}", stderr(&a)); + assert!(b.status.success(), "{}", stderr(&b)); + assert!(stderr(&a).is_empty(), "unexpected stderr: {}", stderr(&a)); + assert!(stderr(&b).is_empty(), "unexpected stderr: {}", stderr(&b)); + + let text_a = stdout(&a); + let text_b = stdout(&b); + assert!(text_a.contains("curate-etl bench-ilp-bars-1m"), "{text_a}"); + assert!(text_a.contains("rows=2000 "), "{text_a}"); + assert!(text_a.contains("rows_encoded=2000 "), "{text_a}"); + assert!(text_a.contains("rows/s"), "{text_a}"); + assert!(text_a.contains("bytes/row"), "{text_a}"); + assert!(text_a.contains("MB/s"), "{text_a}"); + + let field = |s: &str, prefix: &str| { + s.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(str::to_owned) + }; + assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes=")); + assert_eq!(field(&text_a, "flushes="), field(&text_b, "flushes=")); +} + static CLI_TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); struct CliTempDir { From b287a69d54e476473d899341be775e5876543f5c Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:05:09 -0500 Subject: [PATCH 08/36] =?UTF-8?q?T-137:=20M2.3c=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20QuestDB=20ILP=20v2=20encoder=20+=20sharded=20b?= =?UTF-8?q?atch=20writer=20for=20`bars=5F1m`=20/=20`fx=5F1m`=20over=20inje?= =?UTF-8?q?cted=20`Write`=20sinks=20(no=20new=20crates,=20no=20live=20Ques?= =?UTF-8?q?tDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/ilp_tests.rs | 138 ++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) diff --git a/tools/curate-etl/src/ilp_tests.rs b/tools/curate-etl/src/ilp_tests.rs index 5ff705ed..775d1686 100644 --- a/tools/curate-etl/src/ilp_tests.rs +++ b/tools/curate-etl/src/ilp_tests.rs @@ -125,6 +125,9 @@ struct RecordingSink { writes: Arc>>>, flush_calls: Arc>, fail_on_write_call: Option, + /// `(call_index, prefix_bytes)`: on `call_index`, accept only `prefix_bytes` and then fail + /// on the subsequent `write()` call inside `write_all()`. + partial_then_fail_on_write_call: Option<(usize, usize)>, fail_on_flush: bool, } @@ -140,6 +143,13 @@ impl RecordingSink { } } + fn failing_after_partial_write(call_index: usize, prefix_bytes: usize) -> Self { + Self { + partial_then_fail_on_write_call: Some((call_index, prefix_bytes)), + ..Self::default() + } + } + fn failing_on_flush() -> Self { Self { fail_on_flush: true, @@ -151,6 +161,15 @@ impl RecordingSink { self.writes.lock().unwrap().clone() } + fn captured_bytes(&self) -> Vec { + self.writes + .lock() + .unwrap() + .iter() + .flat_map(|w| w.iter().copied()) + .collect() + } + fn captured_flushes(&self) -> usize { *self.flush_calls.lock().unwrap() } @@ -166,6 +185,19 @@ impl Write for RecordingSink { format!("injected write failure on call {call_idx}"), )); } + if let Some((partial_call, prefix_bytes)) = self.partial_then_fail_on_write_call { + if call_idx == partial_call { + let n = prefix_bytes.min(buf.len()); + writes.push(buf[..n].to_vec()); + return Ok(n); + } + if call_idx > partial_call { + return Err(io::Error::new( + io::ErrorKind::BrokenPipe, + format!("injected write failure after partial write on call {call_idx}"), + )); + } + } writes.push(buf.to_vec()); Ok(buf.len()) } @@ -763,3 +795,109 @@ fn writer_validates_options_handles_zero_rows_and_poisons_on_io_error() { // Sanity check FNV-1a 64-bit known test vector ("foobar" -> 0x85944171f73967e8). assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8); } + +#[test] +fn partial_write_failure_poisons_writer_and_freezes_sink_bytes() { + let target_listing = (1..1000) + .find(|&id| shard_for_listing_id(id, 4) == 2) + .expect("listing for shard 2"); + let other_listing = (1..1000) + .find(|&id| shard_for_listing_id(id, 4) == 0) + .expect("listing for shard 0"); + + let row1 = sample_bar(target_listing, 1_700_000_000_000_000); + let row2 = sample_bar(target_listing, 1_700_000_060_000_000); + let other_row = sample_bar(other_listing, 1_700_000_000_000_000); + let known_at = 1_700_000_120_000_000; + + let mut expected_row1 = Vec::new(); + encode_bar_1m(&mut expected_row1, &row1, known_at).unwrap(); + let mut expected_row2 = Vec::new(); + encode_bar_1m(&mut expected_row2, &row2, known_at).unwrap(); + let partial_prefix_len = 32; + assert!(partial_prefix_len < expected_row2.len()); + + let healthy_sink = RecordingSink::new(); + let failing_sink = RecordingSink::failing_after_partial_write(1, partial_prefix_len); + let mut writer = IlpShardedWriter::new( + vec![ + healthy_sink.clone(), + RecordingSink::new(), + failing_sink.clone(), + RecordingSink::new(), + ], + IlpWriterOptions { + max_batch_bytes: 100_000, + max_batch_rows: 1, + }, + ) + .unwrap(); + + // First batch on shard 2 succeeds completely. + writer.write_bar_1m(&row1, known_at).unwrap(); + + // Second batch on shard 2 writes a partial prefix, then hits BrokenPipe. + let err = writer.write_bar_1m(&row2, known_at).unwrap_err(); + assert!(matches!(err, IlpWriterError::Io { shard: 2, .. })); + + let mut expected_captured = expected_row1.clone(); + expected_captured.extend_from_slice(&expected_row2[..partial_prefix_len]); + assert_eq!(failing_sink.captured_bytes(), expected_captured); + + // Subsequent writes (both on the failed shard and on another shard) and finish() are rejected, + // leaving all sink bytes frozen without replaying or appending anything. + assert!(matches!( + writer.write_bar_1m(&row2, known_at), + Err(IlpWriterError::Poisoned { failed_shard: 2 }) + )); + assert!(matches!( + writer.write_bar_1m(&other_row, known_at), + Err(IlpWriterError::Poisoned { failed_shard: 2 }) + )); + assert!(matches!( + writer.write_fx_1m(&sample_fx("USD.CAD", 100)), + Err(IlpWriterError::Poisoned { failed_shard: 2 }) + )); + assert!(matches!( + writer.finish(), + Err(IlpWriterError::Poisoned { failed_shard: 2 }) + )); + + assert_eq!(failing_sink.captured_bytes(), expected_captured); + assert!(healthy_sink.captured_bytes().is_empty()); +} + +#[test] +fn golden_bytes_literal_ieee754_little_endian_without_to_le_bytes() { + let row = Bar1mRow { + key: 7, + ts: 1_700_000_000_000_000, + session_date: 20_000, + open: 1.0, + high: 2.0, + low: 0.5, + close: 1.5, + volume: 0.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_EOD, + }; + let mut actual = Vec::new(); + encode_bar_1m(&mut actual, &row, 1_700_000_060_000_000).unwrap(); + + // Hand-written little-endian IEEE-754 bytes (no f64::to_le_bytes): + // 1.0 -> 00 00 00 00 00 00 f0 3f + // 2.0 -> 00 00 00 00 00 00 00 40 + // 0.5 -> 00 00 00 00 00 00 e0 3f + // 1.5 -> 00 00 00 00 00 00 f8 3f + // 0.0 -> 00 00 00 00 00 00 00 00 + let mut expected: Vec = Vec::new(); + expected.extend_from_slice(b"bars_1m,listing_id=7,session=RTH,source=eod_unadj "); + expected.extend_from_slice(b"open==\x10\x00\x00\x00\x00\x00\x00\xf0\x3f"); + expected.extend_from_slice(b",high==\x10\x00\x00\x00\x00\x00\x00\x00\x40"); + expected.extend_from_slice(b",low==\x10\x00\x00\x00\x00\x00\x00\xe0\x3f"); + expected.extend_from_slice(b",close==\x10\x00\x00\x00\x00\x00\x00\xf8\x3f"); + expected.extend_from_slice(b",volume==\x10\x00\x00\x00\x00\x00\x00\x00\x00"); + expected.extend_from_slice(b",known_at=1700000060000000t 1700000000000000t\n"); + + assert_eq!(actual, expected); +} From 6abee73df25e9cc0d4039bc5f1f9dc3939b59d8c Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:10:32 -0500 Subject: [PATCH 09/36] T-137: tests --- tools/curate-etl/tests/ilp_qa_contract.rs | 381 ++++++++++++++++++++++ 1 file changed, 381 insertions(+) create mode 100644 tools/curate-etl/tests/ilp_qa_contract.rs diff --git a/tools/curate-etl/tests/ilp_qa_contract.rs b/tools/curate-etl/tests/ilp_qa_contract.rs new file mode 100644 index 00000000..36f053ac --- /dev/null +++ b/tools/curate-etl/tests/ilp_qa_contract.rs @@ -0,0 +1,381 @@ +//! QA contract tests for the QuestDB ILP v2 encoder and sharded writer (T-137 / M2.3c). +//! +//! Uses only the public crate API. Expected wire bytes are written out by hand (decimal +//! timestamps, hex IEEE-754 payloads) and shard routing is checked against an independently +//! written FNV-1a reference, so the encoder is not used as its own oracle. + +use std::io::{self, Write}; +use std::sync::{Arc, Mutex}; + +use curate_etl::{ + encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Bar1mRow, + Fx1mRow, IlpEncodeError, IlpShardedWriter, IlpWriterError, IlpWriterOptions, + IntradaySession, BARS_1M_SOURCE_EOD, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M, +}; + +fn bar(key: i32, ts: i64) -> Bar1mRow { + Bar1mRow { + key, + ts, + session_date: 20_000, + open: 1.0, + high: 2.0, + low: 0.5, + close: 1.5, + volume: 0.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_EOD, + } +} + +fn fx(pair: &'static str, ts: i64) -> Fx1mRow<'static> { + Fx1mRow { + pair, + ts, + open: 1.0, + high: 2.0, + low: 0.5, + close: 1.5, + source: "eod", + } +} + +type BarSetter = fn(&mut Bar1mRow, f64); +type FxSetter = fn(&mut Fx1mRow<'static>, f64); + +fn encoded_bar(row: &Bar1mRow, known_at: i64) -> Vec { + let mut v = Vec::new(); + encode_bar_1m(&mut v, row, known_at).unwrap(); + v +} + +/// Independent FNV-1a 64 reference (spec constants written inline). +fn ref_fnv1a(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, &b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }) +} + +/// Sink that records every `write` call and flush, optionally failing a numbered write. +#[derive(Clone, Default)] +struct Rec { + writes: Arc>>>, + flushes: Arc>, + fail_write_call: Option, +} + +impl Rec { + fn writes(&self) -> Vec> { + self.writes.lock().unwrap().clone() + } + fn bytes(&self) -> Vec { + self.writes().concat() + } + fn flushes(&self) -> usize { + *self.flushes.lock().unwrap() + } +} + +impl Write for Rec { + fn write(&mut self, buf: &[u8]) -> io::Result { + let mut w = self.writes.lock().unwrap(); + if self.fail_write_call == Some(w.len()) { + return Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected")); + } + w.push(buf.to_vec()); + Ok(buf.len()) + } + fn flush(&mut self) -> io::Result<()> { + *self.flushes.lock().unwrap() += 1; + Ok(()) + } +} + +#[test] +fn table_names_and_double_marker_match_contract() { + assert_eq!(TABLE_BARS_1M, "bars_1m"); + assert_eq!(TABLE_FX_1M, "fx_1m"); + assert_eq!(ILP_V2_DOUBLE_TYPE, 16); +} + +#[test] +fn fx_1m_golden_bytes_use_hand_written_little_endian_payloads() { + let row = Fx1mRow { + pair: "USD.CAD", + ts: 1_700_000_000_000_000, + open: 1.0, + high: 2.0, + low: 0.5, + close: -1.5, + source: "eod", + }; + let mut actual = Vec::new(); + encode_fx_1m(&mut actual, &row).unwrap(); + + let mut expected = b"fx_1m,pair=USD.CAD,source=eod ".to_vec(); + expected.extend_from_slice(b"open==\x10\x00\x00\x00\x00\x00\x00\xf0\x3f"); + expected.extend_from_slice(b",high==\x10\x00\x00\x00\x00\x00\x00\x00\x40"); + expected.extend_from_slice(b",low==\x10\x00\x00\x00\x00\x00\x00\xe0\x3f"); + expected.extend_from_slice(b",close==\x10\x00\x00\x00\x00\x00\x00\xf8\xbf"); + expected.extend_from_slice(b" 1700000000000000t\n"); + assert_eq!(actual, expected); +} + +#[test] +fn encoder_appends_to_existing_buffer_without_clearing_it() { + let mut buf = b"prior-line\n".to_vec(); + encode_bar_1m(&mut buf, &bar(1, 10), 20).unwrap(); + encode_fx_1m(&mut buf, &fx("EUR.USD", 30)).unwrap(); + + let mut expected = b"prior-line\n".to_vec(); + expected.extend(encoded_bar(&bar(1, 10), 20)); + let mut fx_line = Vec::new(); + encode_fx_1m(&mut fx_line, &fx("EUR.USD", 30)).unwrap(); + expected.extend(fx_line); + assert_eq!(buf, expected); +} + +#[test] +fn integer_extremes_encode_as_exact_decimal_without_overflow() { + // i32::MIN listing id, i64::MIN known_at, i64::MAX designated ts. + let row = bar(i32::MIN, i64::MAX); + let line = encoded_bar(&row, i64::MIN); + assert!(line.starts_with(b"bars_1m,listing_id=-2147483648,session=RTH,source=eod_unadj ")); + assert!(line.ends_with(b",known_at=-9223372036854775808t 9223372036854775807t\n")); + + // Zero designated ts and zero known_at are valid boundaries. + let zero = encoded_bar(&bar(0, 0), 0); + assert!(zero.starts_with(b"bars_1m,listing_id=0,")); + assert!(zero.ends_with(b",known_at=0t 0t\n")); + + let mut buf = Vec::new(); + encode_fx_1m(&mut buf, &fx("X", i64::MAX)).unwrap(); + assert!(buf.ends_with(b" 9223372036854775807t\n")); +} + +#[test] +fn extreme_finite_doubles_round_trip_bit_exactly() { + for v in [ + -0.0_f64, + f64::MIN_POSITIVE, + f64::from_bits(1), // smallest subnormal + f64::MAX, + f64::MIN, + f64::EPSILON, + ] { + let mut row = bar(5, 1); + row.low = v; + let line = encoded_bar(&row, 2); + let prefix = b",low==\x10"; + let pos = line.windows(prefix.len()).position(|w| w == prefix).unwrap() + prefix.len(); + let raw: [u8; 8] = line[pos..pos + 8].try_into().unwrap(); + assert_eq!(f64::from_le_bytes(raw).to_bits(), v.to_bits(), "value {v:e}"); + } +} + +#[test] +fn every_double_field_rejects_each_non_finite_value_atomically() { + let sentinel = b"keep".to_vec(); + let bar_fields: [(&str, BarSetter); 5] = [ + ("open", |r, v| r.open = v), + ("high", |r, v| r.high = v), + ("low", |r, v| r.low = v), + ("close", |r, v| r.close = v), + ("volume", |r, v| r.volume = v), + ]; + let fx_fields: [(&str, FxSetter); 4] = [ + ("open", |r, v| r.open = v), + ("high", |r, v| r.high = v), + ("low", |r, v| r.low = v), + ("close", |r, v| r.close = v), + ]; + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + for (name, set) in bar_fields { + let mut row = bar(1, 1); + set(&mut row, bad); + let mut buf = sentinel.clone(); + match encode_bar_1m(&mut buf, &row, 1) { + Err(IlpEncodeError::NonFiniteDouble { field, .. }) => assert_eq!(field, name), + other => panic!("bars_1m {name}={bad}: unexpected {other:?}"), + } + assert_eq!(buf, sentinel); + } + for (name, set) in fx_fields { + let mut row = fx("USD.CAD", 1); + set(&mut row, bad); + let mut buf = sentinel.clone(); + match encode_fx_1m(&mut buf, &row) { + Err(IlpEncodeError::NonFiniteDouble { field, .. }) => assert_eq!(field, name), + other => panic!("fx_1m {name}={bad}: unexpected {other:?}"), + } + assert_eq!(buf, sentinel); + } + } + + let mut buf = sentinel.clone(); + assert_eq!( + encode_fx_1m(&mut buf, &Fx1mRow { source: "", ..fx("USD.CAD", 1) }), + Err(IlpEncodeError::EmptySymbol { field: "source" }) + ); + assert_eq!(buf, sentinel); +} + +#[test] +fn routing_matches_independent_fnv1a_reference_and_published_vectors() { + // Published FNV-1a 64 test vectors. + assert_eq!(fnv1a_64(b""), 0xcbf2_9ce4_8422_2325); + assert_eq!(fnv1a_64(b"a"), 0xaf63_dc4c_8601_ec8c); + assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8); + + for shards in [1usize, 2, 3, 4, 7, 16] { + for id in [-1_000_000, -1, 0, 1, 42, 65_535, i32::MAX, i32::MIN] { + let expected = (ref_fnv1a(&id.to_le_bytes()) % shards as u64) as usize; + assert_eq!(shard_for_listing_id(id, shards), expected, "id {id} shards {shards}"); + } + for pair in ["USD.CAD", "EUR.USD", "a b", "caf\u{e9}"] { + let expected = (ref_fnv1a(pair.as_bytes()) % shards as u64) as usize; + assert_eq!(shard_for_fx_pair(pair, shards), expected); + } + } +} + +#[test] +fn fx_routing_hashes_raw_pair_not_escaped_wire_form() { + // A pair that needs escaping must route by its raw bytes. + let pair = "US D"; + let shards = 8; + let sinks: Vec = (0..shards).map(|_| Rec::default()).collect(); + let mut w = IlpShardedWriter::new(sinks.clone(), IlpWriterOptions::default()).unwrap(); + w.write_fx_1m(&fx(pair, 1)).unwrap(); + let stats = w.finish().unwrap(); + + let target = (ref_fnv1a(pair.as_bytes()) % shards as u64) as usize; + assert_eq!(stats.per_shard_rows[target], 1); + assert!(sinks[target].bytes().starts_with(b"fx_1m,pair=US\\ D,source=eod ")); +} + +#[test] +fn single_shard_writer_preserves_global_input_order() { + let sink = Rec::default(); + let mut w = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 7 }, + ) + .unwrap(); + let mut expected = Vec::new(); + for i in 0..50i64 { + let row = bar((i % 9) as i32 - 4, 1_000 + i); + expected.extend(encoded_bar(&row, 2_000 + i)); + w.write_bar_1m(&row, 2_000 + i).unwrap(); + } + let stats = w.finish().unwrap(); + assert_eq!(sink.bytes(), expected); + assert_eq!(stats.rows, 50); + assert_eq!(stats.per_shard_rows, vec![50]); + assert_eq!(stats.flushes, 8); // 7 full batches of 7 + one remainder of 1 + assert_eq!(stats.bytes, expected.len()); +} + +#[test] +fn row_and_byte_limits_hit_on_same_row_produce_one_flush() { + let row = bar(3, 100); + let len = encoded_bar(&row, 200).len(); + let sink = Rec::default(); + let mut w = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { max_batch_bytes: 2 * len, max_batch_rows: 2 }, + ) + .unwrap(); + for _ in 0..4 { + w.write_bar_1m(&row, 200).unwrap(); + } + let stats = w.finish().unwrap(); + let writes = sink.writes(); + assert_eq!(writes.len(), 2); + assert!(writes.iter().all(|b| b.len() == 2 * len)); + assert_eq!(stats.flushes, 2); + assert_eq!(sink.flushes(), 1); +} + +#[test] +fn bytes_and_rows_are_counted_only_after_a_successful_batch() { + // Interleave two shards; shard holding the failing sink fails on its 2nd batch. + let a = (1..1000).find(|&id| shard_for_listing_id(id, 2) == 0).unwrap(); + let b = (1..1000).find(|&id| shard_for_listing_id(id, 2) == 1).unwrap(); + let ok = Rec::default(); + let bad = Rec { fail_write_call: Some(1), ..Rec::default() }; + let mut w = IlpShardedWriter::new( + vec![ok.clone(), bad.clone()], + IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 2 }, + ) + .unwrap(); + for i in 0..3 { + w.write_bar_1m(&bar(a, i), i).unwrap(); + } + w.write_bar_1m(&bar(b, 1), 1).unwrap(); + w.write_bar_1m(&bar(b, 2), 2).unwrap(); // first batch on shard 1 succeeds + w.write_bar_1m(&bar(b, 3), 3).unwrap(); + let err = w.write_bar_1m(&bar(b, 4), 4).unwrap_err(); + assert!(matches!(err, IlpWriterError::Io { shard: 1, .. })); + assert!(err.to_string().contains("shard 1"), "{err}"); + assert!(std::error::Error::source(&err).is_some()); + + // Healthy shard got exactly its one full batch; buffered remainder is never sent. + assert_eq!(ok.writes().len(), 1); + assert_eq!(bad.writes().len(), 1); + assert!(matches!(w.finish(), Err(IlpWriterError::Poisoned { failed_shard: 1 }))); + assert_eq!(ok.writes().len(), 1); + assert_eq!(ok.flushes(), 0); +} + +#[test] +fn encode_error_inside_writer_leaves_pending_batch_and_stats_intact() { + let sink = Rec::default(); + let mut w = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 3 }, + ) + .unwrap(); + let good1 = bar(9, 1); + let good2 = bar(9, 2); + let good3 = bar(9, 3); + w.write_bar_1m(&good1, 10).unwrap(); + let mut bad = bar(9, -5); + bad.close = 3.0; + assert!(matches!( + w.write_bar_1m(&bad, 10), + Err(IlpWriterError::Encode(IlpEncodeError::NegativeTimestamp { field: "ts", value: -5 })) + )); + w.write_bar_1m(&good2, 10).unwrap(); + w.write_bar_1m(&good3, 10).unwrap(); // third valid row hits the row limit + let writes = sink.writes(); + assert_eq!(writes.len(), 1); + let mut expected = encoded_bar(&good1, 10); + expected.extend(encoded_bar(&good2, 10)); + expected.extend(encoded_bar(&good3, 10)); + assert_eq!(writes[0], expected); + + let stats = w.finish().unwrap(); + assert_eq!(stats.rows, 3); + assert_eq!(stats.bytes, expected.len()); +} + +#[test] +fn bars_and_fx_rows_can_share_a_writer_with_independent_routing() { + let shards = 4; + let sinks: Vec = (0..shards).map(|_| Rec::default()).collect(); + let mut w = IlpShardedWriter::new(sinks.clone(), IlpWriterOptions::default()).unwrap(); + w.write_bar_1m(&bar(42, 1), 2).unwrap(); + w.write_fx_1m(&fx("USD.CAD", 3)).unwrap(); + let stats = w.finish().unwrap(); + assert_eq!(stats.rows, 2); + + let bar_shard = shard_for_listing_id(42, shards); + let fx_shard = shard_for_fx_pair("USD.CAD", shards); + let total: usize = sinks.iter().map(|s| s.bytes().len()).sum(); + assert_eq!(stats.bytes, total); + let bar_bytes = sinks[bar_shard].bytes(); + let fx_bytes = sinks[fx_shard].bytes(); + assert!(bar_bytes.windows(8).any(|w| w == b"bars_1m,")); + assert!(fx_bytes.windows(6).any(|w| w == b"fx_1m,")); +} From 515b685ffc5d11f85ef0b433ad526987339d2e44 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 06:27:55 -0500 Subject: [PATCH 10/36] =?UTF-8?q?T-136:=20M2.1e=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`read=5Fknowledge`=20tool:=20read-only=20methodology=20card?= =?UTF-8?q?s=20+=20empirical=20findings=20/=20provider=20caveats=20lookup?= =?UTF-8?q?=20via=20injected=20ports=20in=20`libs/research/src/mcp/tools/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/index.ts | 1 + libs/research/src/mcp/tools/read-knowledge.ts | 595 +++++++++++ libs/research/test/mcp-read-knowledge.test.ts | 940 ++++++++++++++++++ 3 files changed, 1536 insertions(+) create mode 100644 libs/research/src/mcp/tools/read-knowledge.ts create mode 100644 libs/research/test/mcp-read-knowledge.test.ts diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 2ed5c994..5241cac4 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -4,4 +4,5 @@ export * from './stdio'; export * from './tools/analyze-signal'; export * from './tools/event-study'; export * from './tools/query-data'; +export * from './tools/read-knowledge'; export * from './tools/search-symbols'; diff --git a/libs/research/src/mcp/tools/read-knowledge.ts b/libs/research/src/mcp/tools/read-knowledge.ts new file mode 100644 index 00000000..1fb5b6e9 --- /dev/null +++ b/libs/research/src/mcp/tools/read-knowledge.ts @@ -0,0 +1,595 @@ +import { z } from 'zod'; +import type { McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool } from '../server'; + +/** Concrete knowledge sources returned in `read_knowledge` rows and source counts. */ +export const READ_KNOWLEDGE_RECORD_SOURCES = ['library', 'findings', 'provider_caveats'] as const; + +export type ReadKnowledgeRecordSource = (typeof READ_KNOWLEDGE_RECORD_SOURCES)[number]; + +/** Supported `source` selector values for `read_knowledge`. */ +export const READ_KNOWLEDGE_SOURCES = [...READ_KNOWLEDGE_RECORD_SOURCES, 'all'] as const; + +export type ReadKnowledgeSource = (typeof READ_KNOWLEDGE_SOURCES)[number]; + +/** Default maximum number of matching records returned by `read_knowledge`. */ +export const READ_KNOWLEDGE_DEFAULT_LIMIT = 20; + +/** Hard maximum number of matching records returned by `read_knowledge`. */ +export const READ_KNOWLEDGE_MAX_LIMIT = 100; + +/** Hard maximum character length of a trimmed `read_knowledge` query string. */ +export const READ_KNOWLEDGE_MAX_QUERY_LENGTH = 64; + +/** Hard maximum character length per projected text field (`body`, `summary`, `caveat`). */ +export const READ_KNOWLEDGE_MAX_TEXT_LENGTH = 4096; + +/** Methodology or literature card record returned by {@link KnowledgePort.listLibraryCards}. */ +export interface LibraryCardRecord { + readonly id: string; + readonly title: string; + readonly tags: readonly string[]; + readonly summary: string; + readonly body: string; +} + +/** Empirical Stock Bot finding record returned by {@link KnowledgePort.listFindings}. */ +export interface FindingRecord { + readonly id: string; + readonly title: string; + readonly status: string; + readonly createdAt: string; + readonly summary: string; + readonly trialRefs: readonly string[]; + readonly evidenceRefs: readonly string[]; +} + +/** Provider dataset caveat record returned by {@link KnowledgePort.listProviderCaveats}. */ +export interface ProviderCaveatRecord { + readonly id: string; + readonly provider: string; + readonly dataset: string; + readonly caveat: string; + readonly createdAt: string; +} + +/** Applicable parsed selectors passed to {@link KnowledgePort.listLibraryCards}. */ +export interface LibraryCardQuery { + readonly id?: string; + readonly query?: string; + readonly tags?: readonly string[]; +} + +/** Applicable parsed selectors passed to {@link KnowledgePort.listFindings}. */ +export interface FindingQuery { + readonly id?: string; + readonly query?: string; +} + +/** Applicable parsed selectors passed to {@link KnowledgePort.listProviderCaveats}. */ +export interface ProviderCaveatQuery { + readonly id?: string; + readonly query?: string; + readonly provider?: string; +} + +/** + * Read-only knowledge lookup port injected into {@link createReadKnowledgeTool}. + * + * Port contract: + * - Read-only by construction: exposes only lookup methods and never mutates backing stores. + * - Callers and concrete adapters must supply research-visible records and references only; + * holdout observations and vault-only evidence must be excluded from the research corpus. + * - Return all eligible candidates (with IDs unique within each source) without pre-slicing + * so the tool controls deterministic global ranking and the global `limit`. + */ +export interface KnowledgePort { + listLibraryCards(q: LibraryCardQuery): Promise; + listFindings(q: FindingQuery): Promise; + listProviderCaveats(q: ProviderCaveatQuery): Promise; +} + +/** + * Strict Zod input schema for the `read_knowledge` MCP tool. + * + * Intentionally omits `scope`, `vault_evaluation_only`, and `vaultCutoffTs`; + * `.strict()` rejects any unknown keys. + */ +export const readKnowledgeInputSchema = z + .object({ + source: z + .enum(READ_KNOWLEDGE_SOURCES) + .default('all') + .describe( + 'Knowledge source to query: library, findings, provider_caveats, or all (default all).' + ), + query: z + .string() + .trim() + .min(1) + .max(READ_KNOWLEDGE_MAX_QUERY_LENGTH) + .optional() + .describe( + `Optional case-insensitive substring query (trimmed, 1–${READ_KNOWLEDGE_MAX_QUERY_LENGTH} characters). Ignored when id is supplied.` + ), + id: z + .string() + .trim() + .min(1) + .optional() + .describe( + 'Optional exact case-sensitive card or record ID selector. Takes precedence over query when supplied.' + ), + tags: z + .array(z.string().trim().min(1)) + .min(1) + .optional() + .describe( + 'Optional tag filter applied only to library cards (case-insensitive all-tag match; findings and provider_caveats are unaffected when source is all).' + ), + provider: z + .string() + .trim() + .min(1) + .optional() + .describe( + 'Optional provider filter applied only to provider_caveats (case-insensitive exact match; library and findings are unaffected when source is all).' + ), + limit: z + .number() + .int() + .min(1) + .max(READ_KNOWLEDGE_MAX_LIMIT) + .default(READ_KNOWLEDGE_DEFAULT_LIMIT) + .describe( + `Maximum number of ranked records to return (default ${READ_KNOWLEDGE_DEFAULT_LIMIT}, max ${READ_KNOWLEDGE_MAX_LIMIT}).` + ), + }) + .strict(); + +export type ReadKnowledgeInput = z.infer; + +/** Server-side injected configuration for {@link createReadKnowledgeTool}. */ +export interface ReadKnowledgeToolOptions { + readonly port: KnowledgePort; +} + +/** Source-labeled library card row emitted by `read_knowledge`. */ +export interface ReadKnowledgeLibraryRow { + readonly source: 'library'; + readonly id: string; + readonly title: string; + readonly tags: readonly string[]; + readonly summary: string; + readonly body: string; + readonly truncated: boolean; +} + +/** Source-labeled empirical finding row emitted by `read_knowledge`. */ +export interface ReadKnowledgeFindingRow { + readonly source: 'findings'; + readonly id: string; + readonly title: string; + readonly status: string; + readonly createdAt: string; + readonly summary: string; + readonly trialRefs: readonly string[]; + readonly evidenceRefs: readonly string[]; + readonly truncated: boolean; +} + +/** Source-labeled provider caveat row emitted by `read_knowledge`. */ +export interface ReadKnowledgeProviderCaveatRow { + readonly source: 'provider_caveats'; + readonly id: string; + readonly provider: string; + readonly dataset: string; + readonly caveat: string; + readonly createdAt: string; + readonly truncated: boolean; +} + +/** Discriminated union of rows emitted by `read_knowledge`. */ +export type ReadKnowledgeRow = + | ReadKnowledgeLibraryRow + | ReadKnowledgeFindingRow + | ReadKnowledgeProviderCaveatRow; + +/** Per-source counts of returned rows after applying the global `limit`. */ +export interface ReadKnowledgeSourceCounts { + readonly library: number; + readonly findings: number; + readonly provider_caveats: number; +} + +/** Structured JSON payload serialized into the `read_knowledge` MCP text result. */ +export interface ReadKnowledgeResultPayload { + readonly rowCount: number; + readonly sources: ReadKnowledgeSourceCounts; + readonly rows: readonly ReadKnowledgeRow[]; +} + +const SOURCE_ORDER: Readonly> = { + library: 0, + findings: 1, + provider_caveats: 2, +}; + +function compareStrings(a: string, b: string): number { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; +} + +function validateRequiredString(value: unknown, field: string): string { + if (typeof value !== 'string') { + throw new Error(`Invalid port string for "${field}".`); + } + return value; +} + +function validateStringArray(value: unknown, field: string): readonly string[] { + if (!Array.isArray(value)) { + throw new Error(`Invalid port string array for "${field}".`); + } + const result: string[] = []; + for (let i = 0; i < value.length; i += 1) { + const entry: unknown = value[i]; + if (typeof entry !== 'string') { + throw new Error(`Invalid port string array entry for "${field}".`); + } + result.push(entry); + } + return result; +} + +function truncateText(value: string): { readonly text: string; readonly truncated: boolean } { + if (value.length <= READ_KNOWLEDGE_MAX_TEXT_LENGTH) { + return { text: value, truncated: false }; + } + return { + text: value.slice(0, READ_KNOWLEDGE_MAX_TEXT_LENGTH), + truncated: true, + }; +} + +function validateLibraryCard(raw: LibraryCardRecord): LibraryCardRecord { + if (typeof raw !== 'object' || raw === null) { + throw new Error('Invalid library card record returned by port.'); + } + return { + id: validateRequiredString(raw.id, 'id'), + title: validateRequiredString(raw.title, 'title'), + tags: validateStringArray(raw.tags, 'tags'), + summary: validateRequiredString(raw.summary, 'summary'), + body: validateRequiredString(raw.body, 'body'), + }; +} + +function validateFinding(raw: FindingRecord): FindingRecord { + if (typeof raw !== 'object' || raw === null) { + throw new Error('Invalid finding record returned by port.'); + } + return { + id: validateRequiredString(raw.id, 'id'), + title: validateRequiredString(raw.title, 'title'), + status: validateRequiredString(raw.status, 'status'), + createdAt: validateRequiredString(raw.createdAt, 'createdAt'), + summary: validateRequiredString(raw.summary, 'summary'), + trialRefs: validateStringArray(raw.trialRefs, 'trialRefs'), + evidenceRefs: validateStringArray(raw.evidenceRefs, 'evidenceRefs'), + }; +} + +function validateProviderCaveat(raw: ProviderCaveatRecord): ProviderCaveatRecord { + if (typeof raw !== 'object' || raw === null) { + throw new Error('Invalid provider caveat record returned by port.'); + } + return { + id: validateRequiredString(raw.id, 'id'), + provider: validateRequiredString(raw.provider, 'provider'), + dataset: validateRequiredString(raw.dataset, 'dataset'), + caveat: validateRequiredString(raw.caveat, 'caveat'), + createdAt: validateRequiredString(raw.createdAt, 'createdAt'), + }; +} + +function matchesAllTags( + cardTags: readonly string[], + requiredLowerTags: readonly string[] +): boolean { + const cardLowerTags = new Set(cardTags.map(tag => tag.toLowerCase())); + for (let i = 0; i < requiredLowerTags.length; i += 1) { + if (!cardLowerTags.has(requiredLowerTags[i] as string)) { + return false; + } + } + return true; +} + +function rankLibraryCard( + card: LibraryCardRecord, + input: ReadKnowledgeInput, + normalizedQuery: string | null, + requiredLowerTags: readonly string[] | null +): number | null { + if (requiredLowerTags !== null && !matchesAllTags(card.tags, requiredLowerTags)) { + return null; + } + if (input.id !== undefined) { + return card.id === input.id ? 0 : null; + } + if (normalizedQuery === null) { + return 2; + } + const titleMatches = card.title.toLowerCase().includes(normalizedQuery); + const tagMatches = card.tags.some(tag => tag.toLowerCase().includes(normalizedQuery)); + const summaryMatches = card.summary.toLowerCase().includes(normalizedQuery); + if (!titleMatches && !tagMatches && !summaryMatches) { + return null; + } + if (card.id === input.query) { + return 0; + } + return titleMatches ? 1 : 2; +} + +function rankFinding( + finding: FindingRecord, + input: ReadKnowledgeInput, + normalizedQuery: string | null +): number | null { + if (input.id !== undefined) { + return finding.id === input.id ? 0 : null; + } + if (normalizedQuery === null) { + return 2; + } + const titleMatches = finding.title.toLowerCase().includes(normalizedQuery); + const summaryMatches = finding.summary.toLowerCase().includes(normalizedQuery); + if (!titleMatches && !summaryMatches) { + return null; + } + if (finding.id === input.query) { + return 0; + } + return titleMatches ? 1 : 2; +} + +function rankProviderCaveat( + caveat: ProviderCaveatRecord, + input: ReadKnowledgeInput, + normalizedQuery: string | null, + normalizedProvider: string | null +): number | null { + if (normalizedProvider !== null && caveat.provider.toLowerCase() !== normalizedProvider) { + return null; + } + if (input.id !== undefined) { + return caveat.id === input.id ? 0 : null; + } + if (normalizedQuery === null) { + return 2; + } + const datasetMatches = caveat.dataset.toLowerCase().includes(normalizedQuery); + const providerMatches = caveat.provider.toLowerCase().includes(normalizedQuery); + const caveatMatches = caveat.caveat.toLowerCase().includes(normalizedQuery); + if (!datasetMatches && !providerMatches && !caveatMatches) { + return null; + } + if (caveat.id === input.query) { + return 0; + } + return datasetMatches ? 1 : 2; +} + +function projectLibraryCard(card: LibraryCardRecord): ReadKnowledgeLibraryRow { + const summary = truncateText(card.summary); + const body = truncateText(card.body); + return { + source: 'library', + id: card.id, + title: card.title, + tags: [...card.tags], + summary: summary.text, + body: body.text, + truncated: summary.truncated || body.truncated, + }; +} + +function projectFinding(finding: FindingRecord): ReadKnowledgeFindingRow { + const summary = truncateText(finding.summary); + return { + source: 'findings', + id: finding.id, + title: finding.title, + status: finding.status, + createdAt: finding.createdAt, + summary: summary.text, + trialRefs: [...finding.trialRefs], + evidenceRefs: [...finding.evidenceRefs], + truncated: summary.truncated, + }; +} + +function projectProviderCaveat(caveat: ProviderCaveatRecord): ReadKnowledgeProviderCaveatRow { + const caveatText = truncateText(caveat.caveat); + return { + source: 'provider_caveats', + id: caveat.id, + provider: caveat.provider, + dataset: caveat.dataset, + caveat: caveatText.text, + createdAt: caveat.createdAt, + truncated: caveatText.truncated, + }; +} + +function validateFactoryOptions(options: ReadKnowledgeToolOptions): KnowledgePort { + if (typeof options !== 'object' || options === null) { + throw new Error('Invalid `options`: expected a ReadKnowledgeToolOptions object.'); + } + + const { port } = options; + if ( + typeof port !== 'object' || + port === null || + typeof port.listLibraryCards !== 'function' || + typeof port.listFindings !== 'function' || + typeof port.listProviderCaveats !== 'function' + ) { + throw new Error( + 'Invalid `port`: expected a KnowledgePort implementing `listLibraryCards`, `listFindings`, and `listProviderCaveats`.' + ); + } + + return port; +} + +interface RankedCandidate { + readonly rank: number; + readonly row: ReadKnowledgeRow; +} + +/** + * Creates the read-only `read_knowledge` MCP tool backed by an injected + * {@link KnowledgePort}. + * + * Queries only the selected source(s), applies exact-ID or case-insensitive + * text matching and source-specific filters (`tags` for library cards, + * `provider` for provider caveats), ranks deterministically (exact ID > title + * match > ascending ID, breaking cross-source ties in `library`, `findings`, + * `provider_caveats` order), applies `limit` after ranking, and caps long text + * fields independently with `truncated: true`. + */ +export function createReadKnowledgeTool(options: ReadKnowledgeToolOptions): McpToolEntry { + const port = validateFactoryOptions(options); + + return defineMcpTool({ + name: 'read_knowledge', + description: + 'Read-only lookup across methodology library cards, empirical findings, and provider dataset caveats.', + inputSchema: readKnowledgeInputSchema, + async handler(input: ReadKnowledgeInput): Promise { + const wantLibrary = input.source === 'all' || input.source === 'library'; + const wantFindings = input.source === 'all' || input.source === 'findings'; + const wantCaveats = input.source === 'all' || input.source === 'provider_caveats'; + + const libraryQuery: LibraryCardQuery = { + ...(input.id !== undefined ? { id: input.id } : {}), + ...(input.query !== undefined ? { query: input.query } : {}), + ...(input.tags !== undefined ? { tags: input.tags } : {}), + }; + const findingQuery: FindingQuery = { + ...(input.id !== undefined ? { id: input.id } : {}), + ...(input.query !== undefined ? { query: input.query } : {}), + }; + const caveatQuery: ProviderCaveatQuery = { + ...(input.id !== undefined ? { id: input.id } : {}), + ...(input.query !== undefined ? { query: input.query } : {}), + ...(input.provider !== undefined ? { provider: input.provider } : {}), + }; + + const [rawLibrary, rawFindings, rawCaveats] = await Promise.all([ + wantLibrary ? port.listLibraryCards(libraryQuery) : Promise.resolve(null), + wantFindings ? port.listFindings(findingQuery) : Promise.resolve(null), + wantCaveats ? port.listProviderCaveats(caveatQuery) : Promise.resolve(null), + ]); + + const normalizedQuery = + input.id === undefined && input.query !== undefined ? input.query.toLowerCase() : null; + const requiredLowerTags = + input.tags !== undefined ? input.tags.map(tag => tag.toLowerCase()) : null; + const normalizedProvider = + input.provider !== undefined ? input.provider.toLowerCase() : null; + + const eligible: RankedCandidate[] = []; + + if (rawLibrary !== null) { + if (!Array.isArray(rawLibrary)) { + throw new Error('Invalid library cards response returned by port.'); + } + for (let i = 0; i < rawLibrary.length; i += 1) { + const card = validateLibraryCard(rawLibrary[i] as LibraryCardRecord); + const rank = rankLibraryCard(card, input, normalizedQuery, requiredLowerTags); + if (rank !== null) { + eligible.push({ rank, row: projectLibraryCard(card) }); + } + } + } + + if (rawFindings !== null) { + if (!Array.isArray(rawFindings)) { + throw new Error('Invalid findings response returned by port.'); + } + for (let i = 0; i < rawFindings.length; i += 1) { + const finding = validateFinding(rawFindings[i] as FindingRecord); + const rank = rankFinding(finding, input, normalizedQuery); + if (rank !== null) { + eligible.push({ rank, row: projectFinding(finding) }); + } + } + } + + if (rawCaveats !== null) { + if (!Array.isArray(rawCaveats)) { + throw new Error('Invalid provider caveats response returned by port.'); + } + for (let i = 0; i < rawCaveats.length; i += 1) { + const caveat = validateProviderCaveat(rawCaveats[i] as ProviderCaveatRecord); + const rank = rankProviderCaveat(caveat, input, normalizedQuery, normalizedProvider); + if (rank !== null) { + eligible.push({ rank, row: projectProviderCaveat(caveat) }); + } + } + } + + eligible.sort((a, b) => { + if (a.rank !== b.rank) { + return a.rank - b.rank; + } + const idCmp = compareStrings(a.row.id, b.row.id); + if (idCmp !== 0) { + return idCmp; + } + return SOURCE_ORDER[a.row.source] - SOURCE_ORDER[b.row.source]; + }); + + const limitCount = Math.min(eligible.length, input.limit); + const rows: ReadKnowledgeRow[] = []; + let libraryCount = 0; + let findingsCount = 0; + let providerCaveatsCount = 0; + + for (let i = 0; i < limitCount; i += 1) { + const row = (eligible[i] as RankedCandidate).row; + rows.push(row); + if (row.source === 'library') { + libraryCount += 1; + } else if (row.source === 'findings') { + findingsCount += 1; + } else { + providerCaveatsCount += 1; + } + } + + const payload: ReadKnowledgeResultPayload = { + rowCount: rows.length, + sources: { + library: libraryCount, + findings: findingsCount, + provider_caveats: providerCaveatsCount, + }, + rows, + }; + + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + }, + }); +} diff --git a/libs/research/test/mcp-read-knowledge.test.ts b/libs/research/test/mcp-read-knowledge.test.ts new file mode 100644 index 00000000..85e25d22 --- /dev/null +++ b/libs/research/test/mcp-read-knowledge.test.ts @@ -0,0 +1,940 @@ +import { describe, expect, test } from 'bun:test'; +import type { MarketDataStore } from '../src/market-data-store'; +import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; +import { + type FindingQuery, + type FindingRecord, + type KnowledgePort, + type LibraryCardQuery, + type LibraryCardRecord, + type ProviderCaveatQuery, + type ProviderCaveatRecord, + READ_KNOWLEDGE_DEFAULT_LIMIT, + READ_KNOWLEDGE_MAX_LIMIT, + READ_KNOWLEDGE_MAX_QUERY_LENGTH, + READ_KNOWLEDGE_MAX_TEXT_LENGTH, + READ_KNOWLEDGE_SOURCES, + type ReadKnowledgeResultPayload, + type SymbolSearchPort, + createAnalyzeSignalTool, + createEventStudyTool, + createMcpServer, + createQueryDataTool, + createReadKnowledgeTool, + createSearchSymbolsTool, + readKnowledgeInputSchema, +} from '../src/mcp/index'; +import type { TrialLedgerExecutor } from '../src/trial-ledger'; + +const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); + +function makeLibraryCard( + overrides: Partial & { readonly id: string } +): LibraryCardRecord { + return { + id: overrides.id, + title: overrides.title ?? `Card ${overrides.id}`, + tags: overrides.tags ?? ['methodology'], + summary: overrides.summary ?? `Summary for ${overrides.id}`, + body: overrides.body ?? `Body for ${overrides.id}`, + }; +} + +function makeFinding(overrides: Partial & { readonly id: string }): FindingRecord { + return { + id: overrides.id, + title: overrides.title ?? `Finding ${overrides.id}`, + status: overrides.status ?? 'confirmed', + createdAt: overrides.createdAt ?? '2025-01-15T12:00:00.000Z', + summary: overrides.summary ?? `Finding summary for ${overrides.id}`, + trialRefs: overrides.trialRefs ?? [`trial-${overrides.id}`], + evidenceRefs: overrides.evidenceRefs ?? [`ev-${overrides.id}`], + }; +} + +function makeCaveat( + overrides: Partial & { readonly id: string } +): ProviderCaveatRecord { + return { + id: overrides.id, + provider: overrides.provider ?? 'eodhd', + dataset: overrides.dataset ?? `Dataset ${overrides.id}`, + caveat: overrides.caveat ?? `Caveat text for ${overrides.id}`, + createdAt: overrides.createdAt ?? '2025-01-20T08:30:00.000Z', + }; +} + +interface FakePortState { + readonly libraryCalls: LibraryCardQuery[]; + readonly findingsCalls: FindingQuery[]; + readonly caveatsCalls: ProviderCaveatQuery[]; + readonly invokedMethods: string[]; + readonly port: KnowledgePort; +} + +function createFakeKnowledgePort(options?: { + readonly libraryCards?: readonly LibraryCardRecord[]; + readonly findings?: readonly FindingRecord[]; + readonly providerCaveats?: readonly ProviderCaveatRecord[]; + readonly libraryError?: unknown; + readonly findingsError?: unknown; + readonly caveatsError?: unknown; +}): FakePortState { + const libraryCalls: LibraryCardQuery[] = []; + const findingsCalls: FindingQuery[] = []; + const caveatsCalls: ProviderCaveatQuery[] = []; + const invokedMethods: string[] = []; + + const libraryCards = options?.libraryCards ?? []; + const findings = options?.findings ?? []; + const providerCaveats = options?.providerCaveats ?? []; + + const rawPort: KnowledgePort = { + async listLibraryCards(q: LibraryCardQuery): Promise { + libraryCalls.push({ ...q }); + if (options?.libraryError !== undefined) { + throw options.libraryError; + } + return [...libraryCards]; + }, + async listFindings(q: FindingQuery): Promise { + findingsCalls.push({ ...q }); + if (options?.findingsError !== undefined) { + throw options.findingsError; + } + return [...findings]; + }, + async listProviderCaveats(q: ProviderCaveatQuery): Promise { + caveatsCalls.push({ ...q }); + if (options?.caveatsError !== undefined) { + throw options.caveatsError; + } + return [...providerCaveats]; + }, + }; + + const port = new Proxy(rawPort, { + get(target, prop, receiver) { + const value: unknown = Reflect.get(target, prop, receiver); + if (typeof value === 'function' && typeof prop === 'string') { + return (...args: unknown[]) => { + invokedMethods.push(prop); + return (value as (...a: unknown[]) => unknown).apply(target, args); + }; + } + return value; + }, + }); + + return { + libraryCalls, + findingsCalls, + caveatsCalls, + invokedMethods, + port, + }; +} + +function createMinimalStore(): MarketDataStore { + return { + bars() { + return { + async *[Symbol.asyncIterator]() { + // empty stream + }, + }; + }, + async universe() { + return []; + }, + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; +} + +function createMinimalLedger(): TrialLedgerExecutor { + return { + async query() { + return { rows: [] }; + }, + }; +} + +function createMinimalSymbolPort(): SymbolSearchPort { + return { + async searchSymbols() { + return []; + }, + }; +} + +async function callReadKnowledge( + fake: FakePortState, + args: Record +): Promise<{ + readonly isError: boolean; + readonly text: string; + readonly payload: ReadKnowledgeResultPayload | null; +}> { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [createReadKnowledgeTool({ port: fake.port })], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'rk-1', + method: 'tools/call', + params: { + name: 'read_knowledge', + arguments: args, + }, + }) + ); + + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw as string) as { + result: { + isError?: boolean; + content: { type: string; text: string }[]; + }; + }; + const isError = parsed.result.isError === true; + const text = parsed.result.content[0]?.text ?? ''; + + return { + isError, + text, + payload: isError ? null : (JSON.parse(text) as ReadKnowledgeResultPayload), + }; +} + +describe('MCP read_knowledge tool', () => { + test('registers alongside existing MCP tools, exposes strict schema via tools/list, and executes via tools/call', async () => { + const store = createMinimalStore(); + const ledger = createMinimalLedger(); + const fake = createFakeKnowledgePort({ + libraryCards: [ + makeLibraryCard({ + id: 'card-cpcv', + title: 'Combinatorial Purged Cross-Validation', + tags: ['validation', 'overfitting'], + summary: 'Purge and embargo overlapping labels across folds.', + body: 'Detailed CPCV methodology card body.', + }), + ], + findings: [ + makeFinding({ + id: 'find-01', + title: 'Earnings drift decay post-2023', + status: 'confirmed', + createdAt: '2025-02-01T10:00:00.000Z', + summary: 'Post-earnings drift attenuates within 3 sessions.', + trialRefs: ['trial-101'], + evidenceRefs: ['ev-202'], + }), + ], + providerCaveats: [ + makeCaveat({ + id: 'cav-01', + provider: 'eodhd', + dataset: 'eodPrices', + caveat: 'Backward split adjustments must be un-adjusted before research.', + createdAt: '2025-02-05T09:00:00.000Z', + }), + ], + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + createAnalyzeSignalTool({ + store, + ledger, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + principalId: 'operator', + }), + createEventStudyTool({ + store, + ledger, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + principalId: 'operator', + resolveExchangeCalendars: () => ({}), + }), + createSearchSymbolsTool({ + port: createMinimalSymbolPort(), + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + createReadKnowledgeTool({ port: fake.port }), + ], + }); + + const listRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/list', + }) + ); + expect(listRaw).not.toBeNull(); + + const listParsed = JSON.parse(listRaw as string) as { + result: { + tools: { + name: string; + description: string; + inputSchema: { + type: string; + properties: Record>; + required?: string[]; + additionalProperties: boolean; + }; + }[]; + }; + }; + + expect(listParsed.result.tools.map(t => t.name)).toEqual([ + 'query_data', + 'analyze_signal', + 'event_study', + 'search_symbols', + 'read_knowledge', + ]); + + const tool = listParsed.result.tools.find(t => t.name === 'read_knowledge'); + expect(tool).toBeDefined(); + expect(tool?.inputSchema.type).toBe('object'); + expect(tool?.inputSchema.additionalProperties).toBe(false); + expect(tool?.inputSchema.required).toBeUndefined(); + expect(tool?.inputSchema.properties.source).toMatchObject({ + type: 'string', + enum: [...READ_KNOWLEDGE_SOURCES], + default: 'all', + }); + expect(tool?.inputSchema.properties.query).toMatchObject({ + type: 'string', + minLength: 1, + maxLength: READ_KNOWLEDGE_MAX_QUERY_LENGTH, + }); + expect(tool?.inputSchema.properties.id).toMatchObject({ + type: 'string', + minLength: 1, + }); + expect(tool?.inputSchema.properties.tags).toMatchObject({ + type: 'array', + minItems: 1, + items: { type: 'string', minLength: 1 }, + }); + expect(tool?.inputSchema.properties.provider).toMatchObject({ + type: 'string', + minLength: 1, + }); + expect(tool?.inputSchema.properties.limit).toMatchObject({ + type: 'integer', + minimum: 1, + maximum: READ_KNOWLEDGE_MAX_LIMIT, + default: READ_KNOWLEDGE_DEFAULT_LIMIT, + }); + expect(tool?.inputSchema.properties.scope).toBeUndefined(); + expect(tool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); + expect(tool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); + + // Execute tools/call end-to-end on the multi-tool server. + const callRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { + name: 'read_knowledge', + arguments: { id: 'card-cpcv' }, + }, + }) + ); + expect(callRaw).not.toBeNull(); + const callParsed = JSON.parse(callRaw as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(callParsed.result.isError).toBeUndefined(); + const payload = JSON.parse(callParsed.result.content[0]?.text ?? '') as ReadKnowledgeResultPayload; + expect(payload).toEqual({ + rowCount: 1, + sources: { + library: 1, + findings: 0, + provider_caveats: 0, + }, + rows: [ + { + source: 'library', + id: 'card-cpcv', + title: 'Combinatorial Purged Cross-Validation', + tags: ['validation', 'overfitting'], + summary: 'Purge and embargo overlapping labels across folds.', + body: 'Detailed CPCV methodology card body.', + truncated: false, + }, + ], + }); + expect(new Set(fake.invokedMethods)).toEqual( + new Set(['listLibraryCards', 'listFindings', 'listProviderCaveats']) + ); + }); + + test('invokes only the selected source port methods with applicable parsed selectors', async () => { + const libraryCard = makeLibraryCard({ id: 'lib-1', tags: ['alpha'] }); + const finding = makeFinding({ id: 'fin-1' }); + const caveat = makeCaveat({ id: 'cav-1', provider: 'eodhd' }); + + // source: 'library' + const libFake = createFakeKnowledgePort({ + libraryCards: [libraryCard], + findings: [finding], + providerCaveats: [caveat], + }); + const libRes = await callReadKnowledge(libFake, { + source: 'library', + query: ' lib-1 ', + tags: [' alpha '], + provider: 'eodhd', + }); + expect(libRes.isError).toBe(false); + expect(libFake.invokedMethods).toEqual(['listLibraryCards']); + expect(libFake.libraryCalls).toEqual([{ query: 'lib-1', tags: ['alpha'] }]); + expect(libFake.findingsCalls).toHaveLength(0); + expect(libFake.caveatsCalls).toHaveLength(0); + expect(libRes.payload?.sources).toEqual({ library: 1, findings: 0, provider_caveats: 0 }); + + // source: 'findings' + const finFake = createFakeKnowledgePort({ + libraryCards: [libraryCard], + findings: [finding], + providerCaveats: [caveat], + }); + const finRes = await callReadKnowledge(finFake, { + source: 'findings', + query: ' fin-1 ', + tags: ['alpha'], + provider: 'eodhd', + }); + expect(finRes.isError).toBe(false); + expect(finFake.invokedMethods).toEqual(['listFindings']); + expect(finFake.findingsCalls).toEqual([{ query: 'fin-1' }]); + expect(finFake.libraryCalls).toHaveLength(0); + expect(finFake.caveatsCalls).toHaveLength(0); + expect(finRes.payload?.sources).toEqual({ library: 0, findings: 1, provider_caveats: 0 }); + + // source: 'provider_caveats' + const cavFake = createFakeKnowledgePort({ + libraryCards: [libraryCard], + findings: [finding], + providerCaveats: [caveat], + }); + const cavRes = await callReadKnowledge(cavFake, { + source: 'provider_caveats', + query: ' cav-1 ', + tags: ['alpha'], + provider: ' EODHD ', + }); + expect(cavRes.isError).toBe(false); + expect(cavFake.invokedMethods).toEqual(['listProviderCaveats']); + expect(cavFake.caveatsCalls).toEqual([{ query: 'cav-1', provider: 'EODHD' }]); + expect(cavFake.libraryCalls).toHaveLength(0); + expect(cavFake.findingsCalls).toHaveLength(0); + expect(cavRes.payload?.sources).toEqual({ library: 0, findings: 0, provider_caveats: 1 }); + + // source: 'all' (explicit) and omitted source + for (const args of [ + { source: 'all', id: ' shared-id ', tags: [' beta '], provider: ' polygon ' }, + { id: ' shared-id ', tags: [' beta '], provider: ' polygon ' }, + ]) { + const allFake = createFakeKnowledgePort(); + const allRes = await callReadKnowledge(allFake, args); + expect(allRes.isError).toBe(false); + expect(allFake.libraryCalls).toEqual([{ id: 'shared-id', tags: ['beta'] }]); + expect(allFake.findingsCalls).toEqual([{ id: 'shared-id' }]); + expect(allFake.caveatsCalls).toEqual([{ id: 'shared-id', provider: 'polygon' }]); + expect(allFake.invokedMethods).toEqual([ + 'listLibraryCards', + 'listFindings', + 'listProviderCaveats', + ]); + } + }); + + test('supports exact case-sensitive id precedence over query, missing id, and explicit field projection', async () => { + const extraCard = { + ...makeLibraryCard({ + id: 'Exact-Id', + title: 'Unrelated Title', + summary: 'Unrelated summary', + }), + internalSecret: 'must-not-leak', + } as unknown as LibraryCardRecord; + + const fake = createFakeKnowledgePort({ + libraryCards: [extraCard, makeLibraryCard({ id: 'exact-id', title: 'Lowercase ID' })], + findings: [makeFinding({ id: 'Exact-Id', title: 'Matching Finding ID' })], + providerCaveats: [makeCaveat({ id: 'Exact-Id', dataset: 'Matching Caveat ID' })], + }); + + // id takes precedence over non-matching query and is case-sensitive + const exactRes = await callReadKnowledge(fake, { + id: ' Exact-Id ', + query: 'nonexistent-query-text', + }); + expect(exactRes.isError).toBe(false); + expect(exactRes.payload?.rowCount).toBe(3); + expect(exactRes.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); + expect(exactRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ + 'library:Exact-Id', + 'findings:Exact-Id', + 'provider_caveats:Exact-Id', + ]); + expect('internalSecret' in (exactRes.payload?.rows[0] ?? {})).toBe(false); + + // Missing id returns empty result with zero counts + const missingRes = await callReadKnowledge(fake, { id: 'does-not-exist' }); + expect(missingRes.isError).toBe(false); + expect(missingRes.payload).toEqual({ + rowCount: 0, + sources: { library: 0, findings: 0, provider_caveats: 0 }, + rows: [], + }); + }); + + test('filters case-insensitively across titles, tags, summaries, caveats, and source-specific filters', async () => { + const fake = createFakeKnowledgePort({ + libraryCards: [ + makeLibraryCard({ + id: 'lib-tag', + title: 'Factor Neutrality', + tags: ['Momentum', 'Neutrality'], + summary: 'Dollar neutral weighting.', + }), + makeLibraryCard({ + id: 'lib-summary', + title: 'Execution Slippage', + tags: ['Microstructure'], + summary: 'Models MOMENTUM crowding impact.', + }), + makeLibraryCard({ + id: 'lib-only-one-tag', + title: 'Momentum Basics', + tags: ['Momentum'], + summary: 'Single tag card.', + }), + ], + findings: [ + makeFinding({ + id: 'fin-match', + title: 'Cross-sectional Momentum', + summary: 'Observed decay in 2024.', + }), + makeFinding({ + id: 'fin-other', + title: 'Value Spread', + summary: 'Unrelated finding.', + }), + ], + providerCaveats: [ + makeCaveat({ + id: 'cav-eodhd', + provider: 'EODHD', + dataset: 'eodPrices', + caveat: 'Momentum backtests need un-adjusted closes.', + }), + makeCaveat({ + id: 'cav-polygon', + provider: 'Polygon', + dataset: 'intraday1m', + caveat: 'Momentum bars omit odd lots.', + }), + ], + }); + + // With source: 'all', tags filters only library (all-tag match) and provider filters only caveats + const combinedRes = await callReadKnowledge(fake, { + query: ' momentum ', + tags: [' MOMENTUM ', 'neutrality'], + provider: ' eodhd ', + }); + expect(combinedRes.isError).toBe(false); + expect(combinedRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ + 'findings:fin-match', + 'provider_caveats:cav-eodhd', + 'library:lib-tag', + ]); + expect(combinedRes.payload?.sources).toEqual({ + library: 1, + findings: 1, + provider_caveats: 1, + }); + + // Empty result when query matches nothing + const emptyRes = await callReadKnowledge(fake, { query: 'zzz-no-match' }); + expect(emptyRes.isError).toBe(false); + expect(emptyRes.payload).toEqual({ + rowCount: 0, + sources: { library: 0, findings: 0, provider_caveats: 0 }, + rows: [], + }); + }); + + test('ranks deterministically across shuffled fixtures: exact id > title/dataset > other > ascending id > source order', async () => { + const libraryCards: LibraryCardRecord[] = [ + makeLibraryCard({ + id: 'tie-id', + title: 'Alpha title match', + tags: ['misc'], + summary: 'summary', + }), + makeLibraryCard({ + id: 'a-other', + title: 'Unrelated', + tags: ['alpha'], + summary: 'summary', + }), + makeLibraryCard({ + id: 'B-other', + title: 'Unrelated', + tags: ['misc'], + summary: 'Contains alpha in summary', + }), + ]; + const findings: FindingRecord[] = [ + makeFinding({ + id: 'tie-id', + title: 'Alpha finding title', + summary: 'summary', + }), + makeFinding({ + id: 'z-summary', + title: 'Unrelated finding', + summary: 'Mentions alpha here', + }), + ]; + const providerCaveats: ProviderCaveatRecord[] = [ + makeCaveat({ + id: 'tie-id', + provider: 'eodhd', + dataset: 'alpha_dataset', + caveat: 'caveat text', + }), + makeCaveat({ + id: 'c-provider', + provider: 'alpha-feed', + dataset: 'bars', + caveat: 'ordinary text', + }), + makeCaveat({ + id: 'd-caveat', + provider: 'other', + dataset: 'bars', + caveat: 'mentions alpha inside caveat', + }), + ]; + + const resA = await callReadKnowledge( + createFakeKnowledgePort({ libraryCards, findings, providerCaveats }), + { query: 'alpha' } + ); + const resB = await callReadKnowledge( + createFakeKnowledgePort({ + libraryCards: [...libraryCards].reverse(), + findings: [...findings].reverse(), + providerCaveats: [...providerCaveats].reverse(), + }), + { query: 'alpha' } + ); + + expect(resA.isError).toBe(false); + expect(resB.isError).toBe(false); + expect(resA.payload).toEqual(resB.payload); + + // Title/dataset matches first (all have id 'tie-id', broken by library -> findings -> provider_caveats), + // then other text matches ordered by ASCII/code-unit id ('B-other' < 'a-other' < 'c-provider' < 'd-caveat' < 'z-summary'). + expect(resA.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ + 'library:tie-id', + 'findings:tie-id', + 'provider_caveats:tie-id', + 'library:B-other', + 'library:a-other', + 'provider_caveats:c-provider', + 'provider_caveats:d-caveat', + 'findings:z-summary', + ]); + }); + + test('enforces default limit 20, hard max 100, late best match, and post-limit source counts', async () => { + // 25 eligible records (22 library + 3 findings) with default limit 20: + // Findings have title matches so they rank ahead of library summary matches, pushing 5 library rows out. + const lib22: LibraryCardRecord[] = []; + for (let i = 1; i <= 22; i += 1) { + lib22.push( + makeLibraryCard({ + id: `lib-${String(i).padStart(2, '0')}`, + title: 'Generic Card', + summary: 'Contains needle in summary', + }) + ); + } + const fin3: FindingRecord[] = [ + makeFinding({ id: 'fin-01', title: 'Needle Title 1', summary: 's' }), + makeFinding({ id: 'fin-02', title: 'Needle Title 2', summary: 's' }), + makeFinding({ id: 'fin-03', title: 'Needle Title 3', summary: 's' }), + ]; + + const defaultRes = await callReadKnowledge( + createFakeKnowledgePort({ libraryCards: lib22, findings: fin3 }), + { query: 'needle' } + ); + expect(defaultRes.isError).toBe(false); + expect(defaultRes.payload?.rowCount).toBe(20); + expect(defaultRes.payload?.rows).toHaveLength(20); + expect(defaultRes.payload?.sources).toEqual({ + library: 17, + findings: 3, + provider_caveats: 0, + }); + + // Hard max 100 with 115 eligible records and the best match placed last in the fixture + const lib115: LibraryCardRecord[] = []; + for (let i = 1; i <= 114; i += 1) { + lib115.push( + makeLibraryCard({ + id: `rec-${String(i).padStart(3, '0')}`, + title: 'Other', + summary: 'Contains signal in summary', + }) + ); + } + lib115.push( + makeLibraryCard({ + id: 'zzz-best-late', + title: 'Signal Title Match Placed Last', + summary: 'summary', + }) + ); + + const maxRes = await callReadKnowledge(createFakeKnowledgePort({ libraryCards: lib115 }), { + source: 'library', + query: 'signal', + limit: READ_KNOWLEDGE_MAX_LIMIT, + }); + expect(maxRes.isError).toBe(false); + expect(maxRes.payload?.rowCount).toBe(100); + expect(maxRes.payload?.rows).toHaveLength(100); + expect(maxRes.payload?.rows[0]?.id).toBe('zzz-best-late'); + expect(maxRes.payload?.sources).toEqual({ + library: 100, + findings: 0, + provider_caveats: 0, + }); + }); + + test('truncates body, summary, and caveat independently at 4096 chars after matching', async () => { + const exactCap = 'x'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH); + const overCapWithTailNeedle = `${'y'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH)}NEEDLE`; + const overCapOne = 'z'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 1); + + const fake = createFakeKnowledgePort({ + libraryCards: [ + makeLibraryCard({ + id: 'lib-exact', + title: 'Exact Cap Card', + summary: exactCap, + body: exactCap, + }), + makeLibraryCard({ + id: 'lib-over-body', + title: 'Over Cap Body', + summary: 'short summary', + body: overCapOne, + }), + makeLibraryCard({ + id: 'lib-over-summary-needle', + title: 'Late Needle Summary', + summary: overCapWithTailNeedle, + body: 'short body', + }), + ], + findings: [ + makeFinding({ + id: 'fin-exact', + title: 'Exact Finding', + summary: exactCap, + }), + makeFinding({ + id: 'fin-over-needle', + title: 'Late Needle Finding', + summary: overCapWithTailNeedle, + }), + ], + providerCaveats: [ + makeCaveat({ + id: 'cav-exact', + dataset: 'exact_ds', + caveat: exactCap, + }), + makeCaveat({ + id: 'cav-over-needle', + dataset: 'over_ds', + caveat: overCapWithTailNeedle, + }), + ], + }); + + // Exact cap rows are not truncated + for (const id of ['lib-exact', 'fin-exact', 'cav-exact']) { + const res = await callReadKnowledge(fake, { id }); + expect(res.isError).toBe(false); + expect(res.payload?.rows).toHaveLength(1); + const row = res.payload?.rows[0]; + expect(row?.truncated).toBe(false); + if (row?.source === 'library') { + expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); + expect(row.body).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); + } else if (row?.source === 'findings') { + expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); + } else if (row?.source === 'provider_caveats') { + expect(row.caveat).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); + } + } + + // Library body 1 char over cap is truncated independently while short summary is untouched + const overBodyRes = await callReadKnowledge(fake, { id: 'lib-over-body' }); + expect(overBodyRes.isError).toBe(false); + const bodyRow = overBodyRes.payload?.rows[0]; + expect(bodyRow?.source).toBe('library'); + if (bodyRow?.source === 'library') { + expect(bodyRow.truncated).toBe(true); + expect(bodyRow.summary).toBe('short summary'); + expect(bodyRow.body).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); + } + + // Query matching text beyond char 4096 still matches, then caps output to 4096 with truncated: true + const needleRes = await callReadKnowledge(fake, { query: 'needle' }); + expect(needleRes.isError).toBe(false); + expect(needleRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ + 'findings:fin-over-needle', + 'library:lib-over-summary-needle', + 'provider_caveats:cav-over-needle', + ]); + for (const row of needleRes.payload?.rows ?? []) { + expect(row.truncated).toBe(true); + if (row.source === 'library') { + expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); + expect(row.body).toBe('short body'); + } else if (row.source === 'findings') { + expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); + } else { + expect(row.caveat).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); + } + } + }); + + test('rejects strict input violations before invoking any port method', async () => { + const invalidInputs: Record[] = [ + { scope: 'vault_evaluation_only' }, + { vault_evaluation_only: true }, + { vaultCutoffTs: VAULT_CUTOFF_TS }, + { unexpectedKey: 'nope' }, + { query: 'A'.repeat(READ_KNOWLEDGE_MAX_QUERY_LENGTH + 1) }, + { query: '' }, + { query: ' \t\n ' }, + { id: '' }, + { id: ' ' }, + { provider: '' }, + { provider: ' ' }, + { tags: [] }, + { tags: ['valid', ' '] }, + { source: 'vault' }, + { source: 'LIBRARY' }, + { limit: 0 }, + { limit: -5 }, + { limit: READ_KNOWLEDGE_MAX_LIMIT + 1 }, + { limit: 1.5 }, + { limit: '10' }, + ]; + + for (const args of invalidInputs) { + expect(readKnowledgeInputSchema.safeParse(args).success).toBe(false); + const fake = createFakeKnowledgePort({ + libraryCards: [makeLibraryCard({ id: 'c1' })], + }); + const res = await callReadKnowledge(fake, args); + expect(res.isError).toBe(true); + expect(res.text).toContain('Invalid arguments for tool "read_knowledge"'); + expect(fake.invokedMethods).toHaveLength(0); + } + }); + + test('returns sanitized isError without leaking connection strings or stack traces when port rejects', async () => { + const secretError = new Error( + 'postgres://admin:super-secret@10.0.0.51:5432/trading_bot connection refused' + ); + secretError.stack = + 'Error: postgres://admin:super-secret@10.0.0.51:5432/trading_bot\n at internalQuery (/srv/secret/db.ts:42:9)'; + + // Single source failure + const singleFake = createFakeKnowledgePort({ libraryError: secretError }); + const singleRes = await callReadKnowledge(singleFake, { source: 'library', query: 'alpha' }); + expect(singleRes.isError).toBe(true); + expect(singleRes.text).toBe('Error: Tool execution failed.'); + expect(singleRes.text).not.toContain('super-secret'); + expect(singleRes.text).not.toContain('10.0.0.51'); + expect(singleRes.text).not.toContain('trading_bot'); + expect(singleRes.text).not.toContain('/srv/secret/db.ts'); + + // Partial failure under source: 'all' when other selected sources succeed + const partialFake = createFakeKnowledgePort({ + libraryCards: [makeLibraryCard({ id: 'ok-1', title: 'Alpha' })], + findingsError: secretError, + providerCaveats: [makeCaveat({ id: 'ok-2', dataset: 'Alpha' })], + }); + const partialRes = await callReadKnowledge(partialFake, { source: 'all', query: 'alpha' }); + expect(partialRes.isError).toBe(true); + expect(partialRes.text).toBe('Error: Tool execution failed.'); + expect(partialRes.text).not.toContain('super-secret'); + expect(partialRes.text).not.toContain('10.0.0.51'); + expect(partialRes.text).not.toContain('db.ts'); + }); + + test('factory throws on missing or invalid port options', () => { + expect(() => + createReadKnowledgeTool(null as unknown as Parameters[0]) + ).toThrow(); + + expect(() => + createReadKnowledgeTool({ port: null as unknown as KnowledgePort }) + ).toThrow(); + + expect(() => + createReadKnowledgeTool({ port: {} as unknown as KnowledgePort }) + ).toThrow(); + }); +}); From a98bfa8934c2cc929f7e2b5b5071b38ef90d9cd1 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 06:35:32 -0500 Subject: [PATCH 11/36] =?UTF-8?q?T-136:=20M2.1e=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`read=5Fknowledge`=20tool:=20read-only=20methodology=20card?= =?UTF-8?q?s=20+=20empirical=20findings=20/=20provider=20caveats=20lookup?= =?UTF-8?q?=20via=20injected=20ports=20in=20`libs/research/src/mcp/tools/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/read-knowledge.ts | 51 +++-- libs/research/test/mcp-read-knowledge.test.ts | 182 +++++++++++++++++- 2 files changed, 198 insertions(+), 35 deletions(-) diff --git a/libs/research/src/mcp/tools/read-knowledge.ts b/libs/research/src/mcp/tools/read-knowledge.ts index 1fb5b6e9..bdf695b6 100644 --- a/libs/research/src/mcp/tools/read-knowledge.ts +++ b/libs/research/src/mcp/tools/read-knowledge.ts @@ -313,15 +313,15 @@ function matchesAllTags( function rankLibraryCard( card: LibraryCardRecord, - input: ReadKnowledgeInput, + exactId: string | undefined, normalizedQuery: string | null, requiredLowerTags: readonly string[] | null ): number | null { if (requiredLowerTags !== null && !matchesAllTags(card.tags, requiredLowerTags)) { return null; } - if (input.id !== undefined) { - return card.id === input.id ? 0 : null; + if (exactId !== undefined) { + return card.id === exactId ? 0 : null; } if (normalizedQuery === null) { return 2; @@ -332,19 +332,16 @@ function rankLibraryCard( if (!titleMatches && !tagMatches && !summaryMatches) { return null; } - if (card.id === input.query) { - return 0; - } return titleMatches ? 1 : 2; } function rankFinding( finding: FindingRecord, - input: ReadKnowledgeInput, + exactId: string | undefined, normalizedQuery: string | null ): number | null { - if (input.id !== undefined) { - return finding.id === input.id ? 0 : null; + if (exactId !== undefined) { + return finding.id === exactId ? 0 : null; } if (normalizedQuery === null) { return 2; @@ -354,23 +351,20 @@ function rankFinding( if (!titleMatches && !summaryMatches) { return null; } - if (finding.id === input.query) { - return 0; - } return titleMatches ? 1 : 2; } function rankProviderCaveat( caveat: ProviderCaveatRecord, - input: ReadKnowledgeInput, + exactId: string | undefined, normalizedQuery: string | null, normalizedProvider: string | null ): number | null { if (normalizedProvider !== null && caveat.provider.toLowerCase() !== normalizedProvider) { return null; } - if (input.id !== undefined) { - return caveat.id === input.id ? 0 : null; + if (exactId !== undefined) { + return caveat.id === exactId ? 0 : null; } if (normalizedQuery === null) { return 2; @@ -381,9 +375,6 @@ function rankProviderCaveat( if (!datasetMatches && !providerMatches && !caveatMatches) { return null; } - if (caveat.id === input.query) { - return 0; - } return datasetMatches ? 1 : 2; } @@ -479,18 +470,20 @@ export function createReadKnowledgeTool(options: ReadKnowledgeToolOptions): McpT const wantFindings = input.source === 'all' || input.source === 'findings'; const wantCaveats = input.source === 'all' || input.source === 'provider_caveats'; + const baseQuery: FindingQuery = + input.id !== undefined + ? { id: input.id } + : input.query !== undefined + ? { query: input.query } + : {}; + const libraryQuery: LibraryCardQuery = { - ...(input.id !== undefined ? { id: input.id } : {}), - ...(input.query !== undefined ? { query: input.query } : {}), + ...baseQuery, ...(input.tags !== undefined ? { tags: input.tags } : {}), }; - const findingQuery: FindingQuery = { - ...(input.id !== undefined ? { id: input.id } : {}), - ...(input.query !== undefined ? { query: input.query } : {}), - }; + const findingQuery: FindingQuery = baseQuery; const caveatQuery: ProviderCaveatQuery = { - ...(input.id !== undefined ? { id: input.id } : {}), - ...(input.query !== undefined ? { query: input.query } : {}), + ...baseQuery, ...(input.provider !== undefined ? { provider: input.provider } : {}), }; @@ -515,7 +508,7 @@ export function createReadKnowledgeTool(options: ReadKnowledgeToolOptions): McpT } for (let i = 0; i < rawLibrary.length; i += 1) { const card = validateLibraryCard(rawLibrary[i] as LibraryCardRecord); - const rank = rankLibraryCard(card, input, normalizedQuery, requiredLowerTags); + const rank = rankLibraryCard(card, input.id, normalizedQuery, requiredLowerTags); if (rank !== null) { eligible.push({ rank, row: projectLibraryCard(card) }); } @@ -528,7 +521,7 @@ export function createReadKnowledgeTool(options: ReadKnowledgeToolOptions): McpT } for (let i = 0; i < rawFindings.length; i += 1) { const finding = validateFinding(rawFindings[i] as FindingRecord); - const rank = rankFinding(finding, input, normalizedQuery); + const rank = rankFinding(finding, input.id, normalizedQuery); if (rank !== null) { eligible.push({ rank, row: projectFinding(finding) }); } @@ -541,7 +534,7 @@ export function createReadKnowledgeTool(options: ReadKnowledgeToolOptions): McpT } for (let i = 0; i < rawCaveats.length; i += 1) { const caveat = validateProviderCaveat(rawCaveats[i] as ProviderCaveatRecord); - const rank = rankProviderCaveat(caveat, input, normalizedQuery, normalizedProvider); + const rank = rankProviderCaveat(caveat, input.id, normalizedQuery, normalizedProvider); if (rank !== null) { eligible.push({ rank, row: projectProviderCaveat(caveat) }); } diff --git a/libs/research/test/mcp-read-knowledge.test.ts b/libs/research/test/mcp-read-knowledge.test.ts index 85e25d22..ec32fe0e 100644 --- a/libs/research/test/mcp-read-knowledge.test.ts +++ b/libs/research/test/mcp-read-knowledge.test.ts @@ -79,6 +79,7 @@ function createFakeKnowledgePort(options?: { readonly libraryError?: unknown; readonly findingsError?: unknown; readonly caveatsError?: unknown; + readonly applySelectors?: boolean; }): FakePortState { const libraryCalls: LibraryCardQuery[] = []; const findingsCalls: FindingQuery[] = []; @@ -88,6 +89,7 @@ function createFakeKnowledgePort(options?: { const libraryCards = options?.libraryCards ?? []; const findings = options?.findings ?? []; const providerCaveats = options?.providerCaveats ?? []; + const applySelectors = options?.applySelectors === true; const rawPort: KnowledgePort = { async listLibraryCards(q: LibraryCardQuery): Promise { @@ -95,21 +97,83 @@ function createFakeKnowledgePort(options?: { if (options?.libraryError !== undefined) { throw options.libraryError; } - return [...libraryCards]; + if (!applySelectors) { + return [...libraryCards]; + } + return libraryCards.filter(card => { + if (q.id !== undefined && card.id !== q.id) { + return false; + } + if (q.tags !== undefined) { + const cardTags = new Set(card.tags.map(t => t.toLowerCase())); + if (!q.tags.every(t => cardTags.has(t.toLowerCase()))) { + return false; + } + } + if (q.query !== undefined) { + const needle = q.query.toLowerCase(); + const inText = + card.title.toLowerCase().includes(needle) || + card.summary.toLowerCase().includes(needle) || + card.tags.some(t => t.toLowerCase().includes(needle)); + if (!inText) { + return false; + } + } + return true; + }); }, async listFindings(q: FindingQuery): Promise { findingsCalls.push({ ...q }); if (options?.findingsError !== undefined) { throw options.findingsError; } - return [...findings]; + if (!applySelectors) { + return [...findings]; + } + return findings.filter(finding => { + if (q.id !== undefined && finding.id !== q.id) { + return false; + } + if (q.query !== undefined) { + const needle = q.query.toLowerCase(); + const inText = + finding.title.toLowerCase().includes(needle) || + finding.summary.toLowerCase().includes(needle); + if (!inText) { + return false; + } + } + return true; + }); }, async listProviderCaveats(q: ProviderCaveatQuery): Promise { caveatsCalls.push({ ...q }); if (options?.caveatsError !== undefined) { throw options.caveatsError; } - return [...providerCaveats]; + if (!applySelectors) { + return [...providerCaveats]; + } + return providerCaveats.filter(caveat => { + if (q.id !== undefined && caveat.id !== q.id) { + return false; + } + if (q.provider !== undefined && caveat.provider.toLowerCase() !== q.provider.toLowerCase()) { + return false; + } + if (q.query !== undefined) { + const needle = q.query.toLowerCase(); + const inText = + caveat.provider.toLowerCase().includes(needle) || + caveat.dataset.toLowerCase().includes(needle) || + caveat.caveat.toLowerCase().includes(needle); + if (!inText) { + return false; + } + } + return true; + }); }, }; @@ -526,6 +590,112 @@ describe('MCP read_knowledge tool', () => { }); }); + test('omits query from port selectors when id is supplied so selector-filtering ports return exact matches', async () => { + const filteringFake = createFakeKnowledgePort({ + applySelectors: true, + libraryCards: [ + makeLibraryCard({ + id: 'card-cpcv', + title: 'Combinatorial Purged Cross-Validation', + tags: ['validation'], + summary: 'Purge and embargo overlapping labels across folds.', + }), + ], + findings: [ + makeFinding({ + id: 'card-cpcv', + title: 'CPCV split stability', + summary: 'No mention of unrelated factors.', + }), + ], + providerCaveats: [ + makeCaveat({ + id: 'card-cpcv', + provider: 'eodhd', + dataset: 'eodPrices', + caveat: 'Backward split adjustments only.', + }), + ], + }); + + const res = await callReadKnowledge(filteringFake, { + id: 'card-cpcv', + query: 'momentum', + tags: ['validation'], + provider: 'eodhd', + }); + + expect(res.isError).toBe(false); + expect(filteringFake.libraryCalls).toEqual([{ id: 'card-cpcv', tags: ['validation'] }]); + expect(filteringFake.findingsCalls).toEqual([{ id: 'card-cpcv' }]); + expect(filteringFake.caveatsCalls).toEqual([{ id: 'card-cpcv', provider: 'eodhd' }]); + expect(res.payload?.rowCount).toBe(3); + expect(res.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); + expect(res.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ + 'library:card-cpcv', + 'findings:card-cpcv', + 'provider_caveats:card-cpcv', + ]); + }); + + test('does not grant exact-ID priority to free-text query matches and stays invariant to query capitalization', async () => { + const fake = createFakeKnowledgePort({ + libraryCards: [ + makeLibraryCard({ + id: 'momentum', + title: 'Factor Crowding Notes', + tags: ['risk'], + summary: 'Discusses momentum drawdown regimes.', + }), + makeLibraryCard({ + id: 'z-card', + title: 'Momentum Basics', + tags: ['factor'], + summary: 'Introductory overview.', + }), + ], + findings: [ + makeFinding({ + id: 'momentum', + title: 'Regime Decay', + summary: 'Observed momentum turnover costs.', + }), + makeFinding({ + id: 'z-finding', + title: 'Momentum Persistence', + summary: 'Observed over 2015–2024.', + }), + ], + providerCaveats: [ + makeCaveat({ + id: 'momentum', + provider: 'eodhd', + dataset: 'eodPrices', + caveat: 'Affects momentum backtests.', + }), + makeCaveat({ + id: 'z-caveat', + provider: 'eodhd', + dataset: 'momentum_signals', + caveat: 'Adjusted series.', + }), + ], + }); + + for (const source of ['library', 'findings', 'provider_caveats'] as const) { + const lowerTop = await callReadKnowledge(fake, { source, query: 'momentum', limit: 1 }); + const upperTop = await callReadKnowledge(fake, { source, query: 'MOMENTUM', limit: 1 }); + + expect(lowerTop.isError).toBe(false); + expect(upperTop.isError).toBe(false); + expect(lowerTop.payload).toEqual(upperTop.payload); + + const expectedId = + source === 'library' ? 'z-card' : source === 'findings' ? 'z-finding' : 'z-caveat'; + expect(lowerTop.payload?.rows.map(r => r.id)).toEqual([expectedId]); + } + }); + test('filters case-insensitively across titles, tags, summaries, caveats, and source-specific filters', async () => { const fake = createFakeKnowledgePort({ libraryCards: [ @@ -777,7 +947,7 @@ describe('MCP read_knowledge tool', () => { }), makeLibraryCard({ id: 'lib-over-summary-needle', - title: 'Late Needle Summary', + title: 'Late Match Summary', summary: overCapWithTailNeedle, body: 'short body', }), @@ -790,7 +960,7 @@ describe('MCP read_knowledge tool', () => { }), makeFinding({ id: 'fin-over-needle', - title: 'Late Needle Finding', + title: 'Late Match Finding', summary: overCapWithTailNeedle, }), ], @@ -840,9 +1010,9 @@ describe('MCP read_knowledge tool', () => { const needleRes = await callReadKnowledge(fake, { query: 'needle' }); expect(needleRes.isError).toBe(false); expect(needleRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ + 'provider_caveats:cav-over-needle', 'findings:fin-over-needle', 'library:lib-over-summary-needle', - 'provider_caveats:cav-over-needle', ]); for (const row of needleRes.payload?.rows ?? []) { expect(row.truncated).toBe(true); From 30552a661d9279aa2c93abd1c901e47f46ed0c9d Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 06:41:41 -0500 Subject: [PATCH 12/36] T-136: tests --- .../test/mcp-read-knowledge-qa.test.ts | 504 ++++++++++++++++++ 1 file changed, 504 insertions(+) create mode 100644 libs/research/test/mcp-read-knowledge-qa.test.ts diff --git a/libs/research/test/mcp-read-knowledge-qa.test.ts b/libs/research/test/mcp-read-knowledge-qa.test.ts new file mode 100644 index 00000000..fbbf4a44 --- /dev/null +++ b/libs/research/test/mcp-read-knowledge-qa.test.ts @@ -0,0 +1,504 @@ +import { describe, expect, test } from 'bun:test'; +import { + createMcpServer, + createReadKnowledgeTool, + type FindingQuery, + type FindingRecord, + type KnowledgePort, + type LibraryCardQuery, + type LibraryCardRecord, + type ProviderCaveatQuery, + type ProviderCaveatRecord, + READ_KNOWLEDGE_MAX_LIMIT, + READ_KNOWLEDGE_MAX_QUERY_LENGTH, + READ_KNOWLEDGE_MAX_TEXT_LENGTH, + type ReadKnowledgeResultPayload, +} from '../src/mcp/index'; + +// QA fixtures: deterministic in-memory KnowledgePort (no network, no Postgres, +// no filesystem). All timestamps are pinned ISO strings; shuffles use a seeded PRNG. + +const SECRET = 'postgres://admin:super-secret@10.0.0.51:5432/trading_bot'; + +function card(id: string, o: Partial = {}): LibraryCardRecord { + return { + id, + title: o.title ?? `Card ${id}`, + tags: o.tags ?? ['methodology'], + summary: o.summary ?? `Summary ${id}`, + body: o.body ?? `Body ${id}`, + }; +} + +function finding(id: string, o: Partial = {}): FindingRecord { + return { + id, + title: o.title ?? `Finding ${id}`, + status: o.status ?? 'confirmed', + createdAt: o.createdAt ?? '2025-01-15T12:00:00.000Z', + summary: o.summary ?? `Finding summary ${id}`, + trialRefs: o.trialRefs ?? [`trial-${id}`], + evidenceRefs: o.evidenceRefs ?? [`ev-${id}`], + }; +} + +function caveat(id: string, o: Partial = {}): ProviderCaveatRecord { + return { + id, + provider: o.provider ?? 'eodhd', + dataset: o.dataset ?? `dataset_${id}`, + caveat: o.caveat ?? `Caveat ${id}`, + createdAt: o.createdAt ?? '2025-01-20T08:30:00.000Z', + }; +} + +interface PortImpl { + readonly library?: (q: LibraryCardQuery) => unknown; + readonly findings?: (q: FindingQuery) => unknown; + readonly caveats?: (q: ProviderCaveatQuery) => unknown; +} + +function makePort(impl: PortImpl): { port: KnowledgePort; calls: string[] } { + const calls: string[] = []; + const port: KnowledgePort = { + listLibraryCards(q) { + calls.push('listLibraryCards'); + return (impl.library ?? (() => Promise.resolve([])))(q) as Promise< + readonly LibraryCardRecord[] + >; + }, + listFindings(q) { + calls.push('listFindings'); + return (impl.findings ?? (() => Promise.resolve([])))(q) as Promise< + readonly FindingRecord[] + >; + }, + listProviderCaveats(q) { + calls.push('listProviderCaveats'); + return (impl.caveats ?? (() => Promise.resolve([])))(q) as Promise< + readonly ProviderCaveatRecord[] + >; + }, + }; + return { port, calls }; +} + +function staticPort( + library: readonly LibraryCardRecord[], + findings: readonly FindingRecord[], + caveats: readonly ProviderCaveatRecord[] +): { port: KnowledgePort; calls: string[] } { + return makePort({ + library: async () => library, + findings: async () => findings, + caveats: async () => caveats, + }); +} + +async function call( + port: KnowledgePort, + args: Record | undefined +): Promise<{ isError: boolean; text: string; payload: ReadKnowledgeResultPayload | null }> { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [createReadKnowledgeTool({ port })], + }); + const params: Record = { name: 'read_knowledge' }; + if (args !== undefined) { + params.arguments = args; + } + const raw = await server.handleMessage( + JSON.stringify({ jsonrpc: '2.0', id: 'qa', method: 'tools/call', params }) + ); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + const isError = parsed.result.isError === true; + const text = parsed.result.content[0]?.text ?? ''; + return { isError, text, payload: isError ? null : (JSON.parse(text) as ReadKnowledgeResultPayload) }; +} + +function expectSanitized(res: { isError: boolean; text: string }): void { + expect(res.isError).toBe(true); + expect(res.text).toMatch(/^[A-Za-z][A-Za-z0-9_]*: Tool execution failed\.$/); + for (const leak of ['super-secret', '10.0.0.51', 'trading_bot', 'postgres://', 'db.ts', ' at ']) { + expect(res.text).not.toContain(leak); + } +} + +function deepFreeze(value: T): T { + if (typeof value === 'object' && value !== null) { + for (const v of Object.values(value)) { + deepFreeze(v); + } + Object.freeze(value); + } + return value; +} + +// mulberry32 — seeded PRNG for reproducible shuffles. +function seededShuffle(items: readonly T[], seed: number): T[] { + let s = seed >>> 0; + const rand = (): number => { + s = (s + 0x6d2b79f5) >>> 0; + let t = s; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + const out = [...items]; + for (let i = out.length - 1; i > 0; i -= 1) { + const j = Math.floor(rand() * (i + 1)); + [out[i], out[j]] = [out[j] as T, out[i] as T]; + } + return out; +} + +describe('read_knowledge QA: port failures and malformed port output', () => { + test('non-Error rejections and synchronous throws carrying connection strings are sanitized', async () => { + const cases: PortImpl[] = [ + { library: () => Promise.reject(SECRET) }, + { findings: () => Promise.reject({ message: SECRET, stack: 'at /srv/db.ts:1' }) }, + { + caveats: () => { + throw new Error(SECRET); + }, + }, + { + library: () => { + const err = new Error(SECRET); + err.name = SECRET; + throw err; + }, + }, + ]; + for (const impl of cases) { + const { port } = makePort(impl); + const res = await call(port, { query: 'alpha' }); + expectSanitized(res); + } + }); + + test('malformed port responses map to a sanitized isError without echoing record contents', async () => { + const badResponses: PortImpl[] = [ + { library: async () => SECRET }, + { library: async () => undefined }, + { library: async () => [null] }, + { library: async () => [{ ...card('c1'), id: 42 }] }, + { library: async () => [{ ...card('c1'), tags: [SECRET, 7] }] }, + { library: async () => [{ ...card('c1'), tags: SECRET }] }, + { findings: async () => [{ ...finding('f1'), trialRefs: undefined }] }, + { findings: async () => [{ ...finding('f1'), createdAt: 1_700_000_000_000 }] }, + { caveats: async () => [{ ...caveat('v1'), caveat: { text: SECRET } }] }, + { caveats: async () => ({ rows: [caveat('v1')] }) }, + ]; + for (const impl of badResponses) { + const { port } = makePort(impl); + const res = await call(port, {}); + expectSanitized(res); + } + }); +}); + +describe('read_knowledge QA: read-only port usage', () => { + test('never calls write-like methods present on the injected object and calls each read method at most once', async () => { + const writes: string[] = []; + const base = staticPort([card('c1')], [finding('f1')], [caveat('v1')]); + const port = Object.assign(base.port, { + fileFinding: () => writes.push('fileFinding'), + upsertCard: () => writes.push('upsertCard'), + deleteCaveat: () => writes.push('deleteCaveat'), + }); + + for (const args of [{}, { source: 'library' }, { id: 'f1' }, { query: 'card', limit: 1 }]) { + base.calls.length = 0; + const res = await call(port, args); + expect(res.isError).toBe(false); + expect(new Set(base.calls).size).toBe(base.calls.length); + } + expect(writes).toEqual([]); + }); + + test('does not mutate deeply frozen port records and returns copies of array fields', async () => { + const lib = deepFreeze([card('c1', { tags: ['Alpha', 'beta'], body: 'b'.repeat(5000) })]); + const fin = deepFreeze([finding('f1', { title: 'Alpha finding' })]); + const cav = deepFreeze([caveat('v1', { dataset: 'alpha_ds', caveat: 'c'.repeat(5000) })]); + const snapshot = JSON.stringify([lib, fin, cav]); + const { port } = staticPort(lib, fin, cav); + + const res = await call(port, { query: 'alpha', tags: ['ALPHA'] }); + + expect(res.isError).toBe(false); + expect(res.payload?.rowCount).toBe(3); + expect(JSON.stringify([lib, fin, cav])).toBe(snapshot); + }); + + test('omitted tools/call arguments use defaults and call all three sources with an empty selector', async () => { + const seen: unknown[] = []; + const { port, calls } = makePort({ + library: async q => { + seen.push(q); + return [card('c1')]; + }, + findings: async q => { + seen.push(q); + return [finding('f1')]; + }, + caveats: async q => { + seen.push(q); + return [caveat('v1')]; + }, + }); + + const res = await call(port, undefined); + + expect(res.isError).toBe(false); + expect(calls.sort()).toEqual(['listFindings', 'listLibraryCards', 'listProviderCaveats']); + expect(seen).toEqual([{}, {}, {}]); + expect(res.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); + }); +}); + +describe('read_knowledge QA: input boundaries', () => { + test('accepts query at exactly the cap, including when surrounding whitespace is trimmed', async () => { + const atCap = 'q'.repeat(READ_KNOWLEDGE_MAX_QUERY_LENGTH); + const seen: (string | undefined)[] = []; + const { port } = makePort({ + library: async q => { + seen.push(q.query); + return [card('c1', { title: `x${atCap}x` })]; + }, + }); + + for (const query of [atCap, ` ${atCap}\t\n `]) { + const res = await call(port, { source: 'library', query }); + expect(res.isError).toBe(false); + expect(res.payload?.rows.map(r => r.id)).toEqual(['c1']); + } + expect(seen).toEqual([atCap, atCap]); + }); + + test('accepts limit 1 and limit max as boundary values', async () => { + const lib = Array.from({ length: READ_KNOWLEDGE_MAX_LIMIT + 5 }, (_, i) => + card(`c${String(i).padStart(3, '0')}`) + ); + const { port } = staticPort(lib, [], []); + + const one = await call(port, { limit: 1 }); + const max = await call(port, { limit: READ_KNOWLEDGE_MAX_LIMIT }); + + expect(one.payload?.rows.map(r => r.id)).toEqual(['c000']); + expect(max.payload?.rowCount).toBe(READ_KNOWLEDGE_MAX_LIMIT); + expect(max.payload?.rows.at(-1)?.id).toBe('c099'); + }); + + test('rejects null-valued optional selectors and non-array tags before calling the port', async () => { + for (const args of [ + { query: null }, + { id: null }, + { tags: 'alpha' }, + { tags: [1] }, + { provider: ['eodhd'] }, + { source: null }, + { limit: null }, + { limit: Number.POSITIVE_INFINITY }, + ]) { + const { port, calls } = staticPort([card('c1')], [], []); + const res = await call(port, args); + expect(res.isError).toBe(true); + expect(res.text).toContain('Invalid arguments for tool "read_knowledge"'); + expect(calls).toEqual([]); + } + }); +}); + +describe('read_knowledge QA: matching semantics', () => { + test('free-text query does not match on id, status, createdAt, or trial/evidence refs alone', async () => { + const { port } = staticPort( + [card('zeta-card', { title: 'A', tags: ['b'], summary: 'c', body: 'zeta in body only' })], + [ + finding('zeta-finding', { + title: 'A', + summary: 'c', + status: 'zeta', + createdAt: 'zeta', + trialRefs: ['zeta'], + evidenceRefs: ['zeta'], + }), + ], + [caveat('zeta-caveat', { provider: 'p', dataset: 'd', caveat: 'c', createdAt: 'zeta' })] + ); + + const res = await call(port, { query: 'zeta' }); + + expect(res.payload).toEqual({ + rowCount: 0, + sources: { library: 0, findings: 0, provider_caveats: 0 }, + rows: [], + }); + }); + + test('provider filter is exact (not substring) and tags filter requires whole-tag equality', async () => { + const { port } = staticPort( + [card('c-full', { tags: ['momentum'] }), card('c-partial', { tags: ['momentum-crash'] })], + [], + [caveat('v-eodhd', { provider: 'eodhd' }), caveat('v-eod', { provider: 'eod' })] + ); + + const byProvider = await call(port, { source: 'provider_caveats', provider: 'EOD' }); + const byTag = await call(port, { source: 'library', tags: ['Momentum'] }); + + expect(byProvider.payload?.rows.map(r => r.id)).toEqual(['v-eod']); + expect(byTag.payload?.rows.map(r => r.id)).toEqual(['c-full']); + }); + + test('provider matched in free text ranks below a dataset match for caveats', async () => { + const { port } = staticPort( + [], + [], + [ + caveat('a-provider', { provider: 'quantmedia', dataset: 'bars', caveat: 'x' }), + caveat('z-dataset', { provider: 'eodhd', dataset: 'quantmedia_filings', caveat: 'x' }), + ] + ); + + const res = await call(port, { query: 'QuantMedia' }); + + expect(res.payload?.rows.map(r => r.id)).toEqual(['z-dataset', 'a-provider']); + }); + + test('id lookup still honours source-specific filters: tag mismatch drops the card but keeps other sources under all', async () => { + const { port } = staticPort( + [card('shared', { tags: ['risk'] })], + [finding('shared')], + [caveat('shared', { provider: 'polygon' })] + ); + + const res = await call(port, { id: 'shared', tags: ['momentum'], provider: 'eodhd' }); + + expect(res.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual(['findings:shared']); + expect(res.payload?.sources).toEqual({ library: 0, findings: 1, provider_caveats: 0 }); + }); + + test('case-insensitive matching handles non-ASCII text', async () => { + const { port } = staticPort( + [card('c1', { title: 'Étude des rendements' })], + [finding('f1', { summary: 'ÜBERRENDITE nach Ankündigung' })], + [] + ); + + const res = await call(port, { query: 'étude' }); + const res2 = await call(port, { query: 'überrendite' }); + + expect(res.payload?.rows.map(r => r.id)).toEqual(['c1']); + expect(res2.payload?.rows.map(r => r.id)).toEqual(['f1']); + }); + + test('projects exactly the documented fields for findings and caveats, dropping extra port fields', async () => { + const extraFinding = { ...finding('f1'), holdoutPnl: 123, dsn: SECRET } as FindingRecord; + const extraCaveat = { ...caveat('v1'), internalNote: SECRET } as ProviderCaveatRecord; + const { port } = staticPort([], [extraFinding], [extraCaveat]); + + const res = await call(port, {}); + + expect(res.text).not.toContain('super-secret'); + expect(res.text).not.toContain('holdoutPnl'); + expect(res.payload?.rows).toEqual([ + { + source: 'findings', + id: 'f1', + title: 'Finding f1', + status: 'confirmed', + createdAt: '2025-01-15T12:00:00.000Z', + summary: 'Finding summary f1', + trialRefs: ['trial-f1'], + evidenceRefs: ['ev-f1'], + truncated: false, + }, + { + source: 'provider_caveats', + id: 'v1', + provider: 'eodhd', + dataset: 'dataset_v1', + caveat: 'Caveat v1', + createdAt: '2025-01-20T08:30:00.000Z', + truncated: false, + }, + ]); + }); +}); + +describe('read_knowledge QA: deterministic ranking and limit', () => { + test('seeded permutations of a mixed fixture replay to identical rows and counts at every limit', async () => { + const lib = [ + card('m-title', { title: 'Drift study', summary: 's' }), + card('a-tag', { title: 'x', tags: ['drift'] }), + card('Q-sum', { title: 'x', summary: 'post drift' }), + card('shared', { title: 'Drift shared', summary: 's' }), + ]; + const fin = [ + finding('shared', { title: 'Drift finding' }), + finding('b-sum', { title: 'x', summary: 'DRIFT' }), + finding('k-none', { title: 'x', summary: 'nothing' }), + ]; + const cav = [ + caveat('shared', { dataset: 'drift_ds' }), + caveat('c-cav', { dataset: 'bars', caveat: 'drift noted' }), + ]; + + for (const limit of [1, 2, 3, 5, 8, 20]) { + let baseline: ReadKnowledgeResultPayload | null = null; + for (let seed = 1; seed <= 12; seed += 1) { + const { port } = staticPort( + seededShuffle(lib, seed), + seededShuffle(fin, seed * 7), + seededShuffle(cav, seed * 13) + ); + const res = await call(port, { query: 'drift', limit }); + expect(res.isError).toBe(false); + if (baseline === null) { + baseline = res.payload; + } else { + expect(res.payload).toEqual(baseline); + } + } + const expectedOrder = [ + 'library:m-title', + 'library:shared', + 'findings:shared', + 'provider_caveats:shared', + 'library:Q-sum', + 'library:a-tag', + 'findings:b-sum', + 'provider_caveats:c-cav', + ].slice(0, limit); + expect(baseline?.rows.map(r => `${r.source}:${r.id}`)).toEqual(expectedOrder); + const counts = { library: 0, findings: 0, provider_caveats: 0 }; + for (const r of baseline?.rows ?? []) { + counts[r.source] += 1; + } + expect(baseline?.sources).toEqual(counts); + expect(baseline?.rowCount).toBe(expectedOrder.length); + } + }); + + test('truncation flag reflects only text fields over the cap; title, tags and refs are never truncated', async () => { + const longTitle = 'T'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 10); + const { port } = staticPort( + [card('c1', { title: longTitle, tags: ['t'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 1)] })], + [finding('f1', { title: longTitle })], + [] + ); + + const res = await call(port, {}); + + for (const row of res.payload?.rows ?? []) { + expect(row.truncated).toBe(false); + if (row.source !== 'provider_caveats') { + expect(row.title).toHaveLength(longTitle.length); + } + } + }); +}); From d3a5105327a8fb0ae0ee04e6ade5c1f3d8e9ad04 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:02:07 -0500 Subject: [PATCH 13/36] T-136: tests --- .../test/mcp-read-knowledge-qa.test.ts | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/libs/research/test/mcp-read-knowledge-qa.test.ts b/libs/research/test/mcp-read-knowledge-qa.test.ts index fbbf4a44..0e2940a3 100644 --- a/libs/research/test/mcp-read-knowledge-qa.test.ts +++ b/libs/research/test/mcp-read-knowledge-qa.test.ts @@ -200,6 +200,48 @@ describe('read_knowledge QA: port failures and malformed port output', () => { expectSanitized(res); } }); + + // Regression: port calls were started eagerly inside the Promise.all array literal, so a + // synchronous throw from a later source abandoned an earlier source's rejected promise. + // Bun treats that unhandled rejection as fatal: the MCP stdio process exits 1 after replying + // and prints the raw error (including any connection string) to stderr. Bun's test runner + // also reports it as an error between tests, so the scenario runs in a child process. + test('earlier async rejection combined with a later synchronous throw does not crash the process', () => { + const indexPath = new URL('../src/mcp/index.ts', import.meta.url).pathname; + const script = ` + import { createMcpServer, createReadKnowledgeTool } from ${JSON.stringify(indexPath)}; + const secret = ${JSON.stringify(SECRET)}; + const combos = [ + { listLibraryCards: () => Promise.reject(new Error(secret)), listFindings: () => { throw new Error('sync'); }, listProviderCaveats: async () => [] }, + { listLibraryCards: () => Promise.reject(new Error(secret)), listFindings: async () => [], listProviderCaveats: () => { throw new Error('sync'); } }, + { listLibraryCards: async () => [], listFindings: () => Promise.reject(new Error(secret)), listProviderCaveats: () => { throw new Error('sync'); } }, + ]; + for (const port of combos) { + const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [createReadKnowledgeTool({ port })] }); + const raw = await server.handleMessage(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'read_knowledge', arguments: {} } })); + console.log(JSON.parse(raw).result.content[0].text); + } + await new Promise(resolve => setTimeout(resolve, 20)); + console.log('DONE'); + `; + + const proc = Bun.spawnSync([process.execPath, '-e', script], { + stdout: 'pipe', + stderr: 'pipe', + timeout: 30_000, + }); + const stdout = proc.stdout.toString(); + const stderr = proc.stderr.toString(); + + expect(stdout.trim().split('\n')).toEqual([ + 'Error: Tool execution failed.', + 'Error: Tool execution failed.', + 'Error: Tool execution failed.', + 'DONE', + ]); + expect(stderr).not.toContain('super-secret'); + expect(proc.exitCode).toBe(0); + }); }); describe('read_knowledge QA: read-only port usage', () => { From 9ca80bd537d630a40744a1112f1a848859ae2abe Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:06:34 -0500 Subject: [PATCH 14/36] =?UTF-8?q?T-136:=20M2.1e=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`read=5Fknowledge`=20tool:=20read-only=20methodology=20card?= =?UTF-8?q?s=20+=20empirical=20findings=20/=20provider=20caveats=20lookup?= =?UTF-8?q?=20via=20injected=20ports=20in=20`libs/research/src/mcp/tools/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/read-knowledge.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libs/research/src/mcp/tools/read-knowledge.ts b/libs/research/src/mcp/tools/read-knowledge.ts index bdf695b6..929b398f 100644 --- a/libs/research/src/mcp/tools/read-knowledge.ts +++ b/libs/research/src/mcp/tools/read-knowledge.ts @@ -488,9 +488,9 @@ export function createReadKnowledgeTool(options: ReadKnowledgeToolOptions): McpT }; const [rawLibrary, rawFindings, rawCaveats] = await Promise.all([ - wantLibrary ? port.listLibraryCards(libraryQuery) : Promise.resolve(null), - wantFindings ? port.listFindings(findingQuery) : Promise.resolve(null), - wantCaveats ? port.listProviderCaveats(caveatQuery) : Promise.resolve(null), + (async () => (wantLibrary ? port.listLibraryCards(libraryQuery) : null))(), + (async () => (wantFindings ? port.listFindings(findingQuery) : null))(), + (async () => (wantCaveats ? port.listProviderCaveats(caveatQuery) : null))(), ]); const normalizedQuery = From 70e6bd30bf41d38fa5c6d03e68a81da7c2a75298 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:12:52 -0500 Subject: [PATCH 15/36] T-136: tests --- libs/research/test/mcp-read-knowledge-qa.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/libs/research/test/mcp-read-knowledge-qa.test.ts b/libs/research/test/mcp-read-knowledge-qa.test.ts index 0e2940a3..33bfac80 100644 --- a/libs/research/test/mcp-read-knowledge-qa.test.ts +++ b/libs/research/test/mcp-read-knowledge-qa.test.ts @@ -424,6 +424,22 @@ describe('read_knowledge QA: matching semantics', () => { expect(res.payload?.sources).toEqual({ library: 0, findings: 1, provider_caveats: 0 }); }); + test('regex and wildcard metacharacters in query are matched literally', async () => { + const { port } = staticPort( + [card('c-literal', { title: 'Sharpe (annualised) * sqrt(252)' }), card('c-plain', { title: 'Sharpe annualised' })], + [finding('f-dot', { summary: 'a.b' }), finding('f-any', { summary: 'axb' })], + [caveat('v-pct', { caveat: '100% adjusted' }), caveat('v-none', { caveat: '100 adjusted' })] + ); + + const paren = await call(port, { query: '(annualised) *' }); + const dot = await call(port, { query: 'a.b' }); + const pct = await call(port, { query: '100%' }); + + expect(paren.payload?.rows.map(r => r.id)).toEqual(['c-literal']); + expect(dot.payload?.rows.map(r => r.id)).toEqual(['f-dot']); + expect(pct.payload?.rows.map(r => r.id)).toEqual(['v-pct']); + }); + test('case-insensitive matching handles non-ASCII text', async () => { const { port } = staticPort( [card('c1', { title: 'Étude des rendements' })], From 46d4c59132e80b57f0a1a358f21a7310306d5994 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:22:36 -0500 Subject: [PATCH 16/36] T-136: tests --- .../test/mcp-read-knowledge-qa.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/libs/research/test/mcp-read-knowledge-qa.test.ts b/libs/research/test/mcp-read-knowledge-qa.test.ts index 33bfac80..b9d233c5 100644 --- a/libs/research/test/mcp-read-knowledge-qa.test.ts +++ b/libs/research/test/mcp-read-knowledge-qa.test.ts @@ -560,3 +560,22 @@ describe('read_knowledge QA: deterministic ranking and limit', () => { } }); }); + +describe('read_knowledge QA: limit cutting through a cross-source tie', () => { + test('limit inside a same-id tie keeps library > findings > provider_caveats and counts only returned rows', async () => { + const { port } = staticPort( + [card('dup', { title: 'Basis risk' })], + [finding('dup', { title: 'Basis risk' })], + [caveat('dup', { dataset: 'basis_ds' })] + ); + + const two = await call(port, { query: 'basis', limit: 2 }); + + expect(two.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ + 'library:dup', + 'findings:dup', + ]); + expect(two.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 0 }); + expect(two.payload?.rowCount).toBe(2); + }); +}); From 2eefa9f168b52a51e778b89b6b912e4c12558541 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:33:48 -0500 Subject: [PATCH 17/36] =?UTF-8?q?T-138:=20M2.1f=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`file=5Ffinding`=20tool:=20validated,=20append-only=20empir?= =?UTF-8?q?ical=20finding=20/=20dead-end=20filing=20via=20an=20injected=20?= =?UTF-8?q?`FindingWritePort`=20in=20`libs/research/src/mcp/tools/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 7 +- libs/research/src/mcp/index.ts | 1 + libs/research/src/mcp/tools/file-finding.ts | 416 +++++++ libs/research/test/mcp-file-finding.test.ts | 1100 +++++++++++++++++++ 4 files changed, 1523 insertions(+), 1 deletion(-) create mode 100644 libs/research/src/mcp/tools/file-finding.ts create mode 100644 libs/research/test/mcp-file-finding.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index 944b6498..03973ff5 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -218,8 +218,13 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **Injected exchange calendars:** `resolveExchangeCalendars({ listingIds, fromDate, toDate })` supplies actual exchange session close timestamps (including half-days) for `buildEventStudyInput` so events are anchored without synthesizing calendars from bars. - **Returns, benchmark & Vault fence:** Models daily close-to-close returns with no execution or transaction costs (`adjustment` defaults to `'raw'`; `benchmark` defaults to `'equal_weight'` using available eligible listing returns, or `'none'` for unbenchmarked returns). Enforces `scope: 'vault_fenced'`, clamps `to`/`asOf` strictly below `vaultCutoffTs`, resolves named universes strictly pre-start, defensively excludes any bar or event on or after the Vault cutoff date (or with `known_at > asOf`), and writes eligible trials exclusively to the injected `trial_ledger` (`stage = 'event_study'`) under the server-injected `principalId`. +### `file_finding` Tool (Append-Only) + +- **`createFileFindingTool({ port, trialLookup, newId, now })`** — Files an append-only empirical `finding` or `dead_end` record linked to 1–32 research-visible `trial_ledger` references (`trialRefs`, capped at 256 chars each) and 0–32 optional opaque snapshot identifiers (`evidenceRefs`, never dereferenced by the tool). Trims and enforces hard limits (`title` ≤ 256, `summary` ≤ 4,096, `idempotencyKey` ≤ 128), applies array bounds before case-sensitive deduplication and sorting, and rejects unknown fields with a fixed message. +- **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`. + ### Remaining M2 MCP Items (Later Tasks) -- Additional research tools: `search_symbols`, `analyze_signal`, `file_finding`, and `read_knowledge`. - SSE/HTTP transport wrapper in `apps/stock/web-api`. - Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters. diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 5241cac4..f228f04a 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -3,6 +3,7 @@ export * from './server'; export * from './stdio'; export * from './tools/analyze-signal'; export * from './tools/event-study'; +export * from './tools/file-finding'; export * from './tools/query-data'; export * from './tools/read-knowledge'; export * from './tools/search-symbols'; diff --git a/libs/research/src/mcp/tools/file-finding.ts b/libs/research/src/mcp/tools/file-finding.ts new file mode 100644 index 00000000..97fb8d3f --- /dev/null +++ b/libs/research/src/mcp/tools/file-finding.ts @@ -0,0 +1,416 @@ +import { z } from 'zod'; +import type { McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool } from '../server'; +import { type FindingRecord, READ_KNOWLEDGE_MAX_TEXT_LENGTH } from './read-knowledge'; +import { MAX_ECMASCRIPT_EPOCH_MS } from './vault-fenced-input'; + +/** Supported filing kinds for `file_finding` (per D12 in `design/PLATFORM-PLAN.md`). */ +export const FILE_FINDING_KINDS = ['finding', 'dead_end'] as const; + +export type FileFindingKind = (typeof FILE_FINDING_KINDS)[number]; + +/** Initial server-assigned review status for every newly filed finding or dead end. */ +export const FILE_FINDING_INITIAL_STATUS = 'pending_review' as const; + +export type FileFindingInitialStatus = typeof FILE_FINDING_INITIAL_STATUS; + +/** Hard maximum character length of a trimmed `file_finding` title. */ +export const FILE_FINDING_MAX_TITLE_LENGTH = 256; + +/** Hard maximum character length of a trimmed `file_finding` summary. */ +export const FILE_FINDING_MAX_SUMMARY_LENGTH = READ_KNOWLEDGE_MAX_TEXT_LENGTH; + +/** Hard maximum character length of a trimmed trial or evidence reference string. */ +export const FILE_FINDING_MAX_REF_LENGTH = 256; + +/** Hard maximum number of raw `trialRefs` accepted before deduplication. */ +export const FILE_FINDING_MAX_TRIAL_REFS = 32; + +/** Hard maximum number of raw `evidenceRefs` accepted before deduplication. */ +export const FILE_FINDING_MAX_EVIDENCE_REFS = 32; + +/** Hard maximum character length of a trimmed `idempotencyKey`. */ +export const FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH = 128; + +/** Fixed validation message used when unknown keys are supplied (never echoes caller keys). */ +export const FILE_FINDING_ERROR_UNKNOWN_KEYS = 'Unrecognized field(s) are not allowed.'; + +/** Fixed tool error message when one or more trial refs are unknown or Vault-only. */ +export const FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF = + 'One or more referenced trials are unavailable in the research-visible trial ledger.'; + +/** Fixed tool error message when an idempotency key is reused with a different payload. */ +export const FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT = + 'Idempotency key conflict: the provided idempotency key was already used with a different finding payload.'; + +/** Fixed tool error message when trial lookup, metadata generation, or append fails. */ +export const FILE_FINDING_ERROR_FILING_FAILED = + 'Failed to file finding due to a storage or lookup error.'; + +/** + * Append-only finding or dead-end record passed to {@link FindingWritePort.appendFinding}. + * + * Extends {@link FindingRecord} with `kind` and fixes `status` to `'pending_review'` + * so filed records are directly readable via `read_knowledge` while director approval + * happens out-of-band. + */ +export interface FiledFindingRecord extends FindingRecord { + readonly kind: FileFindingKind; + readonly status: FileFindingInitialStatus; +} + +/** Normalized caller-supplied fields compared for idempotency equality. */ +export type FiledFindingComparablePayload = Pick< + FiledFindingRecord, + 'kind' | 'title' | 'summary' | 'trialRefs' | 'evidenceRefs' +>; + +/** + * Discriminated outcome returned by {@link FindingWritePort.appendFinding}. + * + * - `'created'`: A new record was appended. + * - `'replayed'`: An existing record with the same `idempotencyKey` and + * identical normalized payload (`kind`, `title`, `summary`, `trialRefs`, + * `evidenceRefs`) was found; zero rows were appended and the stored `id` + * and `createdAt` are returned. + * - `'conflict'`: An existing record with the same `idempotencyKey` has a + * different normalized payload; zero rows were appended. + */ +export type AppendFindingResult = + | { + readonly status: 'created'; + readonly id: string; + readonly createdAt: string; + } + | { + readonly status: 'replayed'; + readonly id: string; + readonly createdAt: string; + } + | { + readonly status: 'conflict'; + }; + +/** + * Append-only write port injected into {@link createFileFindingTool}. + * + * Port contract: + * - Append-only by construction: exposes only {@link appendFinding} (no update + * or delete methods). + * - When `idempotencyKey` is supplied, the port must atomically compare and + * append within its configured key namespace: + * - Compare normalized `kind`, `title`, `summary`, `trialRefs`, and + * `evidenceRefs` (excluding server-generated `id`, `createdAt`, and `status`). + * - On an identical payload match, return `{ status: 'replayed', id, createdAt }` + * with the originally stored `id` and `createdAt` without appending a new row. + * - On a payload mismatch, return `{ status: 'conflict' }` and append zero rows. + * - When `idempotencyKey` is omitted (`undefined`), each call is independent and + * appends a new row, returning `{ status: 'created', id, createdAt }`. + */ +export interface FindingWritePort { + appendFinding( + record: FiledFindingRecord, + idempotencyKey?: string + ): Promise; +} + +/** + * Read-only trial visibility lookup port injected into {@link createFileFindingTool}. + * + * Bound at composition to the caller's research-visible `trial_ledger` and active + * Vault boundary. Accepts opaque string refs (for example, decimal `trialId` strings + * from `trial_ledger` receipts without numeric coercion) and returns `true` only when + * the trial exists and is research-visible. Unknown and Vault-only refs both return + * `false`. + */ +export interface TrialRefLookupPort { + hasResearchVisibleTrial(trialRef: string): Promise | boolean; +} + +/** Server-side injected configuration for {@link createFileFindingTool}. */ +export interface FileFindingToolOptions { + readonly port: FindingWritePort; + readonly trialLookup: TrialRefLookupPort; + readonly newId: () => string; + readonly now: () => Date | number; +} + +/** Structured JSON receipt serialized into the `file_finding` MCP text result. */ +export interface FileFindingResultPayload { + readonly id: string; + readonly createdAt: string; + readonly created: boolean; +} + +function compareStrings(a: string, b: string): number { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; +} + +function normalizeRefSet(refs: readonly string[]): readonly string[] { + const unique = Array.from(new Set(refs)); + unique.sort(compareStrings); + return unique; +} + +function areStringArraysEqual(a: readonly string[], b: readonly string[]): boolean { + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i += 1) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +} + +/** + * Compares two normalized filing payloads for idempotency equality across + * `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` (excluding + * server-generated `id`, `createdAt`, and `status`). + */ +export function areFiledFindingPayloadsEqual( + a: FiledFindingComparablePayload, + b: FiledFindingComparablePayload +): boolean { + return ( + a.kind === b.kind && + a.title === b.title && + a.summary === b.summary && + areStringArraysEqual(a.trialRefs, b.trialRefs) && + areStringArraysEqual(a.evidenceRefs, b.evidenceRefs) + ); +} + +const refStringSchema = z.string().trim().min(1).max(FILE_FINDING_MAX_REF_LENGTH); + +/** + * Strict Zod input schema for the `file_finding` MCP tool. + * + * Intentionally omits server-controlled fields (`id`, `status`, `createdAt`) and + * Vault/holdout fields (`scope`, `vault_evaluation_only`, `vaultCutoffTs`). + * `.strict(FILE_FINDING_ERROR_UNKNOWN_KEYS)` rejects any unknown keys with a fixed + * message so caller-supplied key names are never echoed. + * + * `title` and `summary` must describe research-visible evidence only; `evidenceRefs` + * are opaque snapshot identifiers that the tool stores without dereferencing. + */ +export const fileFindingInputSchema = z + .object({ + kind: z + .enum(FILE_FINDING_KINDS, { + errorMap: () => ({ message: "Expected 'finding' or 'dead_end'." }), + }) + .describe("Filing classification: 'finding' or 'dead_end'."), + title: z + .string() + .trim() + .min(1) + .max(FILE_FINDING_MAX_TITLE_LENGTH) + .describe( + `Short title describing research-visible evidence (trimmed, 1–${FILE_FINDING_MAX_TITLE_LENGTH} characters).` + ), + summary: z + .string() + .trim() + .min(1) + .max(FILE_FINDING_MAX_SUMMARY_LENGTH) + .describe( + `Concise summary of research-visible evidence only; never include Vault holdout observations (trimmed, 1–${FILE_FINDING_MAX_SUMMARY_LENGTH} characters).` + ), + trialRefs: z + .array(refStringSchema) + .min(1) + .max(FILE_FINDING_MAX_TRIAL_REFS) + .transform(normalizeRefSet) + .describe( + `Opaque research-visible trial_ledger references (1–${FILE_FINDING_MAX_TRIAL_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; deduplicated case-sensitively and sorted).` + ), + evidenceRefs: z + .array(refStringSchema) + .max(FILE_FINDING_MAX_EVIDENCE_REFS) + .default([]) + .transform(normalizeRefSet) + .describe( + `Optional opaque snapshot or artifact identifiers never dereferenced by the tool (0–${FILE_FINDING_MAX_EVIDENCE_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; defaults to empty list, deduplicated case-sensitively and sorted).` + ), + idempotencyKey: z + .string() + .trim() + .min(1) + .max(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH) + .optional() + .describe( + `Optional retry idempotency key (trimmed, 1–${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH} characters).` + ), + }) + .strict(FILE_FINDING_ERROR_UNKNOWN_KEYS); + +export type FileFindingInput = z.infer; + +function toolError(message: string): McpToolCallResult { + return { + content: [{ type: 'text', text: message }], + isError: true, + }; +} + +function validateNonEmptyString(value: unknown): string | null { + if (typeof value !== 'string' || value.trim().length === 0) { + return null; + } + return value; +} + +function formatUtcIsoTimestamp(raw: Date | number): string | null { + const epochMs = raw instanceof Date ? raw.getTime() : raw; + if ( + typeof epochMs !== 'number' || + !Number.isFinite(epochMs) || + Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS + ) { + return null; + } + return new Date(epochMs).toISOString(); +} + +function validateFactoryOptions(options: FileFindingToolOptions): FileFindingToolOptions { + if (typeof options !== 'object' || options === null) { + throw new Error('Invalid `options`: expected a FileFindingToolOptions object.'); + } + + if ( + typeof options.port !== 'object' || + options.port === null || + typeof options.port.appendFinding !== 'function' + ) { + throw new Error( + 'Invalid `port`: expected a FindingWritePort implementing `appendFinding`.' + ); + } + + if ( + typeof options.trialLookup !== 'object' || + options.trialLookup === null || + typeof options.trialLookup.hasResearchVisibleTrial !== 'function' + ) { + throw new Error( + 'Invalid `trialLookup`: expected a TrialRefLookupPort implementing `hasResearchVisibleTrial`.' + ); + } + + if (typeof options.newId !== 'function') { + throw new Error('Invalid `newId`: expected a function returning a non-empty finding ID.'); + } + + if (typeof options.now !== 'function') { + throw new Error('Invalid `now`: expected a clock function returning a Date or epoch ms.'); + } + + return options; +} + +/** + * Creates the append-only `file_finding` MCP tool backed by an injected + * {@link FindingWritePort} and read-only {@link TrialRefLookupPort}. + * + * Verifies every unique `trialRef` against the research-visible trial ledger + * before generating server-controlled metadata (`id`, `createdAt`, + * `status: 'pending_review'`) or calling `appendFinding`. Returns only the + * explicitly projected `{ id, createdAt, created }` receipt on success and fixed + * sanitized `isError` messages on failure. + */ +export function createFileFindingTool(options: FileFindingToolOptions): McpToolEntry { + const validated = validateFactoryOptions(options); + const { port, trialLookup, newId, now } = validated; + + return defineMcpTool({ + name: 'file_finding', + description: + 'File an append-only empirical finding or dead end linked to research-visible trial ledger references for director review.', + inputSchema: fileFindingInputSchema, + async handler(input: FileFindingInput): Promise { + // Verify every unique research-visible trial ref before generating metadata or writing. + for (let i = 0; i < input.trialRefs.length; i += 1) { + const trialRef = input.trialRefs[i] as string; + let visible: unknown; + try { + visible = await trialLookup.hasResearchVisibleTrial(trialRef); + } catch { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + if (typeof visible !== 'boolean') { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + if (!visible) { + return toolError(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + } + } + + let id: string | null; + let createdAt: string | null; + try { + id = validateNonEmptyString(newId()); + createdAt = formatUtcIsoTimestamp(now()); + } catch { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + if (id === null || createdAt === null) { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + const record: FiledFindingRecord = { + id, + kind: input.kind, + title: input.title, + status: FILE_FINDING_INITIAL_STATUS, + createdAt, + summary: input.summary, + trialRefs: [...input.trialRefs], + evidenceRefs: [...input.evidenceRefs], + }; + + let outcome: AppendFindingResult; + try { + outcome = await port.appendFinding(record, input.idempotencyKey); + } catch { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + if (typeof outcome !== 'object' || outcome === null) { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + if (outcome.status === 'conflict') { + return toolError(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); + } + + if (outcome.status !== 'created' && outcome.status !== 'replayed') { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + const receiptId = validateNonEmptyString(outcome.id); + const receiptCreatedAt = validateNonEmptyString(outcome.createdAt); + if (receiptId === null || receiptCreatedAt === null) { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + const payload: FileFindingResultPayload = { + id: receiptId, + createdAt: receiptCreatedAt, + created: outcome.status === 'created', + }; + + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + }, + }); +} diff --git a/libs/research/test/mcp-file-finding.test.ts b/libs/research/test/mcp-file-finding.test.ts new file mode 100644 index 00000000..ea47b644 --- /dev/null +++ b/libs/research/test/mcp-file-finding.test.ts @@ -0,0 +1,1100 @@ +import { describe, expect, test } from 'bun:test'; +import * as rootResearchExports from '../src/index'; +import { + type AppendFindingResult, + FILE_FINDING_ERROR_FILING_FAILED, + FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + FILE_FINDING_ERROR_UNKNOWN_KEYS, + FILE_FINDING_INITIAL_STATUS, + FILE_FINDING_KINDS, + FILE_FINDING_MAX_EVIDENCE_REFS, + FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, + FILE_FINDING_MAX_REF_LENGTH, + FILE_FINDING_MAX_SUMMARY_LENGTH, + FILE_FINDING_MAX_TITLE_LENGTH, + FILE_FINDING_MAX_TRIAL_REFS, + type FileFindingResultPayload, + type FiledFindingRecord, + type FindingQuery, + type FindingRecord, + type FindingWritePort, + type KnowledgePort, + type ReadKnowledgeResultPayload, + type TrialRefLookupPort, + areFiledFindingPayloadsEqual, + createFileFindingTool, + createMcpServer, + createReadKnowledgeTool, + fileFindingInputSchema, +} from '../src/mcp/index'; + +interface SharedFindingsFakeOptions { + readonly failNextAppendError?: unknown; + readonly alwaysAppendError?: unknown; + readonly delayFirstAppendMs?: number; + readonly attachExtraReceiptField?: boolean; +} + +interface SharedFindingsFake { + readonly stored: FiledFindingRecord[]; + readonly appendCalls: { + readonly record: FiledFindingRecord; + readonly idempotencyKey?: string; + }[]; + readonly writePort: FindingWritePort; + readonly knowledgePort: KnowledgePort; + readonly invokedWriteMethods: string[]; +} + +function createSharedFindingsFake(options?: SharedFindingsFakeOptions): SharedFindingsFake { + const stored: FiledFindingRecord[] = []; + const byIdempotencyKey = new Map(); + const appendCalls: { readonly record: FiledFindingRecord; readonly idempotencyKey?: string }[] = + []; + const invokedWriteMethods: string[] = []; + + let failOnceError: unknown = options?.failNextAppendError; + let firstCallSeen = false; + + const rawWritePort: FindingWritePort = { + async appendFinding( + record: FiledFindingRecord, + idempotencyKey?: string + ): Promise { + appendCalls.push({ record, idempotencyKey }); + + if (options?.alwaysAppendError !== undefined) { + throw options.alwaysAppendError; + } + + if (failOnceError !== undefined) { + const err = failOnceError; + failOnceError = undefined; + throw err; + } + + // Atomic compare-and-append before any async yield so concurrent calls with + // the same idempotencyKey cannot both insert. + let outcome: AppendFindingResult; + if (idempotencyKey !== undefined) { + const existing = byIdempotencyKey.get(idempotencyKey); + if (existing !== undefined) { + if (areFiledFindingPayloadsEqual(existing, record)) { + outcome = { + status: 'replayed', + id: existing.id, + createdAt: existing.createdAt, + }; + } else { + outcome = { status: 'conflict' }; + } + } else { + const copy: FiledFindingRecord = { + ...record, + trialRefs: [...record.trialRefs], + evidenceRefs: [...record.evidenceRefs], + }; + stored.push(copy); + byIdempotencyKey.set(idempotencyKey, copy); + outcome = { + status: 'created', + id: copy.id, + createdAt: copy.createdAt, + }; + } + } else { + const copy: FiledFindingRecord = { + ...record, + trialRefs: [...record.trialRefs], + evidenceRefs: [...record.evidenceRefs], + }; + stored.push(copy); + outcome = { + status: 'created', + id: copy.id, + createdAt: copy.createdAt, + }; + } + + if (!firstCallSeen && options?.delayFirstAppendMs !== undefined) { + firstCallSeen = true; + await new Promise(resolve => setTimeout(resolve, options.delayFirstAppendMs)); + } + + if (options?.attachExtraReceiptField === true && outcome.status !== 'conflict') { + return { + ...outcome, + internalDsn: 'postgres://leaked:pass@127.0.0.1:5432/trading_bot', + } as unknown as AppendFindingResult; + } + + return outcome; + }, + }; + + const writePort = new Proxy(rawWritePort, { + get(target, prop, receiver) { + const value: unknown = Reflect.get(target, prop, receiver); + if (typeof value === 'function' && typeof prop === 'string') { + return (...args: unknown[]) => { + invokedWriteMethods.push(prop); + return (value as (...a: unknown[]) => unknown).apply(target, args); + }; + } + return value; + }, + }); + + const knowledgePort: KnowledgePort = { + async listLibraryCards() { + return []; + }, + async listFindings(q: FindingQuery): Promise { + return stored.filter(item => { + if (q.id !== undefined && item.id !== q.id) { + return false; + } + if (q.query !== undefined) { + const needle = q.query.toLowerCase(); + return ( + item.title.toLowerCase().includes(needle) || item.summary.toLowerCase().includes(needle) + ); + } + return true; + }); + }, + async listProviderCaveats() { + return []; + }, + }; + + return { + stored, + appendCalls, + writePort, + knowledgePort, + invokedWriteMethods, + }; +} + +interface FakeTrialLookup { + readonly queriedRefs: string[]; + readonly port: TrialRefLookupPort; +} + +function createFakeTrialLookup(options?: { + readonly researchVisibleRefs?: readonly string[]; + readonly vaultOnlyRefs?: readonly string[]; + readonly throwError?: unknown; +}): FakeTrialLookup { + const visibleSet = new Set( + options?.researchVisibleRefs ?? ['trial-101', 'trial-102', '9007199254740993123'] + ); + const vaultOnlySet = new Set(options?.vaultOnlyRefs ?? ['trial-vault-999']); + const queriedRefs: string[] = []; + + const port: TrialRefLookupPort = { + async hasResearchVisibleTrial(trialRef: string): Promise { + queriedRefs.push(trialRef); + if (options?.throwError !== undefined) { + throw options.throwError; + } + if (vaultOnlySet.has(trialRef)) { + return false; + } + return visibleSet.has(trialRef); + }, + }; + + return { queriedRefs, port }; +} + +function createFixedClock(startIso = '2025-03-01T12:00:00.000Z', stepMs = 60_000) { + let current = Date.parse(startIso); + let calls = 0; + return { + get calls() { + return calls; + }, + now: () => { + calls += 1; + const value = current; + current += stepMs; + return value; + }, + }; +} + +function createFixedIdGenerator(prefix = 'find') { + let counter = 0; + return { + get calls() { + return counter; + }, + newId: () => { + counter += 1; + return `${prefix}-${String(counter).padStart(4, '0')}`; + }, + }; +} + +async function callTool( + server: ReturnType, + toolName: string, + args: Record, + id: string | number = 'req-1' +): Promise<{ + readonly isError: boolean; + readonly text: string; + readonly payload: TPayload | null; +}> { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'tools/call', + params: { + name: toolName, + arguments: args, + }, + }) + ); + + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw as string) as { + error?: unknown; + result: { + isError?: boolean; + content: { type: string; text: string }[]; + }; + }; + expect(parsed.error).toBeUndefined(); + const isError = parsed.result.isError === true; + const text = parsed.result.content[0]?.text ?? ''; + + return { + isError, + text, + payload: isError ? null : (JSON.parse(text) as TPayload), + }; +} + +describe('MCP file_finding tool', () => { + test('files both finding and dead_end with fixed server metadata, normalization, and explicit receipt projection', async () => { + const fake = createSharedFindingsFake({ attachExtraReceiptField: true }); + const trialLookup = createFakeTrialLookup(); + const clock = createFixedClock('2025-03-01T10:00:00.000Z', 60_000); + const idGen = createFixedIdGenerator('finding'); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: idGen.newId, + now: clock.now, + }), + ], + }); + + const findingRes = await callTool(server, 'file_finding', { + kind: 'finding', + title: ' Post-earnings drift decays after day 3 ', + summary: ' Cross-sectional CAR flattens after session +3 across 2015-2024. ', + trialRefs: [' trial-102 ', '9007199254740993123', 'trial-102', 'trial-101'], + evidenceRefs: [' snap-b ', 'snap-a', 'snap-b', 'Snap-A'], + }); + + expect(findingRes.isError).toBe(false); + expect(findingRes.payload).toEqual({ + id: 'finding-0001', + createdAt: '2025-03-01T10:00:00.000Z', + created: true, + }); + expect(Object.keys(findingRes.payload as unknown as Record).sort()).toEqual([ + 'created', + 'createdAt', + 'id', + ]); + + expect(fake.stored[0]).toEqual({ + id: 'finding-0001', + kind: 'finding', + title: 'Post-earnings drift decays after day 3', + status: FILE_FINDING_INITIAL_STATUS, + createdAt: '2025-03-01T10:00:00.000Z', + summary: 'Cross-sectional CAR flattens after session +3 across 2015-2024.', + trialRefs: ['9007199254740993123', 'trial-101', 'trial-102'], + evidenceRefs: ['Snap-A', 'snap-a', 'snap-b'], + }); + + const deadEndRes = await callTool(server, 'file_finding', { + kind: 'dead_end', + title: 'Short-interest 1d reversal', + summary: 'No net edge after realistic borrow and spread costs.', + trialRefs: ['trial-101'], + }); + + expect(deadEndRes.isError).toBe(false); + expect(deadEndRes.payload).toEqual({ + id: 'finding-0002', + createdAt: '2025-03-01T10:01:00.000Z', + created: true, + }); + expect(fake.stored[1]).toEqual({ + id: 'finding-0002', + kind: 'dead_end', + title: 'Short-interest 1d reversal', + status: 'pending_review', + createdAt: '2025-03-01T10:01:00.000Z', + summary: 'No net edge after realistic borrow and spread costs.', + trialRefs: ['trial-101'], + evidenceRefs: [], + }); + expect(fake.invokedWriteMethods).toEqual(['appendFinding', 'appendFinding']); + }); + + test('rejects invalid inputs, blank or over-length fields, raw array limits, unknown fields, and metadata overrides with zero writes', async () => { + const fake = createSharedFindingsFake(); + const trialLookup = createFakeTrialLookup(); + const clock = createFixedClock(); + const idGen = createFixedIdGenerator(); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: idGen.newId, + now: clock.now, + }), + ], + }); + + const validBase = { + kind: 'finding', + title: 'Valid title', + summary: 'Valid research-visible summary', + trialRefs: ['trial-101'], + }; + + const invalidCases: readonly { + readonly label: string; + readonly args: Record; + readonly forbiddenSubstring?: string; + }[] = [ + { label: 'missing trialRefs', args: { kind: 'finding', title: 'T', summary: 'S' } }, + { label: 'empty trialRefs', args: { ...validBase, trialRefs: [] } }, + { label: 'blank trialRef', args: { ...validBase, trialRefs: [' '] } }, + { label: 'blank evidenceRef', args: { ...validBase, evidenceRefs: [' '] } }, + { label: 'blank title', args: { ...validBase, title: ' ' } }, + { label: 'blank summary', args: { ...validBase, summary: '\t\n ' } }, + { label: 'blank idempotencyKey', args: { ...validBase, idempotencyKey: ' ' } }, + { + label: 'over-length title', + args: { ...validBase, title: 'a'.repeat(FILE_FINDING_MAX_TITLE_LENGTH + 1) }, + }, + { + label: 'over-length summary', + args: { ...validBase, summary: 's'.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH + 1) }, + }, + { + label: 'over-length trialRef', + args: { ...validBase, trialRefs: ['r'.repeat(FILE_FINDING_MAX_REF_LENGTH + 1)] }, + }, + { + label: 'over-length evidenceRef', + args: { ...validBase, evidenceRefs: ['e'.repeat(FILE_FINDING_MAX_REF_LENGTH + 1)] }, + }, + { + label: 'over-length idempotencyKey', + args: { + ...validBase, + idempotencyKey: 'k'.repeat(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH + 1), + }, + }, + { + label: 'raw trialRefs exceeds 32 even with duplicates', + args: { + ...validBase, + trialRefs: Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS + 1 }, () => 'trial-101'), + }, + }, + { + label: 'raw evidenceRefs exceeds 32 even with duplicates', + args: { + ...validBase, + evidenceRefs: Array.from( + { length: FILE_FINDING_MAX_EVIDENCE_REFS + 1 }, + () => 'snap-01' + ), + }, + }, + { + label: 'invalid kind does not echo caller value', + args: { ...validBase, kind: 'vault_secret_kind_sentinel' }, + forbiddenSubstring: 'vault_secret_kind_sentinel', + }, + { label: 'invalid title type', args: { ...validBase, title: 123 } }, + { label: 'invalid trialRefs type', args: { ...validBase, trialRefs: 'trial-101' } }, + { + label: 'caller-supplied id rejected', + args: { ...validBase, id: 'attacker-id' }, + forbiddenSubstring: 'attacker-id', + }, + { + label: 'caller-supplied status rejected', + args: { ...validBase, status: 'confirmed' }, + forbiddenSubstring: 'confirmed', + }, + { + label: 'caller-supplied createdAt rejected', + args: { ...validBase, createdAt: '2020-01-01T00:00:00.000Z' }, + forbiddenSubstring: '2020-01-01', + }, + { + label: 'holdout scope rejected without echoing key', + args: { ...validBase, scope: 'vault_evaluation_only' }, + forbiddenSubstring: 'scope', + }, + { + label: 'holdout vault_evaluation_only rejected without echoing key', + args: { ...validBase, vault_evaluation_only: true }, + forbiddenSubstring: 'vault_evaluation_only', + }, + { + label: 'holdout vaultCutoffTs rejected without echoing key', + args: { ...validBase, vaultCutoffTs: 1_700_000_000_000 }, + forbiddenSubstring: 'vaultCutoffTs', + }, + { + label: 'unknown-key sentinel rejected without echoing sentinel', + args: { ...validBase, vaultHoldoutKeySentinel_XYZ: 'secret-value' }, + forbiddenSubstring: 'vaultHoldoutKeySentinel_XYZ', + }, + ]; + + for (const testCase of invalidCases) { + const res = await callTool(server, 'file_finding', testCase.args); + expect(res.isError).toBe(true); + if (testCase.forbiddenSubstring !== undefined) { + expect(res.text).not.toContain(testCase.forbiddenSubstring); + } + if ( + testCase.label.includes('unknown-key') || + testCase.label.includes('holdout') || + testCase.label.includes('caller-supplied') + ) { + expect(res.text).toContain(FILE_FINDING_ERROR_UNKNOWN_KEYS); + } + } + + expect(fake.stored).toHaveLength(0); + expect(fake.appendCalls).toHaveLength(0); + expect(trialLookup.queriedRefs).toHaveLength(0); + expect(idGen.calls).toBe(0); + expect(clock.calls).toBe(0); + + // Raw 32 duplicate entries are accepted (bounds applied before dedup). + const maxRawRes = await callTool(server, 'file_finding', { + ...validBase, + trialRefs: Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS }, () => 'trial-101'), + evidenceRefs: Array.from({ length: FILE_FINDING_MAX_EVIDENCE_REFS }, () => 'snap-1'), + }); + expect(maxRawRes.isError).toBe(false); + expect(fake.stored).toHaveLength(1); + expect(fake.stored[0]?.trialRefs).toEqual(['trial-101']); + expect(fake.stored[0]?.evidenceRefs).toEqual(['snap-1']); + }); + + test('rejects unknown and Vault-only trial refs identically with zero writes and zero metadata generation', async () => { + const fake = createSharedFindingsFake(); + const trialLookup = createFakeTrialLookup({ + researchVisibleRefs: ['trial-101'], + vaultOnlyRefs: ['trial-vault-only-secret'], + }); + const clock = createFixedClock(); + const idGen = createFixedIdGenerator(); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: idGen.newId, + now: clock.now, + }), + ], + }); + + const unknownRes = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Mixed valid and unknown ref', + summary: 'Should fail before writing.', + trialRefs: ['trial-101', 'trial-unknown-secret-ref'], + }); + + const vaultRes = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Mixed valid and Vault-only ref', + summary: 'Should fail identically to unknown ref.', + trialRefs: ['trial-101', 'trial-vault-only-secret'], + }); + + expect(unknownRes.isError).toBe(true); + expect(vaultRes.isError).toBe(true); + expect(unknownRes.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(vaultRes.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(unknownRes.text).not.toContain('trial-unknown-secret-ref'); + expect(vaultRes.text).not.toContain('trial-vault-only-secret'); + expect(fake.stored).toHaveLength(0); + expect(fake.appendCalls).toHaveLength(0); + expect(idGen.calls).toBe(0); + expect(clock.calls).toBe(0); + }); + + test('sanitizes lookup and append exceptions so DSNs and stack markers never leak', async () => { + const fakeDsn = 'postgres://writer:supersecret@10.0.0.51:5432/trading_bot'; + const stackMarker = 'at internalPgPoolQuery (/srv/stock-bot/secret-adapter.ts:91:13)'; + + const lookupErr = new Error(`Lookup failed on ${fakeDsn}\n ${stackMarker}`); + lookupErr.name = 'PgConnectionError'; + + const lookupFake = createSharedFindingsFake(); + const failingLookup = createFakeTrialLookup({ throwError: lookupErr }); + const lookupServer = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: lookupFake.writePort, + trialLookup: failingLookup.port, + newId: createFixedIdGenerator().newId, + now: createFixedClock().now, + }), + ], + }); + + const lookupRes = await callTool(lookupServer, 'file_finding', { + kind: 'finding', + title: 'Lookup failure test', + summary: 'Summary text', + trialRefs: ['trial-101'], + }); + expect(lookupRes.isError).toBe(true); + expect(lookupRes.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(lookupRes.text).not.toContain(fakeDsn); + expect(lookupRes.text).not.toContain(stackMarker); + expect(lookupRes.text).not.toContain('PgConnectionError'); + expect(lookupFake.appendCalls).toHaveLength(0); + + const appendErr = new Error(`INSERT failed on ${fakeDsn}\n ${stackMarker}`); + appendErr.name = 'DatabaseWriteError'; + const appendFake = createSharedFindingsFake({ alwaysAppendError: appendErr }); + const appendServer = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: appendFake.writePort, + trialLookup: createFakeTrialLookup().port, + newId: createFixedIdGenerator().newId, + now: createFixedClock().now, + }), + ], + }); + + const appendRes = await callTool(appendServer, 'file_finding', { + kind: 'finding', + title: 'Append failure test', + summary: 'Summary text', + trialRefs: ['trial-101'], + }); + expect(appendRes.isError).toBe(true); + expect(appendRes.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(appendRes.text).not.toContain(fakeDsn); + expect(appendRes.text).not.toContain(stackMarker); + expect(appendRes.text).not.toContain('DatabaseWriteError'); + }); + + test('enforces idempotency replays, per-field conflicts, concurrent retries across instances, post-failure retry, and independent unkeyed calls', async () => { + const fake = createSharedFindingsFake(); + const trialLookup = createFakeTrialLookup(); + const clock = createFixedClock('2025-03-01T14:00:00.000Z', 60_000); + const idGen = createFixedIdGenerator('idem'); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: idGen.newId, + now: clock.now, + }), + ], + }); + + const first = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Momentum crowding signal', + summary: 'Observed IC decay during high volatility regimes.', + trialRefs: ['trial-102', 'trial-101'], + idempotencyKey: ' key-001 ', + }); + expect(first.isError).toBe(false); + expect(first.payload).toEqual({ + id: 'idem-0001', + createdAt: '2025-03-01T14:00:00.000Z', + created: true, + }); + expect(fake.stored).toHaveLength(1); + + // Replay with whitespace, duplicate/reordered refs, and explicit empty evidenceRefs. + const replay = await callTool(server, 'file_finding', { + kind: 'finding', + title: ' Momentum crowding signal ', + summary: ' Observed IC decay during high volatility regimes. ', + trialRefs: ['trial-101', ' trial-102 ', 'trial-101'], + evidenceRefs: [], + idempotencyKey: 'key-001', + }); + expect(replay.isError).toBe(false); + expect(replay.payload).toEqual({ + id: 'idem-0001', + createdAt: '2025-03-01T14:00:00.000Z', + created: false, + }); + expect(fake.stored).toHaveLength(1); + + // Changing each normalized payload field in turn causes a conflict with zero extra rows. + const conflictPayloads: readonly Record[] = [ + { + kind: 'dead_end', + title: 'Momentum crowding signal', + summary: 'Observed IC decay during high volatility regimes.', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: [], + idempotencyKey: 'key-001', + }, + { + kind: 'finding', + title: 'Different title', + summary: 'Observed IC decay during high volatility regimes.', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: [], + idempotencyKey: 'key-001', + }, + { + kind: 'finding', + title: 'Momentum crowding signal', + summary: 'Different summary', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: [], + idempotencyKey: 'key-001', + }, + { + kind: 'finding', + title: 'Momentum crowding signal', + summary: 'Observed IC decay during high volatility regimes.', + trialRefs: ['trial-101'], + evidenceRefs: [], + idempotencyKey: 'key-001', + }, + { + kind: 'finding', + title: 'Momentum crowding signal', + summary: 'Observed IC decay during high volatility regimes.', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: ['snap-extra'], + idempotencyKey: 'key-001', + }, + ]; + + for (const conflictArgs of conflictPayloads) { + const res = await callTool(server, 'file_finding', conflictArgs); + expect(res.isError).toBe(true); + expect(res.text).toBe(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); + } + expect(fake.stored).toHaveLength(1); + + // Concurrent same-key calls across two separate tool instances sharing one port. + const concurrentFake = createSharedFindingsFake({ delayFirstAppendMs: 10 }); + const toolA = createFileFindingTool({ + port: concurrentFake.writePort, + trialLookup: trialLookup.port, + newId: createFixedIdGenerator('instA').newId, + now: createFixedClock('2025-03-02T00:00:00.000Z').now, + }); + const toolB = createFileFindingTool({ + port: concurrentFake.writePort, + trialLookup: trialLookup.port, + newId: createFixedIdGenerator('instB').newId, + now: createFixedClock('2025-03-02T05:00:00.000Z').now, + }); + const concurrentArgs = { + kind: 'finding', + title: 'Concurrent filing', + summary: 'Submitted concurrently by two retries.', + trialRefs: ['trial-101'], + idempotencyKey: 'concurrent-key', + }; + + const [resA, resB] = await Promise.all([ + toolA.execute(concurrentArgs), + toolB.execute(concurrentArgs), + ]); + expect(resA.isError).toBeUndefined(); + expect(resB.isError).toBeUndefined(); + const payloadA = JSON.parse(resA.content[0]?.text ?? '') as FileFindingResultPayload; + const payloadB = JSON.parse(resB.content[0]?.text ?? '') as FileFindingResultPayload; + expect(concurrentFake.stored).toHaveLength(1); + expect(payloadA.id).toBe(payloadB.id); + expect(payloadA.createdAt).toBe(payloadB.createdAt); + expect([payloadA.created, payloadB.created].sort()).toEqual([false, true]); + + // Retry after an injected pre-commit failure succeeds cleanly. + const retryFake = createSharedFindingsFake({ + failNextAppendError: new Error('transient pre-commit timeout'), + }); + const retryServer = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: retryFake.writePort, + trialLookup: trialLookup.port, + newId: createFixedIdGenerator('retry').newId, + now: createFixedClock('2025-03-03T08:00:00.000Z').now, + }), + ], + }); + + const failedAttempt = await callTool(retryServer, 'file_finding', { + kind: 'dead_end', + title: 'Retry after failure', + summary: 'First attempt fails before commit.', + trialRefs: ['trial-101'], + idempotencyKey: 'retry-key', + }); + expect(failedAttempt.isError).toBe(true); + expect(failedAttempt.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(retryFake.stored).toHaveLength(0); + + const retryAttempt = await callTool(retryServer, 'file_finding', { + kind: 'dead_end', + title: 'Retry after failure', + summary: 'First attempt fails before commit.', + trialRefs: ['trial-101'], + idempotencyKey: 'retry-key', + }); + expect(retryAttempt.isError).toBe(false); + expect(retryAttempt.payload).toEqual({ + id: 'retry-0002', + createdAt: '2025-03-03T08:01:00.000Z', + created: true, + }); + expect(retryFake.stored).toHaveLength(1); + + // Unkeyed calls with identical payloads are independent. + const unkeyed1 = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Unkeyed entry', + summary: 'Independent unkeyed filing.', + trialRefs: ['trial-101'], + }); + const unkeyed2 = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Unkeyed entry', + summary: 'Independent unkeyed filing.', + trialRefs: ['trial-101'], + }); + expect(unkeyed1.isError).toBe(false); + expect(unkeyed2.isError).toBe(false); + expect(unkeyed1.payload?.created).toBe(true); + expect(unkeyed2.payload?.created).toBe(true); + expect(unkeyed1.payload?.id).not.toBe(unkeyed2.payload?.id); + expect(fake.stored).toHaveLength(3); + }); + + test('advertises strict schema via tools/list and round-trips filed records through read_knowledge', async () => { + const fake = createSharedFindingsFake(); + const trialLookup = createFakeTrialLookup(); + const clock = createFixedClock('2025-03-04T09:30:00.000Z', 120_000); + const idGen = createFixedIdGenerator('kb'); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: idGen.newId, + now: clock.now, + }), + createReadKnowledgeTool({ + port: fake.knowledgePort, + }), + ], + }); + + const listRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'list-1', + method: 'tools/list', + }) + ); + expect(listRaw).not.toBeNull(); + const listParsed = JSON.parse(listRaw as string) as { + result: { + tools: { + name: string; + description: string; + inputSchema: { + type: string; + properties: Record>; + required?: string[]; + additionalProperties: boolean; + }; + }[]; + }; + }; + + expect(listParsed.result.tools.map(t => t.name)).toEqual(['file_finding', 'read_knowledge']); + const tool = listParsed.result.tools.find(t => t.name === 'file_finding'); + expect(tool).toBeDefined(); + expect(tool?.inputSchema.type).toBe('object'); + expect(tool?.inputSchema.additionalProperties).toBe(false); + expect(tool?.inputSchema.required).toEqual(['kind', 'title', 'summary', 'trialRefs']); + expect(tool?.inputSchema.properties.kind).toMatchObject({ + type: 'string', + enum: [...FILE_FINDING_KINDS], + }); + expect(tool?.inputSchema.properties.title).toMatchObject({ + type: 'string', + minLength: 1, + maxLength: FILE_FINDING_MAX_TITLE_LENGTH, + }); + expect(tool?.inputSchema.properties.summary).toMatchObject({ + type: 'string', + minLength: 1, + maxLength: FILE_FINDING_MAX_SUMMARY_LENGTH, + }); + expect(tool?.inputSchema.properties.trialRefs).toMatchObject({ + type: 'array', + minItems: 1, + maxItems: FILE_FINDING_MAX_TRIAL_REFS, + items: { type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_REF_LENGTH }, + }); + expect(tool?.inputSchema.properties.evidenceRefs).toMatchObject({ + type: 'array', + maxItems: FILE_FINDING_MAX_EVIDENCE_REFS, + default: [], + items: { type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_REF_LENGTH }, + }); + expect(tool?.inputSchema.properties.idempotencyKey).toMatchObject({ + type: 'string', + minLength: 1, + maxLength: FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, + }); + expect(tool?.inputSchema.properties.id).toBeUndefined(); + expect(tool?.inputSchema.properties.status).toBeUndefined(); + expect(tool?.inputSchema.properties.createdAt).toBeUndefined(); + expect(tool?.inputSchema.properties.scope).toBeUndefined(); + expect(tool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); + expect(tool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); + + // File both kinds via tools/call and read each back through read_knowledge. + const filedFinding = await callTool( + server, + 'file_finding', + { + kind: 'finding', + title: ' Event-study drift after SEC 8-K ', + summary: ' CAR peaks on session +2 and persists through +5. ', + trialRefs: ['trial-102', 'trial-101', 'trial-102'], + evidenceRefs: ['ev-html-2', 'ev-html-1'], + }, + 'call-f1' + ); + expect(filedFinding.isError).toBe(false); + const findingId = filedFinding.payload?.id as string; + + const filedDeadEnd = await callTool( + server, + 'file_finding', + { + kind: 'dead_end', + title: 'Intraday gap fade on microcaps', + summary: 'Edge disappears once 15 bps slippage is modeled.', + trialRefs: ['9007199254740993123'], + }, + 'call-f2' + ); + expect(filedDeadEnd.isError).toBe(false); + const deadEndId = filedDeadEnd.payload?.id as string; + + const readFinding = await callTool( + server, + 'read_knowledge', + { source: 'findings', id: findingId }, + 'call-r1' + ); + expect(readFinding.isError).toBe(false); + expect(readFinding.payload).toEqual({ + rowCount: 1, + sources: { library: 0, findings: 1, provider_caveats: 0 }, + rows: [ + { + source: 'findings', + id: findingId, + title: 'Event-study drift after SEC 8-K', + status: 'pending_review', + createdAt: '2025-03-04T09:30:00.000Z', + summary: 'CAR peaks on session +2 and persists through +5.', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: ['ev-html-1', 'ev-html-2'], + truncated: false, + }, + ], + }); + expect(fake.stored.find(r => r.id === findingId)?.kind).toBe('finding'); + + const readDeadEnd = await callTool( + server, + 'read_knowledge', + { source: 'findings', id: deadEndId }, + 'call-r2' + ); + expect(readDeadEnd.isError).toBe(false); + expect(readDeadEnd.payload).toEqual({ + rowCount: 1, + sources: { library: 0, findings: 1, provider_caveats: 0 }, + rows: [ + { + source: 'findings', + id: deadEndId, + title: 'Intraday gap fade on microcaps', + status: 'pending_review', + createdAt: '2025-03-04T09:32:00.000Z', + summary: 'Edge disappears once 15 bps slippage is modeled.', + trialRefs: ['9007199254740993123'], + evidenceRefs: [], + truncated: false, + }, + ], + }); + expect(fake.stored.find(r => r.id === deadEndId)?.kind).toBe('dead_end'); + }); + + test('produces bit-identical receipts, stored records, and read-backs across deterministic replays', async () => { + async function runReplay() { + const fake = createSharedFindingsFake(); + const trialLookup = createFakeTrialLookup(); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: createFixedIdGenerator('rep').newId, + now: createFixedClock('2025-03-05T00:00:00.000Z', 30_000).now, + }), + createReadKnowledgeTool({ port: fake.knowledgePort }), + ], + }); + + const r1 = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Replay finding', + summary: 'Deterministic summary.', + trialRefs: ['trial-102', 'trial-101'], + evidenceRefs: ['ev-b', 'ev-a'], + idempotencyKey: 'rep-key-1', + }); + const r2 = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Replay finding', + summary: 'Deterministic summary.', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: ['ev-a', 'ev-b'], + idempotencyKey: 'rep-key-1', + }); + const r3 = await callTool(server, 'read_knowledge', { + source: 'findings', + }); + return { + receipts: [r1.payload, r2.payload], + stored: fake.stored, + knowledge: r3.payload, + }; + } + + const firstRun = await runReplay(); + const secondRun = await runReplay(); + expect(secondRun).toEqual(firstRun); + }); + + test('validates factory options eagerly and keeps MCP symbols out of browser-safe root export', () => { + const validPort = createSharedFindingsFake().writePort; + const validLookup = createFakeTrialLookup().port; + const validNewId = () => 'id-1'; + const validNow = () => Date.UTC(2025, 2, 1); + + expect(() => createFileFindingTool(null as never)).toThrow(/options/i); + expect(() => + createFileFindingTool({ + port: {} as never, + trialLookup: validLookup, + newId: validNewId, + now: validNow, + }) + ).toThrow(/port/i); + expect(() => + createFileFindingTool({ + port: validPort, + trialLookup: {} as never, + newId: validNewId, + now: validNow, + }) + ).toThrow(/trialLookup/i); + expect(() => + createFileFindingTool({ + port: validPort, + trialLookup: validLookup, + newId: 'not-a-fn' as never, + now: validNow, + }) + ).toThrow(/newId/i); + expect(() => + createFileFindingTool({ + port: validPort, + trialLookup: validLookup, + newId: validNewId, + now: 'not-a-fn' as never, + }) + ).toThrow(/now/i); + + expect( + fileFindingInputSchema.safeParse({ + kind: 'finding', + title: 'Schema export sanity check', + summary: 'Direct schema parse works.', + trialRefs: ['trial-101'], + }).success + ).toBe(true); + + expect(Object.keys(rootResearchExports)).not.toContain('createFileFindingTool'); + }); +}); From f46fb87c74df3072346b0d56223d0a15585fce15 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:39:50 -0500 Subject: [PATCH 18/36] T-138: tests --- .../research/test/mcp-file-finding-qa.test.ts | 469 ++++++++++++++++++ 1 file changed, 469 insertions(+) create mode 100644 libs/research/test/mcp-file-finding-qa.test.ts diff --git a/libs/research/test/mcp-file-finding-qa.test.ts b/libs/research/test/mcp-file-finding-qa.test.ts new file mode 100644 index 00000000..397637ba --- /dev/null +++ b/libs/research/test/mcp-file-finding-qa.test.ts @@ -0,0 +1,469 @@ +import { describe, expect, test } from 'bun:test'; +import { + type AppendFindingResult, + FILE_FINDING_ERROR_FILING_FAILED, + FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + FILE_FINDING_MAX_EVIDENCE_REFS, + FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, + FILE_FINDING_MAX_REF_LENGTH, + FILE_FINDING_MAX_SUMMARY_LENGTH, + FILE_FINDING_MAX_TITLE_LENGTH, + FILE_FINDING_MAX_TRIAL_REFS, + type FileFindingResultPayload, + type FiledFindingRecord, + type FindingWritePort, + type TrialRefLookupPort, + areFiledFindingPayloadsEqual, + createFileFindingTool, +} from '../src/mcp/index'; + +// Compile-time guard: the write port exposes exactly one append method (no update/delete). +type Equal = (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + ? true + : false; +const writePortKeysAreAppendOnly: Equal = true; + +const FIXED_EPOCH_MS = Date.UTC(2025, 5, 2, 15, 30, 0); + +interface RecordingPort { + readonly calls: { record: FiledFindingRecord; idempotencyKey: string | undefined }[]; + readonly port: FindingWritePort; +} + +function recordingPort( + respond: (record: FiledFindingRecord, key: string | undefined) => unknown +): RecordingPort { + const calls: RecordingPort['calls'] = []; + return { + calls, + port: { + async appendFinding(record, idempotencyKey) { + calls.push({ record, idempotencyKey }); + return respond(record, idempotencyKey) as AppendFindingResult; + }, + }, + }; +} + +function createdEcho(record: FiledFindingRecord): AppendFindingResult { + return { status: 'created', id: record.id, createdAt: record.createdAt }; +} + +function lookupFrom( + answer: (ref: string) => unknown +): { readonly queried: string[]; readonly port: TrialRefLookupPort } { + const queried: string[] = []; + return { + queried, + port: { + hasResearchVisibleTrial(ref: string) { + queried.push(ref); + return answer(ref) as boolean; + }, + }, + }; +} + +function counter(fn: () => T): { calls: number; fn: () => T } { + const state = { + calls: 0, + fn: () => { + state.calls += 1; + return fn(); + }, + }; + return state; +} + +const validArgs = { + kind: 'finding', + title: 'QA filing', + summary: 'Research-visible summary.', + trialRefs: ['trial-1'], +}; + +function parseReceipt(text: string | undefined): FileFindingResultPayload { + return JSON.parse(text ?? '') as FileFindingResultPayload; +} + +describe('MCP file_finding QA edge cases', () => { + test('write port type exposes only appendFinding', () => { + expect(writePortKeysAreAppendOnly).toBe(true); + }); + + test('deduplicates trial refs before lookup, verifies in sorted order, and short-circuits on the first unavailable ref', async () => { + const rec = recordingPort(createdEcho); + const lookup = lookupFrom(ref => ref !== 'trial-b'); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookup.port, + newId: () => 'id-1', + now: () => FIXED_EPOCH_MS, + }); + + const res = await tool.execute({ + ...validArgs, + trialRefs: ['trial-c', 'trial-a', 'trial-b', 'trial-a', 'trial-c'], + }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(lookup.queried).toEqual(['trial-a', 'trial-b']); + expect(rec.calls).toHaveLength(0); + }); + + test('accepts a synchronous boolean lookup and queries each unique ref exactly once on success', async () => { + const rec = recordingPort(createdEcho); + const lookup = lookupFrom(() => true); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookup.port, + newId: () => 'id-sync', + now: () => FIXED_EPOCH_MS, + }); + + const res = await tool.execute({ ...validArgs, trialRefs: ['t2', 't1', 't2', 't1'] }); + + expect(res.isError).toBeUndefined(); + expect(lookup.queried).toEqual(['t1', 't2']); + expect(rec.calls).toHaveLength(1); + expect(rec.calls[0]?.record.trialRefs).toEqual(['t1', 't2']); + }); + + test('treats non-boolean lookup answers as a filing failure with zero writes and no metadata generation', async () => { + for (const answer of [1, 'true', null, undefined, {}]) { + const rec = recordingPort(createdEcho); + const ids = counter(() => 'never'); + const clock = counter(() => FIXED_EPOCH_MS); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => answer).port, + newId: ids.fn, + now: clock.fn, + }); + + const res = await tool.execute(validArgs); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(rec.calls).toHaveLength(0); + expect(ids.calls).toBe(0); + expect(clock.calls).toBe(0); + } + }); + + test('rejects unusable generated ids and clock values with a fixed error and zero writes', async () => { + const badSources: readonly { + readonly label: string; + readonly newId: () => string; + readonly now: () => Date | number; + }[] = [ + { label: 'empty id', newId: () => '', now: () => FIXED_EPOCH_MS }, + { label: 'blank id', newId: () => ' ', now: () => FIXED_EPOCH_MS }, + { label: 'non-string id', newId: () => 42 as unknown as string, now: () => FIXED_EPOCH_MS }, + { + label: 'throwing id source', + newId: () => { + throw new Error('postgres://u:p@db/x id sequence exhausted'); + }, + now: () => FIXED_EPOCH_MS, + }, + { label: 'NaN clock', newId: () => 'id-1', now: () => Number.NaN }, + { label: 'infinite clock', newId: () => 'id-1', now: () => Number.POSITIVE_INFINITY }, + { label: 'invalid Date', newId: () => 'id-1', now: () => new Date('not-a-date') }, + { label: 'out-of-range epoch', newId: () => 'id-1', now: () => 9e15 }, + { label: 'string clock', newId: () => 'id-1', now: () => '2025-01-01' as unknown as number }, + { + label: 'throwing clock', + newId: () => 'id-1', + now: () => { + throw new Error('clock unavailable at /srv/secret.ts:1:1'); + }, + }, + ]; + + for (const source of badSources) { + const rec = recordingPort(createdEcho); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: source.newId, + now: source.now, + }); + + const res = await tool.execute(validArgs); + + expect({ label: source.label, isError: res.isError }).toEqual({ + label: source.label, + isError: true, + }); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(rec.calls).toHaveLength(0); + } + }); + + test('stores Date and epoch clock values as identical UTC ISO timestamps', async () => { + const fromDate = recordingPort(createdEcho); + const fromEpoch = recordingPort(createdEcho); + const lookup = lookupFrom(() => true).port; + + await createFileFindingTool({ + port: fromDate.port, + trialLookup: lookup, + newId: () => 'id-d', + now: () => new Date(FIXED_EPOCH_MS), + }).execute(validArgs); + await createFileFindingTool({ + port: fromEpoch.port, + trialLookup: lookup, + newId: () => 'id-e', + now: () => FIXED_EPOCH_MS, + }).execute(validArgs); + + expect(fromDate.calls[0]?.record.createdAt).toBe('2025-06-02T15:30:00.000Z'); + expect(fromEpoch.calls[0]?.record.createdAt).toBe('2025-06-02T15:30:00.000Z'); + }); + + test('passes the trimmed idempotency key to the port and undefined when omitted', async () => { + const rec = recordingPort(createdEcho); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-k', + now: () => FIXED_EPOCH_MS, + }); + + await tool.execute({ ...validArgs, idempotencyKey: '\t retry-key-7 \n' }); + await tool.execute(validArgs); + + expect(rec.calls.map(c => c.idempotencyKey)).toEqual(['retry-key-7', undefined]); + }); + + test('receipt reflects the port-stored id and timestamp on replay, not freshly generated metadata', async () => { + const rec = recordingPort(() => ({ + status: 'replayed', + id: 'stored-original', + createdAt: '2024-12-31T23:59:59.000Z', + })); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'fresh-id', + now: () => FIXED_EPOCH_MS, + }); + + const res = await tool.execute({ ...validArgs, idempotencyKey: 'k' }); + + expect(res.isError).toBeUndefined(); + expect(parseReceipt(res.content[0]?.text)).toEqual({ + id: 'stored-original', + createdAt: '2024-12-31T23:59:59.000Z', + created: false, + }); + }); + + test('maps malformed port outcomes to the fixed filing error and conflict to the fixed conflict error', async () => { + const malformed: readonly unknown[] = [ + null, + undefined, + 'created', + {}, + { status: 'updated', id: 'x', createdAt: 'y' }, + { status: 'created', id: '', createdAt: '2025-01-01T00:00:00.000Z' }, + { status: 'created', id: 'x' }, + { status: 'replayed', id: 7, createdAt: '2025-01-01T00:00:00.000Z' }, + ]; + + for (const outcome of malformed) { + const tool = createFileFindingTool({ + port: recordingPort(() => outcome).port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-m', + now: () => FIXED_EPOCH_MS, + }); + const res = await tool.execute(validArgs); + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + } + + const conflictTool = createFileFindingTool({ + port: recordingPort(() => ({ status: 'conflict' })).port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-c', + now: () => FIXED_EPOCH_MS, + }); + const conflict = await conflictTool.execute({ ...validArgs, idempotencyKey: 'k' }); + expect(conflict.isError).toBe(true); + expect(conflict.content[0]?.text).toBe(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); + }); + + test('accepts every field exactly at its hard limit', async () => { + const rec = recordingPort(createdEcho); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-limit', + now: () => FIXED_EPOCH_MS, + }); + const trialRefs = Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS }, (_, i) => + `t${String(i).padStart(2, '0')}`.padEnd(FILE_FINDING_MAX_REF_LENGTH, 'x') + ); + const evidenceRefs = Array.from({ length: FILE_FINDING_MAX_EVIDENCE_REFS }, (_, i) => + `e${String(i).padStart(2, '0')}`.padEnd(FILE_FINDING_MAX_REF_LENGTH, 'y') + ); + + const res = await tool.execute({ + kind: 'dead_end', + title: 'T'.repeat(FILE_FINDING_MAX_TITLE_LENGTH), + summary: 'S'.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH), + trialRefs, + evidenceRefs, + idempotencyKey: 'K'.repeat(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH), + }); + + expect(res.isError).toBeUndefined(); + expect(rec.calls).toHaveLength(1); + expect(rec.calls[0]?.record.trialRefs).toHaveLength(FILE_FINDING_MAX_TRIAL_REFS); + expect(rec.calls[0]?.record.evidenceRefs).toHaveLength(FILE_FINDING_MAX_EVIDENCE_REFS); + }); + + test('measures limits after trimming, so padded at-limit text is accepted', async () => { + const rec = recordingPort(createdEcho); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-trim', + now: () => FIXED_EPOCH_MS, + }); + + const res = await tool.execute({ + ...validArgs, + title: ` ${'T'.repeat(FILE_FINDING_MAX_TITLE_LENGTH)} `, + }); + + expect(res.isError).toBeUndefined(); + expect(rec.calls[0]?.record.title).toHaveLength(FILE_FINDING_MAX_TITLE_LENGTH); + }); + + test('validation errors never echo submitted text, refs, or keys', async () => { + const sentinel = 'HOLDOUT_OBSERVATION_SENTINEL_0x5f3'; + const rec = recordingPort(createdEcho); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-v', + now: () => FIXED_EPOCH_MS, + }); + + const cases: readonly Record[] = [ + { ...validArgs, summary: `${sentinel} `.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH) }, + { ...validArgs, title: sentinel.repeat(20) }, + { ...validArgs, trialRefs: [sentinel.repeat(10)] }, + { ...validArgs, evidenceRefs: [sentinel.repeat(10)] }, + { ...validArgs, idempotencyKey: sentinel.repeat(5) }, + { ...validArgs, kind: sentinel }, + { ...validArgs, [sentinel]: 1.2345 }, + { ...validArgs, observations: [{ date: '2025-09-01', value: sentinel }] }, + ]; + + for (const args of cases) { + const res = await tool.execute(args); + expect(res.isError).toBe(true); + expect(res.content[0]?.text).not.toContain(sentinel); + } + expect(rec.calls).toHaveLength(0); + }); + + test('concurrent same-key filings across two tool instances store one row (promise barrier, no timers)', async () => { + const stored: FiledFindingRecord[] = []; + const byKey = new Map(); + let releaseFirst: () => void = () => undefined; + const firstHeld = new Promise(resolve => { + releaseFirst = resolve; + }); + let secondArrived: () => void = () => undefined; + const secondReached = new Promise(resolve => { + secondArrived = resolve; + }); + let callIndex = 0; + + const port: FindingWritePort = { + async appendFinding(record, key) { + callIndex += 1; + const mine = callIndex; + // Atomic compare-and-append (no await between read and write). + let outcome: AppendFindingResult; + const existing = key === undefined ? undefined : byKey.get(key); + if (existing === undefined) { + stored.push(record); + if (key !== undefined) { + byKey.set(key, record); + } + outcome = { status: 'created', id: record.id, createdAt: record.createdAt }; + } else if (areFiledFindingPayloadsEqual(existing, record)) { + outcome = { status: 'replayed', id: existing.id, createdAt: existing.createdAt }; + } else { + outcome = { status: 'conflict' }; + } + if (mine === 1) { + await firstHeld; + } else { + secondArrived(); + } + return outcome; + }, + }; + const lookup = lookupFrom(() => true).port; + const toolA = createFileFindingTool({ + port, + trialLookup: lookup, + newId: () => 'inst-a', + now: () => FIXED_EPOCH_MS, + }); + const toolB = createFileFindingTool({ + port, + trialLookup: lookup, + newId: () => 'inst-b', + now: () => FIXED_EPOCH_MS + 1_000, + }); + const args = { ...validArgs, idempotencyKey: 'concurrent' }; + + const pendingA = toolA.execute(args); + const pendingB = toolB.execute(args); + await secondReached; + releaseFirst(); + const [resA, resB] = await Promise.all([pendingA, pendingB]); + + expect(stored).toHaveLength(1); + expect(parseReceipt(resA.content[0]?.text)).toEqual({ + id: 'inst-a', + createdAt: new Date(FIXED_EPOCH_MS).toISOString(), + created: true, + }); + expect(parseReceipt(resB.content[0]?.text)).toEqual({ + id: 'inst-a', + createdAt: new Date(FIXED_EPOCH_MS).toISOString(), + created: false, + }); + }); + + test('payload equality helper ignores server metadata and is order-sensitive on normalized refs', () => { + const base = { + kind: 'finding' as const, + title: 't', + summary: 's', + trialRefs: ['a', 'b'], + evidenceRefs: [], + }; + expect( + areFiledFindingPayloadsEqual( + { ...base, id: 'x', createdAt: '1', status: 'pending_review' } as FiledFindingRecord, + { ...base, id: 'y', createdAt: '2', status: 'pending_review' } as FiledFindingRecord + ) + ).toBe(true); + expect(areFiledFindingPayloadsEqual(base, { ...base, trialRefs: ['a'] })).toBe(false); + expect(areFiledFindingPayloadsEqual(base, { ...base, evidenceRefs: ['e'] })).toBe(false); + expect(areFiledFindingPayloadsEqual(base, { ...base, title: 'T' })).toBe(false); + }); +}); From 7d7a1e3a5a5384fe0213334fe6ff8142f9f721a0 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:50:48 -0500 Subject: [PATCH 19/36] =?UTF-8?q?T-140:=20M2.2b=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20`ceoPosts`=20builder=20(`bot=20=3D=3D=20"1"`?= =?UTF-8?q?=20newswire=20vs=20retail=20split=20+=20`edited`=20text=20`know?= =?UTF-8?q?n=5Fat`=20guard=20+=20`spielId`=20dedup)=20with=20tests=20(no?= =?UTF-8?q?=20new=20crates,=20no=20CLI/bench=20changes)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 13 + tools/curate-etl/src/lib.rs | 6 + tools/curate-etl/src/posts.rs | 261 +++++++++ tools/curate-etl/src/posts_tests.rs | 806 ++++++++++++++++++++++++++++ 4 files changed, 1086 insertions(+) create mode 100644 tools/curate-etl/src/posts.rs create mode 100644 tools/curate-etl/src/posts_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 1b9ab54e..1d9b3436 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -131,6 +131,19 @@ Rules: Deferred out of `src/shorts.rs`: MongoDB `ceoShorts` BSON streaming, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, `rayon` sharding, and deriving `pct_float` from shares outstanding (values are passed through as supplied by the caller). +## `posts` Builder (`M2.2b`) + +`build_posts` (`src/posts.rs`) turns already-decoded `ceoPosts` rows (`CeoPost`) into two disjoint, deterministically sorted point-in-time `PostRow` streams (`newswire` and `retail`) aligned with `design/DATA-CONTRACTS.md` §1 (`ceoSymbols`, `ceoPosts`, `ceoShorts` row). + +Rules: +1. **Newswire vs. retail split:** `is_bot` is `true` iff `bot` is `"1"` after trimming whitespace; only `is_bot == true` rows route to `newswire`, and all other values (`None`, `"0"`, `""`, etc.) route to `retail`. +2. **Point-in-time `known_at` guard:** `posted_at = timestamp_ms * 1_000` (UTC microseconds) and `known_at = max(timestamp_ms, edited_ms) * 1_000` (`COALESCE(edited, timestamp)` clamped so `known_at >= posted_at` always holds). Any text-based feature MUST join on `known_at`, never `posted_at`. Rows with `edited_ms < timestamp_ms` clamp `known_at` to `posted_at` and increment `stats.edited_before_posted`. Both `stats.edited` and `stats.edited_before_posted` are counted on valid input rows before deduplication. Because `ceoPosts` overwrites `spiel` in place without version history, the builder retains one supplied version per `spiel_id` and cannot recover earlier pre-edit text. +3. **Validation & overflow:** Empty `spiel_id` or `timestamp_ms <= 0` rows are rejected before conversion and counted in `stats.rejected_invalid`. Overflow converting `timestamp_ms` or the selected `known_at` millisecond value to UTC microseconds returns `PostsError::TimestampOverflow`. +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. + ## `events` Builder (`M1.2g`) `build_events` (`src/events.rs`) turns raw `qmFilings` (`QmFiling`) and `qmEarnings` (`QmEarning`) streams into deterministically sorted point-in-time `EventRow` records matching `events/year=YYYY/part.parquet` in `design/DATA-CONTRACTS.md` (`listing_id, ts, known_at, known_at_source, kind, subtype, payload_json`), plus `partition_year_utc` / `EventRow::partition_year` for UTC `year=YYYY` partitioning. diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index cd76c47d..ced89856 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -25,6 +25,7 @@ pub mod parquet_events; pub mod parquet_fx; mod parquet_publish; pub mod parquet_shorts; +pub mod posts; pub mod provider_mapping; pub mod session_close; pub mod shorts; @@ -150,6 +151,9 @@ pub use parquet_shorts::{ shorts_parquet_schema, write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, ShortsWriteStats, }; +pub use posts::{ + build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO, +}; pub use provider_mapping::{ MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow, ProviderMappingTable, @@ -263,5 +267,7 @@ pub use run_mongo::{ CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError, }; +#[cfg(test)] +mod posts_tests; #[cfg(test)] mod tsv_fixture_tests; diff --git a/tools/curate-etl/src/posts.rs b/tools/curate-etl/src/posts.rs new file mode 100644 index 00000000..9ab9369f --- /dev/null +++ b/tools/curate-etl/src/posts.rs @@ -0,0 +1,261 @@ +//! Pure, in-memory `posts` builder for `ceoPosts` (`bot == "1"` newswire vs. retail split, +//! `edited` text point-in-time `known_at` guard, and deterministic global `spielId` deduplication). +//! +//! Aligned with `design/DATA-CONTRACTS.md` §1 (`ceoSymbols`, `ceoPosts`, `ceoShorts` row): +//! - Separates `bot == "1"` newswire posts (e.g. `@thenewswire`) from retail posts so wire +//! releases are never pooled with crowd chat. +//! - Computes text availability as `known_at = COALESCE(edited, timestamp)` in UTC microseconds, +//! clamped so `known_at >= posted_at` always holds. +//! - **Point-in-time rule:** any text-based feature or sentiment model MUST join on `known_at`, +//! 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. + +use std::error::Error; +use std::fmt; + +/// Canonical provenance label written to [`PostRow::source`]. +pub const POSTS_SOURCE_CEO: &str = "ceo_posts"; + +/// Typed errors returned by [`build_posts`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PostsError { + /// Converting a millisecond timestamp (`timestamp_ms` or `edited_ms`) to UTC microseconds + /// overflowed `i64`. + TimestampOverflow { + spiel_id: String, + field: &'static str, + timestamp_ms: i64, + }, +} + +impl fmt::Display for PostsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TimestampOverflow { + spiel_id, + field, + timestamp_ms, + } => write!( + f, + "timestamp overflow converting {field}={timestamp_ms} ms to UTC microseconds for spiel_id '{spiel_id}'" + ), + } + } +} + +impl Error for PostsError {} + +/// A single already-decoded `ceoPosts` input row. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CeoPost { + /// Channel / `ceoId` (or resolved listing key). + pub key: K, + /// Provider post identifier (`spielId`, MongoDB upsert key). + pub spiel_id: String, + /// Provider post creation time in epoch milliseconds (`timestamp`). + pub timestamp_ms: i64, + /// Optional provider last-edit time in epoch milliseconds (`edited`). + pub edited_ms: Option, + /// Raw provider bot flag (`bot`; only `"1"` after trim classifies as newswire). + pub bot: Option, + /// Optional provider author identifier (`userId`). + pub user_id: Option, + /// Post text (`spiel`). + pub text: String, +} + +/// A single curated `ceoPosts` output row. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PostRow { + pub key: K, + pub spiel_id: String, + /// Post creation timestamp in UTC microseconds (`timestamp_ms * 1_000`). + pub posted_at: i64, + /// Point-in-time text availability timestamp in UTC microseconds (`max(posted_at, edited_at)`). + /// Downstream text features MUST join on `known_at`, never `posted_at`. + pub known_at: i64, + pub is_bot: bool, + pub is_edited: bool, + pub user_id: Option, + pub text: String, + pub source: &'static str, +} + +/// Summary accounting counters produced alongside [`PostsBuild::newswire`] and +/// [`PostsBuild::retail`]. +/// +/// Conservation invariant: +/// `input == newswire + retail + duplicates_dropped + rejected_invalid` +/// +/// Accounting note: `edited` and `edited_before_posted` are counted on valid input rows before +/// `spiel_id` deduplication (so they include valid duplicates and exclude `rejected_invalid`). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PostsStats { + pub input: usize, + pub newswire: usize, + pub retail: usize, + pub edited: usize, + pub edited_before_posted: usize, + pub duplicates_dropped: usize, + pub rejected_invalid: usize, +} + +/// Output of [`build_posts`]: disjoint, deterministically sorted `newswire` and `retail` streams +/// plus exact accounting stats. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PostsBuild { + pub newswire: Vec>, + pub retail: Vec>, + pub stats: PostsStats, +} + +/// Builds disjoint, deterministically sorted `newswire` and `retail` post streams from raw +/// `ceoPosts` inputs. +/// +/// Rules: +/// - Rejects (counts in [`PostsStats::rejected_invalid`] without aborting) rows with an empty +/// `spiel_id` or `timestamp_ms <= 0` before timestamp conversion. +/// - Classifies `is_bot` as `true` iff `bot` is `"1"` after trimming whitespace; all other values +/// (`None`, `"0"`, `""`, etc.) route to `retail`. +/// - Sets `is_edited = edited_ms.is_some()`, counts valid edited rows in [`PostsStats::edited`], +/// and guards against look-ahead / clock-skew edits earlier than posting (`edited_ms < +/// timestamp_ms`) by clamping `known_at` to `posted_at` and incrementing +/// [`PostsStats::edited_before_posted`]. Both edit counters are recorded on valid rows prior to +/// deduplication. +/// - Converts `timestamp_ms` and the selected `known_at` millisecond value to UTC microseconds via +/// `checked_mul(1_000)`, returning [`PostsError::TimestampOverflow`] on overflow. +/// - Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail` (keeping +/// one supplied version per `spiel_id`; earlier pre-edit versions cannot be recovered). Within a +/// `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties +/// deterministically 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. All other `group_len - 1` rows are counted in +/// [`PostsStats::duplicates_dropped`]. +/// - Sorts both `newswire` and `retail` strictly ascending by `(key, known_at, spiel_id)`. +/// - Any permutation of `rows` produces identical `newswire`, `retail`, and `stats`. +pub fn build_posts(rows: I) -> Result, PostsError> +where + K: Ord + Clone, + I: IntoIterator>, +{ + let iter = rows.into_iter(); + let (lower, _) = iter.size_hint(); + let mut stats = PostsStats::default(); + let mut normalized: Vec> = Vec::with_capacity(lower); + + for row in iter { + stats.input += 1; + + if row.spiel_id.is_empty() || row.timestamp_ms <= 0 { + stats.rejected_invalid += 1; + continue; + } + + let is_bot = row.bot.as_deref().map(str::trim) == Some("1"); + let is_edited = row.edited_ms.is_some(); + + let known_at_ms = match row.edited_ms { + Some(edited_ms) => { + stats.edited += 1; + if edited_ms < row.timestamp_ms { + stats.edited_before_posted += 1; + row.timestamp_ms + } else { + edited_ms + } + } + None => row.timestamp_ms, + }; + + let posted_at = + row.timestamp_ms + .checked_mul(1_000) + .ok_or_else(|| PostsError::TimestampOverflow { + spiel_id: row.spiel_id.clone(), + field: "timestamp_ms", + timestamp_ms: row.timestamp_ms, + })?; + + let known_at = if known_at_ms == row.timestamp_ms { + posted_at + } else { + known_at_ms + .checked_mul(1_000) + .ok_or_else(|| PostsError::TimestampOverflow { + spiel_id: row.spiel_id.clone(), + field: "edited_ms", + timestamp_ms: known_at_ms, + })? + }; + + normalized.push(PostRow { + key: row.key, + spiel_id: row.spiel_id, + posted_at, + known_at, + is_bot, + is_edited, + user_id: row.user_id, + text: row.text, + source: POSTS_SOURCE_CEO, + }); + } + + normalized.sort_unstable_by(|a, b| { + a.spiel_id + .cmp(&b.spiel_id) + .then_with(|| b.known_at.cmp(&a.known_at)) + .then_with(|| b.posted_at.cmp(&a.posted_at)) + .then_with(|| b.is_edited.cmp(&a.is_edited)) + .then_with(|| b.is_bot.cmp(&a.is_bot)) + .then_with(|| b.key.cmp(&a.key)) + .then_with(|| b.user_id.cmp(&a.user_id)) + .then_with(|| b.text.cmp(&a.text)) + }); + + let mut newswire: Vec> = Vec::new(); + let mut retail: Vec> = Vec::new(); + let mut last_kept_in_newswire: Option = None; + + for row in normalized { + let is_dup = match last_kept_in_newswire { + Some(true) => newswire + .last() + .is_some_and(|prev| prev.spiel_id == row.spiel_id), + Some(false) => retail + .last() + .is_some_and(|prev| prev.spiel_id == row.spiel_id), + None => false, + }; + if is_dup { + stats.duplicates_dropped += 1; + continue; + } + if row.is_bot { + newswire.push(row); + last_kept_in_newswire = Some(true); + } else { + retail.push(row); + last_kept_in_newswire = Some(false); + } + } + + let output_order = |a: &PostRow, b: &PostRow| { + a.key + .cmp(&b.key) + .then_with(|| a.known_at.cmp(&b.known_at)) + .then_with(|| a.spiel_id.cmp(&b.spiel_id)) + }; + newswire.sort_unstable_by(output_order); + retail.sort_unstable_by(output_order); + + stats.newswire = newswire.len(); + stats.retail = retail.len(); + + Ok(PostsBuild { + newswire, + retail, + stats, + }) +} diff --git a/tools/curate-etl/src/posts_tests.rs b/tools/curate-etl/src/posts_tests.rs new file mode 100644 index 00000000..802e532d --- /dev/null +++ b/tools/curate-etl/src/posts_tests.rs @@ -0,0 +1,806 @@ +use std::collections::HashSet; + +use crate::posts::{ + build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO, +}; + +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_invariants(build: &PostsBuild) { + let s = &build.stats; + assert_eq!( + s.input, + s.newswire + s.retail + s.duplicates_dropped + s.rejected_invalid, + "accounting invariant failed: {s:?}" + ); + assert_eq!(s.newswire, build.newswire.len()); + assert_eq!(s.retail, build.retail.len()); + assert!(s.edited_before_posted <= s.edited); + + let mut seen_ids = HashSet::with_capacity(s.newswire + s.retail); + for (stream_name, rows, expected_bot) in [ + ("newswire", &build.newswire, true), + ("retail", &build.retail, false), + ] { + for pair in rows.windows(2) { + assert!( + (&pair[0].key, pair[0].known_at, &pair[0].spiel_id) + < (&pair[1].key, pair[1].known_at, &pair[1].spiel_id), + "{stream_name} must be strictly sorted by (key, known_at, spiel_id)" + ); + } + for row in rows { + assert_eq!(row.is_bot, expected_bot); + assert_eq!(row.source, POSTS_SOURCE_CEO); + assert!( + row.known_at >= row.posted_at, + "look-ahead violation in {stream_name}: known_at {} < posted_at {}", + row.known_at, + row.posted_at + ); + assert!( + seen_ids.insert(row.spiel_id.as_str()), + "spiel_id '{}' appeared more than once across streams", + row.spiel_id + ); + } + } +} + +/// Deterministic SplitMix64 PRNG for fixture generation and shuffles. +struct SplitMix64(u64); + +impl SplitMix64 { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) + } + + fn shuffle(&mut self, slice: &mut [T]) { + for i in (1..slice.len()).rev() { + let j = (self.next_u64() as usize) % (i + 1); + slice.swap(i, j); + } + } +} + +/// 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 +} + +#[test] +fn bot_split_routes_only_trimmed_one_to_newswire_and_preserves_fields() { + let input = vec![ + post( + "chan_a", + "sp_bot_exact", + 1_700_000_000_000, + None, + Some("1"), + Some("wire_user"), + "News release headline", + ), + post( + "chan_b", + "sp_bot_trimmed", + 1_700_000_001_000, + None, + Some(" 1 "), + None, + "Trimmed bot flag release", + ), + post( + "chan_a", + "sp_retail_zero", + 1_700_000_002_000, + None, + Some("0"), + Some("u1"), + "Retail zero flag", + ), + post( + "chan_a", + "sp_retail_empty", + 1_700_000_003_000, + None, + Some(""), + Some("u2"), + "Retail empty flag", + ), + post( + "chan_b", + "sp_retail_none", + 1_700_000_004_000, + None, + None, + None, + "Retail missing flag", + ), + post( + "chan_b", + "sp_retail_other", + 1_700_000_005_000, + None, + Some("true"), + Some("u3"), + "Non-1 string is retail", + ), + ]; + + let built = build_posts(input).expect("valid posts should build"); + assert_invariants(&built); + + assert_eq!( + built.stats, + PostsStats { + input: 6, + newswire: 2, + retail: 4, + edited: 0, + edited_before_posted: 0, + duplicates_dropped: 0, + rejected_invalid: 0, + } + ); + + assert_eq!( + built.newswire, + vec![ + PostRow { + key: "chan_a".to_string(), + spiel_id: "sp_bot_exact".to_string(), + posted_at: 1_700_000_000_000_000, + known_at: 1_700_000_000_000_000, + is_bot: true, + is_edited: false, + user_id: Some("wire_user".to_string()), + text: "News release headline".to_string(), + source: POSTS_SOURCE_CEO, + }, + PostRow { + key: "chan_b".to_string(), + spiel_id: "sp_bot_trimmed".to_string(), + posted_at: 1_700_000_001_000_000, + known_at: 1_700_000_001_000_000, + is_bot: true, + is_edited: false, + user_id: None, + text: "Trimmed bot flag release".to_string(), + source: POSTS_SOURCE_CEO, + }, + ] + ); + + let retail_ids: Vec<&str> = built.retail.iter().map(|r| r.spiel_id.as_str()).collect(); + assert_eq!( + retail_ids, + vec![ + "sp_retail_zero", + "sp_retail_empty", + "sp_retail_none", + "sp_retail_other" + ] + ); + assert_eq!(built.retail[0].user_id.as_deref(), Some("u1")); + assert_eq!(built.retail[0].text, "Retail zero flag"); + assert_eq!(built.retail[2].user_id, None); + assert_eq!(built.retail[2].source, POSTS_SOURCE_CEO); +} + +#[test] +fn edited_timestamps_guard_known_at_and_availability_cutoff() { + let t_post = 1_710_000_000_000_i64; + let t_edit_later = t_post + 720_000; // +12 minutes + let t_edit_earlier = t_post - 5_000; // -5 seconds (clock skew) + + let input = vec![ + post( + "TSX:ABC", + "sp_unedited", + t_post, + None, + None, + Some("u1"), + "Unedited baseline", + ), + post( + "TSX:ABC", + "sp_edited_equal", + t_post, + Some(t_post), + None, + Some("u2"), + "Edited at exact post ms", + ), + post( + "TSX:ABC", + "sp_edited_later", + t_post, + Some(t_edit_later), + None, + Some("u3"), + "Rewritten after move", + ), + post( + "TSX:ABC", + "sp_edited_earlier", + t_post, + Some(t_edit_earlier), + None, + Some("u4"), + "Skewed edit timestamp", + ), + ]; + + let built = build_posts(input).expect("valid posts should build"); + assert_invariants(&built); + + assert_eq!(built.stats.edited, 3); + assert_eq!(built.stats.edited_before_posted, 1); + + let by_id = |id: &str| { + built + .retail + .iter() + .find(|r| r.spiel_id == id) + .expect("expected row in retail") + }; + + let unedited = by_id("sp_unedited"); + assert_eq!(unedited.posted_at, t_post * 1_000); + assert_eq!(unedited.known_at, t_post * 1_000); + assert!(!unedited.is_edited); + + let equal = by_id("sp_edited_equal"); + assert_eq!(equal.posted_at, t_post * 1_000); + assert_eq!(equal.known_at, t_post * 1_000); + assert!(equal.is_edited); + + let later = by_id("sp_edited_later"); + assert_eq!(later.posted_at, t_post * 1_000); + assert_eq!(later.known_at, t_edit_later * 1_000); + assert!(later.is_edited); + + // Point-in-time availability check: at a cutoff strictly between posted_at and edited_at, + // the unedited post is visible (known_at < cutoff) while the edited post is NOT yet visible. + let cutoff = (t_post + 300_000) * 1_000; // +5 minutes after post + assert!(unedited.known_at < cutoff); + assert!(later.posted_at < cutoff); + assert!(later.known_at > cutoff); + + let earlier = by_id("sp_edited_earlier"); + assert_eq!(earlier.posted_at, t_post * 1_000); + assert_eq!(earlier.known_at, t_post * 1_000); + assert!(earlier.is_edited); +} + +#[test] +fn generated_fixture_preserves_known_at_ge_posted_at_and_edit_accounting() { + let mut rng = SplitMix64(0x5eed_cafe_1234_5678); + let mut input = Vec::with_capacity(220); + let mut expected_edited = 0usize; + let mut expected_edited_before_posted = 0usize; + let mut expected_rejected = 0usize; + + // 200 valid rows (including intentional duplicate spiel_ids across 120 buckets). + for i in 0..200usize { + let key = format!("CH_{:02}", rng.next_u64() % 10); + let spiel_id = format!("sp_{:03}", rng.next_u64() % 120); + let timestamp_ms = 1_700_000_000_000 + (rng.next_u64() % 10_000_000) as i64; + let edit_mode = rng.next_u64() % 4; + let edited_ms = match edit_mode { + 0 => None, + 1 => { + expected_edited += 1; + Some(timestamp_ms + (rng.next_u64() % 900_000) as i64 + 1) + } + 2 => { + expected_edited += 1; + expected_edited_before_posted += 1; + Some(timestamp_ms - (rng.next_u64() % 60_000) as i64 - 1) + } + _ => { + expected_edited += 1; + Some(timestamp_ms) + } + }; + let bot = match rng.next_u64() % 5 { + 0 => Some("1"), + 1 => Some(" 1 "), + 2 => Some("0"), + 3 => Some(""), + _ => None, + }; + input.push(post( + &key, + &spiel_id, + timestamp_ms, + edited_ms, + bot, + Some(&format!("u{}", i % 17)), + &format!("generated post {i}"), + )); + } + + // 20 rejected rows (some carrying edited_ms that must NOT count toward edited stats). + for i in 0..20usize { + expected_rejected += 1; + if i % 2 == 0 { + input.push(post( + "CH_BAD", + "", + 1_700_000_000_000, + Some(1_699_999_999_000), + Some("1"), + None, + "empty id", + )); + } else { + input.push(post( + "CH_BAD", + &format!("bad_ts_{i}"), + -(i as i64), + Some(-(i as i64) - 100), + None, + None, + "non-positive ts", + )); + } + } + + let built = build_posts(input).expect("generated fixture should build"); + assert_invariants(&built); + assert_eq!(built.stats.input, 220); + assert_eq!(built.stats.rejected_invalid, expected_rejected); + assert_eq!(built.stats.edited, expected_edited); + assert_eq!( + built.stats.edited_before_posted, + expected_edited_before_posted + ); + assert!(built.stats.duplicates_dropped > 0); +} + +#[test] +fn dedup_keeps_greatest_known_at_globally_across_channels_and_streams() { + let base_ms = 1_720_000_000_000_i64; + let input = vec![ + post( + "chan_a", + "shared_id", + base_ms, + None, + Some("1"), + Some("wire"), + "v1 newswire", + ), + post( + "chan_b", + "shared_id", + base_ms, + Some(base_ms + 120_000), + Some("0"), + Some("retail_u"), + "v2 edited later in another channel/stream", + ), + post( + "chan_c", + "shared_id", + base_ms + 60_000, + None, + Some("1"), + Some("wire"), + "v1.5 intermediate known_at", + ), + ]; + + let built = build_posts(input).expect("valid posts should build"); + assert_invariants(&built); + + assert_eq!(built.stats.input, 3); + assert_eq!(built.stats.newswire, 0); + assert_eq!(built.stats.retail, 1); + assert_eq!(built.stats.duplicates_dropped, 2); + assert_eq!(built.retail[0].key, "chan_b"); + assert_eq!(built.retail[0].known_at, (base_ms + 120_000) * 1_000); + assert_eq!( + built.retail[0].text, + "v2 edited later in another channel/stream" + ); +} + +fn conflicting_tie_group() -> Vec> { + let t = 1_725_000_000_000_i64; + vec![ + // Same spiel_id & same known_at = t * 1_000, differing in text and bot flag. + post( + "chan_m", + "tie_spiel", + t, + None, + Some("0"), + Some("u_b"), + "alpha text", + ), + post( + "chan_m", + "tie_spiel", + t, + None, + Some("0"), + Some("u_b"), + "zeta text", + ), + // is_bot = true beats is_bot = false on same (known_at, posted_at, is_edited). + post( + "chan_m", + "tie_spiel", + t, + None, + Some("1"), + Some("u_a"), + "bot winner text", + ), + // is_edited = true beats is_edited = false on same (known_at, posted_at), even with bot="0". + post( + "chan_a", + "tie_spiel", + t, + Some(t), + Some("0"), + None, + "edited winner text", + ), + ] +} + +#[test] +fn dedup_conflicting_known_at_ties_pick_exact_tuple_winner_across_all_permutations() { + let group = conflicting_tie_group(); + let expected_drops = group.len() - 1; + let perms = all_permutations(&group); + assert_eq!(perms.len(), 24); + + let baseline = build_posts(group).expect("tie group should build"); + assert_invariants(&baseline); + assert_eq!(baseline.stats.duplicates_dropped, expected_drops); + assert_eq!(baseline.newswire.len(), 0); + assert_eq!(baseline.retail.len(), 1); + assert_eq!(baseline.retail[0].text, "edited winner text"); + assert!(baseline.retail[0].is_edited); + assert!(!baseline.retail[0].is_bot); + + for perm in perms { + let built = build_posts(perm).expect("permutation should build"); + assert_eq!(built, baseline); + } + + // Also verify each individual tie-break field in exact precedence order: + // (posted_at, is_edited, is_bot, key, user_id [None < Some], text). + let t = 1_725_000_100_000_i64; + // 1. posted_at beats is_edited + let b1 = build_posts(vec![ + post( + "z", + "tb1", + t - 1_000, + Some(t), + Some("1"), + Some("z"), + "earlier post edited to t", + ), + post( + "a", + "tb1", + t, + None, + Some("0"), + None, + "later posted_at wins", + ), + ]) + .unwrap(); + assert_eq!(b1.retail[0].text, "later posted_at wins"); + + // 2. is_bot beats key + let b2 = build_posts(vec![ + post("zzz", "tb2", t, None, Some("0"), Some("z"), "retail"), + post("aaa", "tb2", t, None, Some("1"), None, "bot wins"), + ]) + .unwrap(); + assert_eq!(b2.newswire[0].text, "bot wins"); + + // 3. key beats user_id + let b3 = build_posts(vec![ + post("chan_a", "tb3", t, None, Some("0"), Some("zzz"), "low key"), + post("chan_z", "tb3", t, None, Some("0"), None, "high key wins"), + ]) + .unwrap(); + assert_eq!(b3.retail[0].text, "high key wins"); + + // 4. user_id (None < Some) beats text + let b4 = build_posts(vec![ + post("chan_a", "tb4", t, None, Some("0"), None, "zzz text"), + post( + "chan_a", + "tb4", + t, + None, + Some("0"), + Some("a"), + "some user_id wins", + ), + ]) + .unwrap(); + assert_eq!(b4.retail[0].text, "some user_id wins"); + + // 5. text breaks final tie + let b5 = build_posts(vec![ + post("chan_a", "tb5", t, None, Some("0"), Some("u1"), "alpha"), + post("chan_a", "tb5", t, None, Some("0"), Some("u1"), "omega"), + ]) + .unwrap(); + assert_eq!(b5.retail[0].text, "omega"); +} + +#[test] +fn shuffle_invariance_with_conflicting_ties_and_sort_order() { + let mut fixture = conflicting_tie_group(); + fixture.extend([ + post( + "chan_b", + "sp_10", + 1_725_000_010_000, + None, + Some("1"), + Some("wire"), + "wire 10", + ), + post( + "chan_a", + "sp_02", + 1_725_000_020_000, + None, + Some("1"), + Some("wire"), + "wire 02", + ), + post( + "chan_a", + "sp_01", + 1_725_000_020_000, + None, + Some("1"), + Some("wire"), + "wire 01 same known_at", + ), + post( + "chan_b", + "sp_20", + 1_725_000_005_000, + Some(1_725_000_030_000), + None, + Some("u20"), + "retail edited later", + ), + post( + "chan_b", + "sp_20", + 1_725_000_005_000, + None, + None, + Some("u20"), + "retail older version", + ), + post( + "chan_a", + "sp_03", + 1_725_000_001_000, + Some(1_725_000_000_000), + Some("0"), + Some("u03"), + "retail edited before posted", + ), + post( + "chan_a", + "", + 1_725_000_001_000, + None, + Some("1"), + None, + "invalid empty id", + ), + post( + "chan_a", + "sp_bad_ts", + 0, + None, + None, + None, + "invalid zero ts", + ), + ]); + + let baseline = build_posts(fixture.clone()).expect("fixture should build"); + assert_invariants(&baseline); + + // Reversed order. + let mut reversed = fixture.clone(); + reversed.reverse(); + assert_eq!(build_posts(reversed).unwrap(), baseline); + + // Multiple deterministic shuffles. + let mut rng = SplitMix64(0x1234_5678_9abc_def0); + for _ in 0..16 { + let mut shuffled = fixture.clone(); + rng.shuffle(&mut shuffled); + let built = build_posts(shuffled).expect("shuffled fixture should build"); + assert_eq!(built, baseline); + } + + // Verify generic non-String key (e.g., listing_id: i32) works identically. + let int_keyed = build_posts(vec![ + CeoPost { + key: 200_i32, + spiel_id: "s2".to_string(), + timestamp_ms: 1_700_000_000_000, + edited_ms: None, + bot: None, + user_id: None, + text: "listing 200".to_string(), + }, + CeoPost { + key: 100_i32, + spiel_id: "s1".to_string(), + timestamp_ms: 1_700_000_000_000, + edited_ms: None, + bot: Some("1".to_string()), + user_id: None, + text: "listing 100".to_string(), + }, + ]) + .expect("i32 keys should build"); + assert_invariants(&int_keyed); + assert_eq!(int_keyed.newswire[0].key, 100); + assert_eq!(int_keyed.retail[0].key, 200); +} + +#[test] +fn empty_invalid_and_timestamp_overflow_boundaries() { + // Empty input. + let empty = build_posts(Vec::>::new()).expect("empty input should succeed"); + assert!(empty.newswire.is_empty()); + assert!(empty.retail.is_empty()); + assert_eq!(empty.stats, PostsStats::default()); + + // Empty spiel_id, zero timestamp_ms, negative timestamp_ms (including i64::MIN). + let invalid = build_posts(vec![ + post("c", "", 1_700_000_000_000, None, Some("1"), None, "empty id"), + post("c", "sp_zero", 0, None, None, None, "zero ts"), + post("c", "sp_neg", -1, None, None, None, "negative ts"), + post("c", "sp_min", i64::MIN, None, None, None, "i64 min ts"), + ]) + .expect("invalid rows should be rejected, not error"); + assert_invariants(&invalid); + assert_eq!(invalid.stats.input, 4); + assert_eq!(invalid.stats.rejected_invalid, 4); + assert_eq!(invalid.stats.newswire, 0); + assert_eq!(invalid.stats.retail, 0); + + // Greatest convertible millisecond value succeeds for both timestamp_ms and edited_ms. + let max_ms = i64::MAX / 1_000; + let boundary_ok = build_posts(vec![ + post("c", "sp_max_post", max_ms, None, None, None, "max posted"), + post( + "c", + "sp_max_edit", + max_ms - 1, + Some(max_ms), + None, + None, + "max edited", + ), + // Clamped earlier edited_ms = i64::MIN must not overflow when rejected in favor of timestamp_ms. + post( + "c", + "sp_clamped_min_edit", + 1_000, + Some(i64::MIN), + None, + None, + "clamped min edit", + ), + ]) + .expect("max convertible ms should succeed"); + assert_invariants(&boundary_ok); + assert_eq!(boundary_ok.stats.retail, 3); + assert_eq!(boundary_ok.stats.edited, 2); + assert_eq!(boundary_ok.stats.edited_before_posted, 1); + + // Overflow on timestamp_ms returns typed PostsError::TimestampOverflow. + let err_post = build_posts(vec![post( + "c", + "sp_overflow_post", + max_ms + 1, + None, + None, + None, + "overflow post", + )]) + .expect_err("timestamp_ms overflow should error"); + assert_eq!( + err_post, + PostsError::TimestampOverflow { + spiel_id: "sp_overflow_post".to_string(), + field: "timestamp_ms", + timestamp_ms: max_ms + 1, + } + ); + assert!(err_post.to_string().contains("timestamp_ms")); + assert!(err_post.to_string().contains("sp_overflow_post")); + + // Overflow on selected edited_ms returns typed PostsError::TimestampOverflow. + let err_edit = build_posts(vec![post( + "c", + "sp_overflow_edit", + 1_700_000_000_000, + Some(max_ms + 1), + None, + None, + "overflow edit", + )]) + .expect_err("edited_ms overflow should error"); + assert_eq!( + err_edit, + PostsError::TimestampOverflow { + spiel_id: "sp_overflow_edit".to_string(), + field: "edited_ms", + timestamp_ms: max_ms + 1, + } + ); + assert!(err_edit.to_string().contains("edited_ms")); + assert!(err_edit.to_string().contains("sp_overflow_edit")); +} From d4df7344e6a5dd7d10c193bf5309fb008e129b7a Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:57:27 -0500 Subject: [PATCH 20/36] =?UTF-8?q?T-140:=20M2.2b=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20`ceoPosts`=20builder=20(`bot=20=3D=3D=20"1"`?= =?UTF-8?q?=20newswire=20vs=20retail=20split=20+=20`edited`=20text=20`know?= =?UTF-8?q?n=5Fat`=20guard=20+=20`spielId`=20dedup)=20with=20tests=20(no?= =?UTF-8?q?=20new=20crates,=20no=20CLI/bench=20changes)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/posts.rs | 21 +--- tools/curate-etl/src/posts_tests.rs | 182 ++++++++++++++++++++++++++++ 2 files changed, 186 insertions(+), 17 deletions(-) diff --git a/tools/curate-etl/src/posts.rs b/tools/curate-etl/src/posts.rs index 9ab9369f..3769fcf8 100644 --- a/tools/curate-etl/src/posts.rs +++ b/tools/curate-etl/src/posts.rs @@ -214,30 +214,17 @@ where .then_with(|| b.text.cmp(&a.text)) }); + let before_dedup = normalized.len(); + normalized.dedup_by(|a, b| a.spiel_id == b.spiel_id); + stats.duplicates_dropped = before_dedup - normalized.len(); + let mut newswire: Vec> = Vec::new(); let mut retail: Vec> = Vec::new(); - let mut last_kept_in_newswire: Option = None; - for row in normalized { - let is_dup = match last_kept_in_newswire { - Some(true) => newswire - .last() - .is_some_and(|prev| prev.spiel_id == row.spiel_id), - Some(false) => retail - .last() - .is_some_and(|prev| prev.spiel_id == row.spiel_id), - None => false, - }; - if is_dup { - stats.duplicates_dropped += 1; - continue; - } if row.is_bot { newswire.push(row); - last_kept_in_newswire = Some(true); } else { retail.push(row); - last_kept_in_newswire = Some(false); } } diff --git a/tools/curate-etl/src/posts_tests.rs b/tools/curate-etl/src/posts_tests.rs index 802e532d..53f0f91d 100644 --- a/tools/curate-etl/src/posts_tests.rs +++ b/tools/curate-etl/src/posts_tests.rs @@ -804,3 +804,185 @@ fn empty_invalid_and_timestamp_overflow_boundaries() { assert!(err_edit.to_string().contains("edited_ms")); assert!(err_edit.to_string().contains("sp_overflow_edit")); } + +#[test] +fn bot_flag_whitespace_and_near_miss_values() { + let base = 1_730_000_000_000_i64; + let input = vec![ + post("c", "b_exact", base, None, Some("1"), None, "exact"), + post("c", "b_tabs", base + 1, None, Some("\t1\r\n"), None, "tabs"), + post("c", "r_leading_zero", base + 2, None, Some("01"), None, "01"), + post("c", "r_decimal", base + 3, None, Some("1.0"), None, "1.0"), + post("c", "r_plus", base + 4, None, Some("+1"), None, "+1"), + post("c", "r_ten", base + 5, None, Some("10"), None, "10"), + post("c", "r_two_ones", base + 6, None, Some("1 1"), None, "1 1"), + post("c", "r_spaces", base + 7, None, Some(" "), None, "spaces"), + ]; + + let built = build_posts(input).expect("valid posts should build"); + assert_invariants(&built); + + let wire_ids: Vec<&str> = built.newswire.iter().map(|r| r.spiel_id.as_str()).collect(); + let retail_ids: Vec<&str> = built.retail.iter().map(|r| r.spiel_id.as_str()).collect(); + assert_eq!(wire_ids, vec!["b_exact", "b_tabs"]); + assert_eq!( + retail_ids, + vec![ + "r_leading_zero", + "r_decimal", + "r_plus", + "r_ten", + "r_two_ones", + "r_spaces", + ] + ); +} + +#[test] +fn exact_duplicate_rows_collapse_and_preserve_pre_dedup_edit_counts() { + let t = 1_730_100_000_000_i64; + let edited_dup = post( + "TSXV:XYZ", + "dup_edited", + t, + Some(t + 60_000), + Some("0"), + Some("u1"), + "exact same edited text", + ); + let skewed_dup = post( + "TSXV:XYZ", + "dup_skewed", + t + 1_000, + Some(t), + Some("1"), + Some("wire"), + "exact same skewed wire", + ); + + let input = vec![ + edited_dup.clone(), + edited_dup.clone(), + edited_dup, + skewed_dup.clone(), + skewed_dup, + ]; + + let built = build_posts(input).expect("exact duplicates should build"); + assert_invariants(&built); + assert_eq!( + built.stats, + PostsStats { + input: 5, + newswire: 1, + retail: 1, + edited: 5, + edited_before_posted: 2, + duplicates_dropped: 3, + rejected_invalid: 0, + } + ); + assert_eq!(built.retail[0].spiel_id, "dup_edited"); + assert_eq!(built.newswire[0].spiel_id, "dup_skewed"); +} + +#[test] +fn dedup_alternating_stream_winners_and_losers_across_shuffles() { + let t = 1_730_200_000_000_i64; + let fixture = vec![ + // Group 1: newswire wins over retail via higher known_at. + post("c1", "sp_01", t, None, Some("0"), Some("r1"), "retail v1"), + post("c1", "sp_01", t, Some(t + 5_000), Some("1"), Some("w1"), "wire v2"), + // Group 2: retail wins over newswire via higher known_at. + post("c1", "sp_02", t, None, Some("1"), Some("w2"), "wire v1"), + post("c1", "sp_02", t, Some(t + 5_000), Some("0"), Some("r2"), "retail v2"), + // Group 3: newswire wins over retail via tie-break (is_bot = true > false). + post("c1", "sp_03", t, None, Some("0"), Some("r3"), "retail tie"), + post("c1", "sp_03", t, None, Some("1"), Some("w3"), "wire tie"), + // Group 4: retail wins over newswire via tie-break (is_edited = true > false). + post("c1", "sp_04", t, None, Some("1"), Some("w4"), "wire unedited"), + post("c1", "sp_04", t, Some(t), Some("0"), Some("r4"), "retail edited"), + ]; + + let baseline = build_posts(fixture.clone()).expect("alternating fixture should build"); + assert_invariants(&baseline); + assert_eq!(baseline.stats.newswire, 2); + assert_eq!(baseline.stats.retail, 2); + assert_eq!(baseline.stats.duplicates_dropped, 4); + + let wire_ids: Vec<&str> = baseline + .newswire + .iter() + .map(|r| r.spiel_id.as_str()) + .collect(); + let retail_ids: Vec<&str> = baseline + .retail + .iter() + .map(|r| r.spiel_id.as_str()) + .collect(); + assert_eq!(wire_ids, vec!["sp_03", "sp_01"]); + assert_eq!(retail_ids, vec!["sp_04", "sp_02"]); + + let mut rng = SplitMix64(0xdead_beef_cafe_babe); + for _ in 0..32 { + let mut shuffled = fixture.clone(); + rng.shuffle(&mut shuffled); + let built = build_posts(shuffled).expect("shuffled alternating fixture should build"); + assert_eq!(built, baseline); + } +} + +#[test] +fn cutoff_filter_on_known_at_hides_post_edited_after_cutoff() { + // Mirrors the worked example: cutoff at 15:45, six retail posts (one posted at 15:40 and + // rewritten at 15:52 after the stock drops), plus three unedited wire releases. + let t_1530 = 1_730_300_000_000_i64; + let t_1540 = t_1530 + 10 * 60_000; + let t_1545_cutoff_us = (t_1530 + 15 * 60_000) * 1_000; + let t_1552 = t_1530 + 22 * 60_000; + + let input = vec![ + post("TSXV:EX", "r1", t_1530, None, None, Some("u1"), "+1"), + post("TSXV:EX", "r2", t_1530 + 60_000, None, None, Some("u2"), "+1"), + post("TSXV:EX", "r3", t_1530 + 120_000, None, None, Some("u3"), "0"), + post("TSXV:EX", "r4", t_1530 + 180_000, None, None, Some("u4"), "-1"), + post("TSXV:EX", "r5", t_1530 + 240_000, None, None, Some("u5"), "0"), + post( + "TSXV:EX", + "r6_edited_after_cutoff", + t_1540, + Some(t_1552), + None, + Some("u6"), + "-1 rewritten after drop", + ), + post("TSXV:EX", "w1", t_1530 + 30_000, None, Some("1"), Some("wire"), "+1"), + post("TSXV:EX", "w2", t_1530 + 90_000, None, Some("1"), Some("wire"), "+1"), + post("TSXV:EX", "w3", t_1530 + 150_000, None, Some("1"), Some("wire"), "+1"), + ]; + + let built = build_posts(input).expect("worked example should build"); + assert_invariants(&built); + assert_eq!(built.retail.len(), 6); + assert_eq!(built.newswire.len(), 3); + + // Filtering retail on known_at < cutoff excludes the post edited at 15:52. + let visible_by_known_at: Vec<&str> = built + .retail + .iter() + .filter(|r| r.known_at < t_1545_cutoff_us) + .map(|r| r.spiel_id.as_str()) + .collect(); + assert_eq!(visible_by_known_at.len(), 5); + assert!(!visible_by_known_at.contains(&"r6_edited_after_cutoff")); + + // Filtering on posted_at < cutoff would leak the post edited at 15:52. + let leaked_by_posted_at: Vec<&str> = built + .retail + .iter() + .filter(|r| r.posted_at < t_1545_cutoff_us) + .map(|r| r.spiel_id.as_str()) + .collect(); + assert_eq!(leaked_by_posted_at.len(), 6); + assert!(leaked_by_posted_at.contains(&"r6_edited_after_cutoff")); +} From 0e5074c5f422b2f0136859ce6ef24df8dbc254a9 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 08:02:51 -0500 Subject: [PATCH 21/36] T-140: tests --- tools/curate-etl/tests/posts_qa_contract.rs | 332 ++++++++++++++++++++ 1 file changed, 332 insertions(+) create mode 100644 tools/curate-etl/tests/posts_qa_contract.rs diff --git a/tools/curate-etl/tests/posts_qa_contract.rs b/tools/curate-etl/tests/posts_qa_contract.rs new file mode 100644 index 00000000..06bb8a27 --- /dev/null +++ b/tools/curate-etl/tests/posts_qa_contract.rs @@ -0,0 +1,332 @@ +//! QA contract tests for the public `posts` builder (T-140 / M2.2b). +//! +//! Covers gaps left by the in-crate `posts_tests.rs`, checking against independent references +//! rather than the builder's own logic: +//! - seeded differential test against a naive reference (group by `spiel_id`, `max_by` winner +//! tuple, route, sort) on high-collision fixtures that force `known_at` ties; +//! - truncation test: every row visible at a cutoff in the full build is reproduced unchanged by a +//! build over only the inputs available before that cutoff; +//! - poison test: absurd future edits to existing posts never change what is visible before the +//! cutoff, except that the poisoned posts stop being visible (latest-only text, no recovery); +//! - an overflow row anywhere in the batch fails the whole build for every input order. + +use std::collections::{BTreeMap, BTreeSet}; + +use curate_etl::{build_posts, CeoPost, PostRow, PostsBuild, PostsError, POSTS_SOURCE_CEO}; + +/// Deterministic SplitMix64 PRNG (seeded; no wall clock). +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + + fn shuffle(&mut self, v: &mut [T]) { + for i in (1..v.len()).rev() { + let j = self.below(i as u64 + 1) as usize; + v.swap(i, j); + } + } +} + +const BASE_MS: i64 = 1_735_000_000_000; + +/// High-collision fixture: few ids, few channels, coarse timestamps, so ties on `known_at` and on +/// several tie-break fields are frequent. Includes invalid rows. +fn collision_fixture(seed: u64, n: usize, ids: u64) -> Vec> { + let mut rng = Rng(seed); + let bots = [ + Some("1"), + Some(" 1"), + Some("0"), + Some(""), + None, + Some("yes"), + ]; + let users = [None, Some("u_a"), Some("u_b")]; + let texts = ["a", "b", "c"]; + (0..n) + .map(|_| { + let spiel_id = match rng.below(25) { + 0 => String::new(), + _ => format!("sp_{}", rng.below(ids)), + }; + let timestamp_ms = match rng.below(20) { + 0 => 0, + 1 => -5, + _ => BASE_MS + 1_000 * rng.below(4) as i64, + }; + let edited_ms = match rng.below(4) { + 0 => None, + 1 => Some(timestamp_ms), + 2 => Some(timestamp_ms - 1_000), + _ => Some(BASE_MS + 1_000 * rng.below(6) as i64), + }; + CeoPost { + key: format!("ch_{}", rng.below(3)), + spiel_id, + timestamp_ms, + edited_ms, + bot: bots[rng.below(bots.len() as u64) as usize].map(str::to_string), + user_id: users[rng.below(users.len() as u64) as usize].map(str::to_string), + text: texts[rng.below(texts.len() as u64) as usize].to_string(), + } + }) + .collect() +} + +/// Independent reference written from the task's rules, not from `posts.rs`. +fn reference(rows: &[CeoPost]) -> (Vec, Vec, usize, usize) { + let mut rejected = 0usize; + let mut groups: BTreeMap> = BTreeMap::new(); + for r in rows { + if r.spiel_id.is_empty() || r.timestamp_ms <= 0 { + rejected += 1; + continue; + } + let posted_at = r.timestamp_ms * 1_000; + let known_at = r + .edited_ms + .map_or(r.timestamp_ms, |e| e.max(r.timestamp_ms)) + * 1_000; + groups.entry(r.spiel_id.clone()).or_default().push(PostRow { + key: r.key.clone(), + spiel_id: r.spiel_id.clone(), + posted_at, + known_at, + is_bot: r.bot.as_deref().map(str::trim) == Some("1"), + is_edited: r.edited_ms.is_some(), + user_id: r.user_id.clone(), + text: r.text.clone(), + source: POSTS_SOURCE_CEO, + }); + } + let mut dropped = 0usize; + let (mut wire, mut retail) = (Vec::new(), Vec::new()); + for (_, group) in groups { + dropped += group.len() - 1; + let winner = group + .into_iter() + .max_by(|a, b| { + ( + a.known_at, + a.posted_at, + a.is_edited, + a.is_bot, + &a.key, + &a.user_id, + &a.text, + ) + .cmp(&( + b.known_at, + b.posted_at, + b.is_edited, + b.is_bot, + &b.key, + &b.user_id, + &b.text, + )) + }) + .unwrap(); + if winner.is_bot { + wire.push(winner); + } else { + retail.push(winner); + } + } + let order = |r: &PostRow| (r.key.clone(), r.known_at, r.spiel_id.clone()); + wire.sort_by_key(order); + retail.sort_by_key(order); + (wire, retail, dropped, rejected) +} + +#[test] +fn seeded_differential_matches_naive_reference_on_high_collision_fixtures() { + for seed in 0..40u64 { + let input = collision_fixture(0xC0FF_EE00 + seed, 120, 8); + let built = build_posts(input.clone()).expect("fixture has no overflow"); + let (wire, retail, dropped, rejected) = reference(&input); + + assert_eq!(built.newswire, wire, "seed {seed}: newswire mismatch"); + assert_eq!(built.retail, retail, "seed {seed}: retail mismatch"); + assert_eq!(built.stats.duplicates_dropped, dropped, "seed {seed}"); + assert_eq!(built.stats.rejected_invalid, rejected, "seed {seed}"); + assert_eq!(built.stats.input, input.len()); + assert_eq!( + built.stats.input, + built.stats.newswire + + built.stats.retail + + built.stats.duplicates_dropped + + built.stats.rejected_invalid + ); + let valid = input + .iter() + .filter(|r| !r.spiel_id.is_empty() && r.timestamp_ms > 0); + assert_eq!( + built.stats.edited, + valid.clone().filter(|r| r.edited_ms.is_some()).count() + ); + assert_eq!( + built.stats.edited_before_posted, + valid + .filter(|r| r.edited_ms.is_some_and(|e| e < r.timestamp_ms)) + .count() + ); + } +} + +/// Ordered projection of a `PostRow` (which is not `Ord`) for set comparisons. +type RowKey = (String, String, i64, i64, bool, bool, Option, String); + +fn row_key(r: &PostRow) -> RowKey { + ( + r.spiel_id.clone(), + r.key.clone(), + r.posted_at, + r.known_at, + r.is_bot, + r.is_edited, + r.user_id.clone(), + r.text.clone(), + ) +} + +fn visible(build: &PostsBuild, cutoff_us: i64) -> BTreeSet { + build + .newswire + .iter() + .chain(build.retail.iter()) + .filter(|r| r.known_at < cutoff_us) + .map(row_key) + .collect() +} + +fn known_at_us(r: &CeoPost) -> i64 { + r.edited_ms + .map_or(r.timestamp_ms, |e| e.max(r.timestamp_ms)) + * 1_000 +} + +#[test] +fn truncation_rows_visible_at_cutoff_are_reproduced_from_pre_cutoff_inputs_only() { + for seed in 0..20u64 { + let input = collision_fixture(0x7A0C_0000 + seed, 150, 60); + let full = build_posts(input.clone()).unwrap(); + assert!(!visible(&full, (BASE_MS + 2_000) * 1_000).is_empty()); + for step in 0..=6i64 { + let cutoff_us = (BASE_MS + 1_000 * step) * 1_000; + let truncated_input: Vec<_> = input + .iter() + .filter(|r| r.timestamp_ms > 0 && known_at_us(r) < cutoff_us) + .cloned() + .collect(); + let truncated = build_posts(truncated_input).unwrap(); + + let full_visible = visible(&full, cutoff_us); + let trunc_visible = visible(&truncated, cutoff_us); + // Every row the full build exposes before the cutoff must be derivable from data + // available before the cutoff (no future-dependent winner selection). + assert!( + full_visible.is_subset(&trunc_visible), + "seed {seed} cutoff step {step}: full build exposes rows not reproducible pre-cutoff: {:?}", + full_visible.difference(&trunc_visible).collect::>() + ); + // Truncated build never exposes anything at/after the cutoff. + assert!(truncated + .newswire + .iter() + .chain(truncated.retail.iter()) + .all(|r| r.known_at < cutoff_us)); + } + } +} + +#[test] +fn poison_future_edits_never_change_pre_cutoff_view_except_hiding_poisoned_ids() { + let cutoff_us = (BASE_MS + 3_000) * 1_000; + let far_future_ms = BASE_MS + 10 * 365 * 86_400_000; + for seed in 0..20u64 { + let input = collision_fixture(0x9015_0000 + seed, 120, 60); + let base = build_posts(input.clone()).unwrap(); + let base_visible = visible(&base, cutoff_us); + + // Poison half of the ids that are visible before the cutoff with an absurd future edit + // flagged as a wire release in a different channel. + let poisoned: BTreeSet = base_visible + .iter() + .map(|r| r.0.clone()) + .enumerate() + .filter(|(i, _)| i % 2 == 0) + .map(|(_, id)| id) + .collect(); + assert!( + !poisoned.is_empty(), + "seed {seed}: fixture must expose pre-cutoff rows" + ); + let mut poisoned_input = input.clone(); + for id in &poisoned { + poisoned_input.push(CeoPost { + key: "ch_poison".to_string(), + spiel_id: id.clone(), + timestamp_ms: BASE_MS, + edited_ms: Some(far_future_ms), + bot: Some("1".to_string()), + user_id: Some("poison".to_string()), + text: "POISON: future restatement".to_string(), + }); + } + let mut rng = Rng(seed); + rng.shuffle(&mut poisoned_input); + let after = build_posts(poisoned_input).unwrap(); + let after_visible = visible(&after, cutoff_us); + + let expected: BTreeSet<_> = base_visible + .iter() + .filter(|r| !poisoned.contains(&r.0)) + .cloned() + .collect(); + assert_eq!(after_visible, expected, "seed {seed}"); + assert!(after_visible.iter().all(|r| !r.7.starts_with("POISON"))); + assert_eq!( + after.stats.duplicates_dropped, + base.stats.duplicates_dropped + poisoned.len() + ); + } +} + +#[test] +fn overflow_row_anywhere_fails_build_for_every_input_order() { + let mut input = collision_fixture(0x0F10_0001, 40, 8); + input.push(CeoPost { + key: "ch_x".to_string(), + spiel_id: "sp_overflow".to_string(), + timestamp_ms: BASE_MS, + edited_ms: Some(i64::MAX / 1_000 + 1), + bot: None, + user_id: None, + text: "overflow".to_string(), + }); + let mut rng = Rng(7); + for _ in 0..16 { + let mut shuffled = input.clone(); + rng.shuffle(&mut shuffled); + let err = build_posts(shuffled).expect_err("overflow must fail the build"); + assert_eq!( + err, + PostsError::TimestampOverflow { + spiel_id: "sp_overflow".to_string(), + field: "edited_ms", + timestamp_ms: i64::MAX / 1_000 + 1, + } + ); + } +} From d43d987416c160a4b2586f2e6bd76cceee35782b Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 09:29:43 -0500 Subject: [PATCH 22/36] =?UTF-8?q?T-141:=20M2.3d=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20zero-copy=20`eodIntraday1M`=20BSON=20decoder=20+=20ch?= =?UTF-8?q?unked=20stream=20decode=20into=20`EodIntradayBar`=20(pure,=20no?= =?UTF-8?q?=20new=20crates,=20no=20live=20Mongo/QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 8 + tools/curate-etl/src/bson_eod_intraday.rs | 655 ++++++++++++++ .../curate-etl/src/bson_eod_intraday_tests.rs | 817 ++++++++++++++++++ tools/curate-etl/src/bson_stream.rs | 82 ++ tools/curate-etl/src/bson_stream_tests.rs | 171 +++- tools/curate-etl/src/lib.rs | 9 +- 6 files changed, 1737 insertions(+), 5 deletions(-) create mode 100644 tools/curate-etl/src/bson_eod_intraday.rs create mode 100644 tools/curate-etl/src/bson_eod_intraday_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 1d9b3436..78788231 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1566,6 +1566,14 @@ Measured locally (`2026-11-30`, two back-to-back offline runs on the final code - **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress. - **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks). +## Zero-Copy `eodIntraday1M` BSON Decoder (`M2.3d`) + +`src/bson_eod_intraday.rs` decodes raw `eodIntraday1M` MongoDB BSON documents in a single zero-copy forward pass (`RawEodIntradayBar<'a>`, `decode_eod_intraday_doc`, `decode_eod_intraday_bytes`, `decode_eod_intraday_buffer`, `BsonEodIntradayError`, `BsonEodIntradayDecodeStats`) with bounded-memory streaming helpers in `src/bson_stream.rs` (`decode_eod_intraday_chunks`, `decode_eod_intraday_stream`): + +- **Timestamp units:** `timestamp` is bar-start **UTC Unix seconds** (accepted in BSON `Int32`, `Int64`, or finite integral `Double` within `0..=i64::MAX / 1_000_000`) converted to UTC microseconds (`ts: i64`) via checked multiplication by `1_000_000`. It is bar start only (not a publication / `known_at` timestamp). +- **Split-adjusted passthrough:** `open`, `high`, `low`, `close` (finite and `> 0.0`) and `volume` (finite and `>= 0.0`, `-0.0` normalized to `+0.0`) are passed through untouched as the provider's retroactively split-adjusted values; downstream `bars_1m::build_bars_1m` performs split un-adjustment via `SplitTable`. +- **Conversion & zero-copy:** `eodSearchCode` is borrowed verbatim from the input `&RawDocument` slice; `into_eod_intraday_bar` / `try_into_eod_intraday_bar` map `(&'a str, i64)` directly into `bars_1m::EodIntradayBar`. + ## Exporting Input Files (`data-pipeline`) All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`: diff --git a/tools/curate-etl/src/bson_eod_intraday.rs b/tools/curate-etl/src/bson_eod_intraday.rs new file mode 100644 index 00000000..0cd039e8 --- /dev/null +++ b/tools/curate-etl/src/bson_eod_intraday.rs @@ -0,0 +1,655 @@ +//! Zero-copy raw BSON decoder for MongoDB `eodIntraday1M` documents (`M2.3d`). +//! +//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into +//! borrowed [`RawEodIntradayBar`] views without allocating a `String` or `bson::Document` per row. +//! Callers convert borrowed views into [`crate::bars_1m::EodIntradayBar`] via a caller-supplied +//! key mapper (for example [`crate::provider_mapping::ProviderMappingTable::resolve`] or an +//! interned integer symbol ID), keeping the 3.40B-document path free of per-row `String` +//! allocations. +//! +//! # Empirical Field Contract & Cited Sources +//! +//! Field names and semantics are grounded in the repository's ingestion writer, historical reader, +//! and empirical data contract: +//! - `apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts:565-585` (`fetchIntraday` +//! writes `symbol`, `exchange`, `eodSearchCode`, `datetime`, `timestamp`, `gmtoffset`, `open`, +//! `high`, `low`, `close`, `volume`, `source` into `eodIntraday1M`, keyed by +//! `['timestamp', 'eodSearchCode']`) +//! - `libs/trading-runtime/src/historical-storage.ts:265-298` (`timestamp` is bar-start **UTC +//! Unix seconds**, not a local `datetime` label and not a publication / `known_at` time) +//! - `design/DATA-CONTRACTS.md` §1: `eodIntraday1M` (~3.40B docs) stores retroactively +//! split-adjusted OHLC and volume. This decoder passes those split-adjusted values through +//! untouched; split un-adjustment happens downstream in [`crate::bars_1m::build_bars_1m`]. +//! +//! # Accepted BSON Representations & Daily-Decoder Conventions +//! +//! Where a rule is ambiguous, this module follows [`crate::bson_eod_prices`]: +//! - `eodSearchCode`: BSON UTF-8 `String`, borrowed verbatim (never trimmed). Empty or +//! whitespace-only strings are rejected as [`BsonEodIntradayError::EmptyField`]; non-string +//! values (including BSON `Null`) are rejected as [`BsonEodIntradayError::WrongType`]. +//! - `timestamp`: bar-start UTC Unix seconds in BSON `Int32`, `Int64`, or finite integral `Double` +//! within `0..=i64::MAX / 1_000_000`, converted to UTC microseconds via checked multiplication +//! by `1_000_000`. Non-numeric types (including `Null` and `DateTime`) are rejected as +//! [`BsonEodIntradayError::WrongType`]; negative, fractional, non-finite, or microsecond-overflow +//! values are rejected as [`BsonEodIntradayError::InvalidTimestamp`]. +//! - `open`, `high`, `low`, `close`: BSON `Double`, `Int32`, or `Int64`; must be finite and +//! strictly positive (`> 0.0`). Non-numeric types (including `Null`) are rejected as +//! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, `0.0`, `-0.0`, and `< 0.0` are rejected +//! as [`BsonEodIntradayError::InvalidNumber`]. +//! - `volume`: BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` is +//! normalized to `+0.0`). Non-numeric types (including `Null`) are rejected as +//! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, and `< 0.0` are rejected as +//! [`BsonEodIntradayError::InvalidNumber`]. +//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `datetime`, `gmtoffset`, `source`, nested +//! objects/arrays, etc.) are skipped without calling `elem.value()`. +//! - Error precedence: retains the first semantic error while continuing to scan remaining +//! top-level elements so any malformed BSON bytes surface immediately as `CorruptBson`. + +use std::error::Error; +use std::fmt; + +use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement}; +use bson::spec::ElementType; + +use crate::bars_1m::EodIntradayBar; +use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError}; + +const MICROS_PER_SECOND: i64 = 1_000_000; +/// Largest whole Unix-second timestamp that fits in signed `i64` microseconds (`9_223_372_036_854`). +pub(crate) const MAX_TIMESTAMP_SECONDS: i64 = i64::MAX / MICROS_PER_SECOND; + +/// Borrowed zero-copy view of a single decoded `eodIntraday1M` BSON document. +/// +/// Borrows `eod_search_code` directly from the underlying `&RawDocument` byte slice. +/// `open`, `high`, `low`, `close`, and `volume` are passed through as the provider's +/// split-adjusted values so [`crate::bars_1m::build_bars_1m`] can apply split un-adjustment. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RawEodIntradayBar<'a> { + pub eod_search_code: &'a str, + /// Bar start timestamp in UTC microseconds since the Unix epoch. + pub ts: i64, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub volume: f64, +} + +impl<'a> RawEodIntradayBar<'a> { + /// Converts this borrowed view into an [`EodIntradayBar`] using a caller-supplied key + /// mapper. + /// + /// `map_key` receives `(eod_search_code, ts)` (provider code and UTC bar-start microseconds) + /// so callers can resolve an integer `listing_id` or interned key without allocating a per-row + /// `String`. + #[inline] + pub fn into_eod_intraday_bar(self, map_key: F) -> EodIntradayBar + where + F: FnOnce(&'a str, i64) -> K, + { + EodIntradayBar { + key: map_key(self.eod_search_code, self.ts), + ts: self.ts, + open: self.open, + high: self.high, + low: self.low, + close: self.close, + volume: self.volume, + } + } + + /// Fallible conversion into [`EodIntradayBar`] using a caller-supplied key resolver. + #[inline] + pub fn try_into_eod_intraday_bar(self, map_key: F) -> Option> + where + F: FnOnce(&'a str, i64) -> Option, + { + let key = map_key(self.eod_search_code, self.ts)?; + Some(EodIntradayBar { + key, + ts: self.ts, + open: self.open, + high: self.high, + low: self.low, + close: self.close, + volume: self.volume, + }) + } +} + +/// Typed errors returned while decoding raw `eodIntraday1M` BSON documents or length-prefixed +/// buffers. +/// +/// Every field-level error names the offending BSON field in both its structure and `Display` +/// output; framing errors carry byte offsets; no input path panics. +#[derive(Debug, Clone, PartialEq)] +pub enum BsonEodIntradayError { + /// A required field was absent from the document. + MissingField { field: &'static str }, + /// A required string field was empty or contained only whitespace. + EmptyField { field: &'static str }, + /// A required field had an unexpected BSON element type (including `Null`). + WrongType { + field: &'static str, + actual: ElementType, + }, + /// `timestamp` was negative, non-integral, non-finite, or overflowed `i64` microseconds. + InvalidTimestamp { field: &'static str }, + /// An OHLC field was non-finite or `<= 0.0`, or `volume` was non-finite or `< 0.0`. + InvalidNumber { field: &'static str, value: f64 }, + /// Buffer ended before a complete 4-byte length prefix or declared document body. + TruncatedDocument { + offset: usize, + remaining: usize, + declared_len: Option, + }, + /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single + /// document slice). + CorruptDocumentLength { offset: usize, declared_len: i32 }, + /// Underlying BSON framing or element bytes were malformed. + CorruptBson { offset: usize, detail: String }, +} + +impl fmt::Display for BsonEodIntradayError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MissingField { field } => { + write!(f, "eodIntraday1M BSON missing required field '{field}'") + } + Self::EmptyField { field } => { + write!( + f, + "eodIntraday1M BSON field '{field}' must not be empty or blank" + ) + } + Self::WrongType { field, actual } => { + write!( + f, + "eodIntraday1M BSON field '{field}' has unexpected BSON type {actual:?}" + ) + } + Self::InvalidTimestamp { field } => { + write!( + f, + "eodIntraday1M BSON field '{field}' is not a valid non-negative integral Unix-seconds timestamp within i64 microsecond range" + ) + } + Self::InvalidNumber { field, value } => { + if *field == "volume" { + write!( + f, + "eodIntraday1M BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0" + ) + } else { + write!( + f, + "eodIntraday1M BSON field '{field}' has invalid numeric value {value}: must be finite and > 0" + ) + } + } + 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 BsonEodIntradayError {} + +#[inline] +fn map_framing_error(err: BsonEodPriceError) -> BsonEodIntradayError { + match err { + BsonEodPriceError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonEodIntradayError::TruncatedDocument { + offset, + remaining, + declared_len, + }, + BsonEodPriceError::CorruptDocumentLength { + offset, + declared_len, + } => BsonEodIntradayError::CorruptDocumentLength { + offset, + declared_len, + }, + BsonEodPriceError::CorruptBson { offset, detail } => { + BsonEodIntradayError::CorruptBson { offset, detail } + } + BsonEodPriceError::MissingField { field } => BsonEodIntradayError::MissingField { field }, + BsonEodPriceError::EmptyField { field } => BsonEodIntradayError::EmptyField { field }, + BsonEodPriceError::WrongType { field, actual } => { + BsonEodIntradayError::WrongType { field, actual } + } + BsonEodPriceError::MalformedDate { field } => { + BsonEodIntradayError::InvalidTimestamp { field } + } + BsonEodPriceError::InvalidNumber { field, value } => { + BsonEodIntradayError::InvalidNumber { field, value } + } + } +} + +/// Per-batch decode and rejection accounting for [`decode_eod_intraday_buffer`]. +/// +/// Conservation invariant: `rows_decoded + rejected_total() == docs_seen`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BsonEodIntradayDecodeStats { + pub docs_seen: usize, + pub rows_decoded: usize, + pub rejected_missing_field: usize, + pub rejected_empty_field: usize, + pub rejected_wrong_type: usize, + pub rejected_invalid_timestamp: usize, + pub rejected_invalid_number: usize, + pub rejected_corrupt_document: usize, +} + +impl BsonEodIntradayDecodeStats { + /// Total number of rejected documents across all error categories. + #[inline] + pub fn rejected_total(&self) -> usize { + self.rejected_missing_field + + self.rejected_empty_field + + self.rejected_wrong_type + + self.rejected_invalid_timestamp + + self.rejected_invalid_number + + self.rejected_corrupt_document + } + + /// Increments the rejection counter corresponding to `err`. + #[inline] + pub fn record_error(&mut self, err: &BsonEodIntradayError) { + match err { + BsonEodIntradayError::MissingField { .. } => self.rejected_missing_field += 1, + BsonEodIntradayError::EmptyField { .. } => self.rejected_empty_field += 1, + BsonEodIntradayError::WrongType { .. } => self.rejected_wrong_type += 1, + BsonEodIntradayError::InvalidTimestamp { .. } => self.rejected_invalid_timestamp += 1, + BsonEodIntradayError::InvalidNumber { .. } => self.rejected_invalid_number += 1, + BsonEodIntradayError::TruncatedDocument { .. } + | BsonEodIntradayError::CorruptDocumentLength { .. } + | BsonEodIntradayError::CorruptBson { .. } => self.rejected_corrupt_document += 1, + } + } + + /// Accumulates counters from another batch into `self`. + #[inline] + pub fn merge(&mut self, other: &Self) { + self.docs_seen += other.docs_seen; + self.rows_decoded += other.rows_decoded; + self.rejected_missing_field += other.rejected_missing_field; + self.rejected_empty_field += other.rejected_empty_field; + self.rejected_wrong_type += other.rejected_wrong_type; + self.rejected_invalid_timestamp += other.rejected_invalid_timestamp; + self.rejected_invalid_number += other.rejected_invalid_number; + self.rejected_corrupt_document += other.rejected_corrupt_document; + } +} + +impl std::ops::AddAssign for BsonEodIntradayDecodeStats { + #[inline] + fn add_assign(&mut self, rhs: Self) { + self.merge(&rhs); + } +} + +#[inline] +fn decode_element_value<'a>( + field: &'static str, + elem: RawElement<'a>, + offset: usize, +) -> Result, BsonEodIntradayError> { + elem.value().map_err(|err| BsonEodIntradayError::CorruptBson { + offset, + detail: format!("field '{field}': {err}"), + }) +} + +#[inline] +fn decode_timestamp_seconds_to_micros(val: RawBsonRef<'_>) -> Result { + let secs = match val { + RawBsonRef::Int32(v) => { + if v < 0 { + return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }); + } + i64::from(v) + } + RawBsonRef::Int64(v) => { + if v < 0 { + return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }); + } + v + } + RawBsonRef::Double(v) => { + // `MAX_TIMESTAMP_SECONDS` (9_223_372_036_854 < 2^44) is well within `f64`'s exact + // 53-bit integer range, so both the upper bound and the cast are exact. + if !v.is_finite() + || v < 0.0 + || v.fract() != 0.0 + || v > MAX_TIMESTAMP_SECONDS as f64 + { + return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }); + } + v as i64 + } + other => { + return Err(BsonEodIntradayError::WrongType { + field: "timestamp", + actual: other.element_type(), + }); + } + }; + + secs.checked_mul(MICROS_PER_SECOND) + .ok_or(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }) +} + +#[inline] +fn decode_positive_number( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::Double(v) => { + if !v.is_finite() || v <= 0.0 { + return Err(BsonEodIntradayError::InvalidNumber { field, value: v }); + } + Ok(v) + } + RawBsonRef::Int32(v) => { + if v <= 0 { + return Err(BsonEodIntradayError::InvalidNumber { + field, + value: f64::from(v), + }); + } + Ok(f64::from(v)) + } + RawBsonRef::Int64(v) => { + if v <= 0 { + return Err(BsonEodIntradayError::InvalidNumber { + field, + value: v as f64, + }); + } + Ok(v as f64) + } + other => Err(BsonEodIntradayError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +#[inline] +fn decode_non_negative_number( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::Double(v) => { + if !v.is_finite() || v < 0.0 { + return Err(BsonEodIntradayError::InvalidNumber { field, value: v }); + } + if v == 0.0 { + Ok(0.0) + } else { + Ok(v) + } + } + RawBsonRef::Int32(v) => { + if v < 0 { + return Err(BsonEodIntradayError::InvalidNumber { + field, + value: f64::from(v), + }); + } + Ok(f64::from(v)) + } + RawBsonRef::Int64(v) => { + if v < 0 { + return Err(BsonEodIntradayError::InvalidNumber { + field, + value: v as f64, + }); + } + Ok(v as f64) + } + other => Err(BsonEodIntradayError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +fn decode_eod_intraday_doc_at<'a>( + doc: &'a RawDocument, + offset: usize, +) -> Result, BsonEodIntradayError> { + let mut eod_search_code: Option<&'a str> = None; + let mut ts: Option = None; + let mut open: Option = None; + let mut high: Option = None; + let mut low: Option = None; + let mut close: Option = None; + let mut volume: Option = None; + let mut first_semantic_err: Option = None; + + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonEodIntradayError::CorruptBson { + offset, + detail: err.to_string(), + })?; + let key = elem.key(); + + if key == cstr!("eodSearchCode") { + match decode_element_value("eodSearchCode", elem, offset)? { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + if first_semantic_err.is_none() { + first_semantic_err = Some(BsonEodIntradayError::EmptyField { + field: "eodSearchCode", + }); + } + } else { + eod_search_code = Some(s); + } + } + other => { + if first_semantic_err.is_none() { + first_semantic_err = Some(BsonEodIntradayError::WrongType { + field: "eodSearchCode", + actual: other.element_type(), + }); + } + } + } + } else if key == cstr!("timestamp") { + let val = decode_element_value("timestamp", elem, offset)?; + match decode_timestamp_seconds_to_micros(val) { + Ok(micros) => ts = Some(micros), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("open") { + let val = decode_element_value("open", elem, offset)?; + match decode_positive_number("open", val) { + Ok(v) => open = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("high") { + let val = decode_element_value("high", elem, offset)?; + match decode_positive_number("high", val) { + Ok(v) => high = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("low") { + let val = decode_element_value("low", elem, offset)?; + match decode_positive_number("low", val) { + Ok(v) => low = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("close") { + let val = decode_element_value("close", elem, offset)?; + match decode_positive_number("close", val) { + Ok(v) => close = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("volume") { + let val = decode_element_value("volume", elem, offset)?; + match decode_non_negative_number("volume", val) { + Ok(v) => volume = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } + // Unknown extra fields (`_id`, `symbol`, `exchange`, `datetime`, `gmtoffset`, `source`, + // etc.) are skipped without calling `elem.value()`. + } + + if let Some(err) = first_semantic_err { + return Err(err); + } + + let Some(eod_search_code) = eod_search_code else { + return Err(BsonEodIntradayError::MissingField { + field: "eodSearchCode", + }); + }; + let Some(ts) = ts else { + return Err(BsonEodIntradayError::MissingField { field: "timestamp" }); + }; + let Some(open) = open else { + return Err(BsonEodIntradayError::MissingField { field: "open" }); + }; + let Some(high) = high else { + return Err(BsonEodIntradayError::MissingField { field: "high" }); + }; + let Some(low) = low else { + return Err(BsonEodIntradayError::MissingField { field: "low" }); + }; + let Some(close) = close else { + return Err(BsonEodIntradayError::MissingField { field: "close" }); + }; + let Some(volume) = volume else { + return Err(BsonEodIntradayError::MissingField { field: "volume" }); + }; + + Ok(RawEodIntradayBar { + eod_search_code, + ts, + open, + high, + low, + close, + volume, + }) +} + +/// Decodes a single `&RawDocument` representing an `eodIntraday1M` MongoDB document in one forward +/// pass without allocating a `String` or owned `bson::Document`. +#[inline] +pub fn decode_eod_intraday_doc<'a>( + doc: &'a RawDocument, +) -> Result, BsonEodIntradayError> { + decode_eod_intraday_doc_at(doc, 0) +} + +/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed +/// [`RawEodIntradayBar`]. +pub fn decode_eod_intraday_bytes<'a>( + bytes: &'a [u8], +) -> Result, BsonEodIntradayError> { + let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; + decode_eod_intraday_doc_at(doc, 0) +} + +/// Streams a concatenated length-prefixed BSON buffer through [`decode_eod_intraday_doc`], +/// invoking `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected +/// document without aborting the stream on per-document errors. +/// +/// Always maintains `stats.rows_decoded + stats.rejected_total() == stats.docs_seen`. +pub fn decode_eod_intraday_buffer<'a, F, E>( + buf: &'a [u8], + mut on_bar: F, + mut on_error: E, +) -> BsonEodIntradayDecodeStats +where + F: FnMut(RawEodIntradayBar<'a>), + E: FnMut(usize, BsonEodIntradayError), +{ + let mut stats = BsonEodIntradayDecodeStats::default(); + let mut iter = iter_raw_bson_docs(buf); + + while let Some(item) = iter.next_with_offset() { + stats.docs_seen += 1; + match item { + Ok((doc_offset, doc)) => match decode_eod_intraday_doc_at(doc, doc_offset) { + Ok(bar) => { + stats.rows_decoded += 1; + on_bar(bar); + } + Err(err) => { + stats.record_error(&err); + on_error(doc_offset, err); + } + }, + Err((doc_offset, err)) => { + let mapped = map_framing_error(err); + stats.record_error(&mapped); + on_error(doc_offset, mapped); + } + } + } + + stats +} + +#[cfg(test)] +#[path = "bson_eod_intraday_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bson_eod_intraday_tests.rs b/tools/curate-etl/src/bson_eod_intraday_tests.rs new file mode 100644 index 00000000..099f760b --- /dev/null +++ b/tools/curate-etl/src/bson_eod_intraday_tests.rs @@ -0,0 +1,817 @@ +use bson::oid::ObjectId; +use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; +use bson::spec::ElementType; +use bson::DateTime; + +use super::*; +use crate::bars_1m::{build_bars_1m, IntradaySession, BARS_1M_SOURCE_EOD}; +use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).unwrap() +} + +fn make_valid_doc( + code: &str, + timestamp_sec: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("timestamp"), timestamp_sec); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc +} + +fn make_doc_with_timestamp(timestamp: RawBsonRef<'_>) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("timestamp"), timestamp); + doc.append(cstr!("open"), 120.15_f64); + doc.append(cstr!("high"), 120.42_f64); + doc.append(cstr!("low"), 120.05_f64); + doc.append(cstr!("close"), 120.38_f64); + doc.append(cstr!("volume"), 842_500.0_f64); + doc +} + +fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { + let diff = (actual - expected).abs(); + let scale = expected.abs().max(1.0); + assert!( + diff <= rel_tol * scale, + "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" + ); +} + +#[test] +fn decodes_nvda_fixture_across_int32_int64_double_timestamps_and_ignores_metadata() { + const TS_SEC: i32 = 1_717_767_000; + const EXPECTED_TS_MICROS: i64 = 1_717_767_000_000_000; + + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("provider"), "eodhd"); + nested.append(cstr!("interval"), "1m"); + + let mut tags = RawArrayBuf::new(); + tags.push("us"); + tags.push("intraday"); + + let mut doc_i32 = RawDocumentBuf::new(); + doc_i32.append( + cstr!("_id"), + ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), + ); + doc_i32.append(cstr!("symbol"), "NVDA"); + doc_i32.append(cstr!("exchange"), "US"); + doc_i32.append(cstr!("eodSearchCode"), "NVDA.US"); + doc_i32.append(cstr!("datetime"), "2024-06-07 13:30:00"); + doc_i32.append(cstr!("timestamp"), TS_SEC); + doc_i32.append(cstr!("gmtoffset"), 0_i32); + doc_i32.append(cstr!("open"), 119.77_f64); + doc_i32.append(cstr!("high"), 121.692_f64); + doc_i32.append(cstr!("low"), 118.022_f64); + doc_i32.append(cstr!("close"), 120.888_f64); + doc_i32.append(cstr!("volume"), 412_390.0_f64); + doc_i32.append(cstr!("source"), "eod"); + doc_i32.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + doc_i32.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); + + let bar_i32 = decode_eod_intraday_doc(&doc_i32).unwrap(); + assert_eq!(bar_i32.eod_search_code, "NVDA.US"); + assert_eq!(bar_i32.ts, EXPECTED_TS_MICROS); + assert_eq!(bar_i32.open.to_bits(), 119.77_f64.to_bits()); + assert_eq!(bar_i32.high.to_bits(), 121.692_f64.to_bits()); + assert_eq!(bar_i32.low.to_bits(), 118.022_f64.to_bits()); + assert_eq!(bar_i32.close.to_bits(), 120.888_f64.to_bits()); + assert_eq!(bar_i32.volume.to_bits(), 412_390.0_f64.to_bits()); + + // decode_eod_intraday_bytes matches decode_eod_intraday_doc bit-for-bit. + let from_bytes = decode_eod_intraday_bytes(doc_i32.as_bytes()).unwrap(); + assert_eq!(from_bytes, bar_i32); + + // Same document with timestamp as Int64 and as integral Double decodes identically. + let mut doc_i64 = RawDocumentBuf::new(); + doc_i64.append(cstr!("eodSearchCode"), "NVDA.US"); + doc_i64.append(cstr!("timestamp"), i64::from(TS_SEC)); + doc_i64.append(cstr!("open"), 119.77_f64); + doc_i64.append(cstr!("high"), 121.692_f64); + doc_i64.append(cstr!("low"), 118.022_f64); + doc_i64.append(cstr!("close"), 120.888_f64); + doc_i64.append(cstr!("volume"), 412_390.0_f64); + + let mut doc_f64 = RawDocumentBuf::new(); + doc_f64.append(cstr!("eodSearchCode"), "NVDA.US"); + doc_f64.append(cstr!("timestamp"), f64::from(TS_SEC)); + doc_f64.append(cstr!("open"), 119.77_f64); + doc_f64.append(cstr!("high"), 121.692_f64); + doc_f64.append(cstr!("low"), 118.022_f64); + doc_f64.append(cstr!("close"), 120.888_f64); + doc_f64.append(cstr!("volume"), 412_390.0_f64); + + let bar_i64 = decode_eod_intraday_doc(&doc_i64).unwrap(); + let bar_f64 = decode_eod_intraday_doc(&doc_f64).unwrap(); + assert_eq!(bar_i64, bar_i32); + assert_eq!(bar_f64, bar_i32); + + // Verify into_eod_intraday_bar and try_into_eod_intraday_bar pass exact (code, ts). + let mut seen_into: Option<(&str, i64)> = None; + let mapped = bar_i32.into_eod_intraday_bar(|code, ts| { + seen_into = Some((code, ts)); + 42_u64 + }); + assert_eq!(seen_into, Some(("NVDA.US", EXPECTED_TS_MICROS))); + assert_eq!(mapped.key, 42_u64); + assert_eq!(mapped.ts, EXPECTED_TS_MICROS); + assert_eq!(mapped.close.to_bits(), 120.888_f64.to_bits()); + + let mut seen_try_some: Option<(&str, i64)> = None; + let try_some = bar_i32.try_into_eod_intraday_bar(|code, ts| { + seen_try_some = Some((code, ts)); + Some(99_u64) + }); + assert_eq!(seen_try_some, Some(("NVDA.US", EXPECTED_TS_MICROS))); + assert_eq!(try_some.unwrap().key, 99_u64); + + let try_none: Option> = bar_i32.try_into_eod_intraday_bar(|code, ts| { + assert_eq!(code, "NVDA.US"); + assert_eq!(ts, EXPECTED_TS_MICROS); + None + }); + assert!(try_none.is_none()); +} + +#[test] +fn borrows_eod_search_code_zero_copy_from_input_buffer() { + let doc = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0); + let bytes = doc.as_bytes(); + let buf_start = bytes.as_ptr() as usize; + let buf_end = buf_start + bytes.len(); + + let bar = decode_eod_intraday_bytes(bytes).unwrap(); + let code_start = bar.eod_search_code.as_ptr() as usize; + let code_end = code_start + bar.eod_search_code.len(); + assert!( + code_start >= buf_start && code_end <= buf_end, + "expected eod_search_code pointer {code_start:#x}..{code_end:#x} inside input buffer {buf_start:#x}..{buf_end:#x}" + ); + assert_eq!(bar.eod_search_code, "NVDA.US"); +} + +#[test] +fn accepts_mixed_numeric_types_zero_volume_and_timestamp_boundaries() { + let mut mixed = RawDocumentBuf::new(); + mixed.append(cstr!("eodSearchCode"), "SHOP.TO"); + mixed.append(cstr!("timestamp"), 0_i32); + mixed.append(cstr!("open"), 100_i32); + mixed.append(cstr!("high"), 105_i64); + mixed.append(cstr!("low"), 99.5_f64); + mixed.append(cstr!("close"), 104_i32); + mixed.append(cstr!("volume"), 5_000_000_000_i64); + + let bar = decode_eod_intraday_doc(&mixed).unwrap(); + assert_eq!(bar.eod_search_code, "SHOP.TO"); + assert_eq!(bar.ts, 0); + assert_eq!(bar.open.to_bits(), 100.0_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 105.0_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 99.5_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 104.0_f64.to_bits()); + assert_eq!(bar.volume.to_bits(), 5_000_000_000.0_f64.to_bits()); + + // Epoch zero in Int32, Int64, Double (+0.0 and -0.0). + for zero_ts in [ + RawBsonRef::Int32(0), + RawBsonRef::Int64(0), + RawBsonRef::Double(0.0), + RawBsonRef::Double(-0.0), + ] { + let doc = make_doc_with_timestamp(zero_ts); + let decoded = decode_eod_intraday_doc(&doc).unwrap(); + assert_eq!(decoded.ts, 0); + } + + // Largest accepted whole second in Int64 and Double. + let expected_max_micros = MAX_TIMESTAMP_SECONDS * 1_000_000; + for max_ts in [ + RawBsonRef::Int64(MAX_TIMESTAMP_SECONDS), + RawBsonRef::Double(MAX_TIMESTAMP_SECONDS as f64), + ] { + let doc = make_doc_with_timestamp(max_ts); + let decoded = decode_eod_intraday_doc(&doc).unwrap(); + assert_eq!(decoded.ts, expected_max_micros); + } + + // Zero volume in Double (+0.0, -0.0), Int32 (0), Int64 (0) normalizes to +0.0. + for zero_vol in [ + RawBsonRef::Double(0.0), + RawBsonRef::Double(-0.0), + RawBsonRef::Int32(0), + RawBsonRef::Int64(0), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("timestamp"), 1_717_767_000_i64); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.5_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), zero_vol); + + let decoded = decode_eod_intraday_doc(&doc).unwrap(); + assert_eq!(decoded.volume.to_bits(), 0.0_f64.to_bits()); + } +} + +#[test] +fn rejects_invalid_eod_search_code_variants_with_matching_stats() { + // Missing eodSearchCode + let mut missing = RawDocumentBuf::new(); + missing.append(cstr!("timestamp"), 1_717_767_000_i64); + missing.append(cstr!("open"), 10.0_f64); + missing.append(cstr!("high"), 11.0_f64); + missing.append(cstr!("low"), 9.0_f64); + missing.append(cstr!("close"), 10.5_f64); + missing.append(cstr!("volume"), 100.0_f64); + let err = decode_eod_intraday_doc(&missing).unwrap_err(); + assert_eq!( + err, + BsonEodIntradayError::MissingField { + field: "eodSearchCode" + } + ); + let mut stats = BsonEodIntradayDecodeStats::default(); + stats.record_error(&err); + assert_eq!(stats.rejected_missing_field, 1); + assert_eq!(stats.rejected_total(), 1); + + // Empty and whitespace-only keys + for blank in ["", " ", "\t\n\r "] { + let doc = make_valid_doc(blank, 1_717_767_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let err = decode_eod_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodIntradayError::EmptyField { + field: "eodSearchCode" + } + ); + let mut s = BsonEodIntradayDecodeStats::default(); + s.record_error(&err); + assert_eq!(s.rejected_empty_field, 1); + assert_eq!(s.rejected_total(), 1); + } + + // Wrong BSON types for eodSearchCode + let wrong_types: [(RawBsonRef<'_>, ElementType); 3] = [ + (RawBsonRef::Null, ElementType::Null), + (RawBsonRef::Int32(123), ElementType::Int32), + (RawBsonRef::Boolean(true), ElementType::Boolean), + ]; + for (val, expected_type) in wrong_types { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), val); + doc.append(cstr!("timestamp"), 1_717_767_000_i64); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 100.0_f64); + let err = decode_eod_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodIntradayError::WrongType { + field: "eodSearchCode", + actual: expected_type, + } + ); + let mut s = BsonEodIntradayDecodeStats::default(); + s.record_error(&err); + assert_eq!(s.rejected_wrong_type, 1); + assert_eq!(s.rejected_total(), 1); + } +} + +#[test] +fn rejects_invalid_timestamp_variants_with_matching_stats() { + // Missing timestamp + let mut missing = RawDocumentBuf::new(); + missing.append(cstr!("eodSearchCode"), "NVDA.US"); + missing.append(cstr!("open"), 10.0_f64); + missing.append(cstr!("high"), 11.0_f64); + missing.append(cstr!("low"), 9.0_f64); + missing.append(cstr!("close"), 10.5_f64); + missing.append(cstr!("volume"), 100.0_f64); + let err = decode_eod_intraday_doc(&missing).unwrap_err(); + assert_eq!(err, BsonEodIntradayError::MissingField { field: "timestamp" }); + let mut stats = BsonEodIntradayDecodeStats::default(); + stats.record_error(&err); + assert_eq!(stats.rejected_missing_field, 1); + assert_eq!(stats.rejected_total(), 1); + + // Wrong BSON types for timestamp + let wrong_types: [(RawBsonRef<'_>, ElementType); 4] = [ + (RawBsonRef::Null, ElementType::Null), + (RawBsonRef::String("1717767000"), ElementType::String), + ( + RawBsonRef::DateTime(DateTime::from_millis(1_717_767_000_000)), + ElementType::DateTime, + ), + (RawBsonRef::Boolean(false), ElementType::Boolean), + ]; + for (val, expected_type) in wrong_types { + let doc = make_doc_with_timestamp(val); + let err = decode_eod_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodIntradayError::WrongType { + field: "timestamp", + actual: expected_type, + } + ); + let mut s = BsonEodIntradayDecodeStats::default(); + s.record_error(&err); + assert_eq!(s.rejected_wrong_type, 1); + assert_eq!(s.rejected_total(), 1); + } + + // Invalid numeric timestamps: fractional, NaN, inf, -inf, negative, overflowing + let invalid_timestamps: [RawBsonRef<'_>; 11] = [ + RawBsonRef::Double(1_717_767_000.5), + RawBsonRef::Double(0.25), + RawBsonRef::Double(f64::NAN), + RawBsonRef::Double(f64::INFINITY), + RawBsonRef::Double(f64::NEG_INFINITY), + RawBsonRef::Int32(-1), + RawBsonRef::Int64(-1), + RawBsonRef::Double(-1.0), + RawBsonRef::Int64(MAX_TIMESTAMP_SECONDS + 1), + RawBsonRef::Int64(i64::MAX), + RawBsonRef::Double((MAX_TIMESTAMP_SECONDS + 1) as f64), + ]; + for bad_ts in invalid_timestamps { + let doc = make_doc_with_timestamp(bad_ts); + let err = decode_eod_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodIntradayError::InvalidTimestamp { field: "timestamp" } + ); + let mut s = BsonEodIntradayDecodeStats::default(); + s.record_error(&err); + assert_eq!(s.rejected_invalid_timestamp, 1); + assert_eq!(s.rejected_total(), 1); + } +} + +#[test] +fn rejects_invalid_ohlc_and_volume_variants_with_matching_stats() { + let ohlc_fields = ["open", "high", "low", "close"]; + + for target in ohlc_fields { + // Missing field + let mut missing = RawDocumentBuf::new(); + missing.append(cstr!("eodSearchCode"), "NVDA.US"); + missing.append(cstr!("timestamp"), 1_717_767_000_i64); + for (f, key) in [ + ("open", cstr!("open")), + ("high", cstr!("high")), + ("low", cstr!("low")), + ("close", cstr!("close")), + ("volume", cstr!("volume")), + ] { + if f != target { + missing.append(key, 10.0_f64); + } + } + let err = decode_eod_intraday_doc(&missing).unwrap_err(); + assert_eq!(err, BsonEodIntradayError::MissingField { field: target }); + let mut s = BsonEodIntradayDecodeStats::default(); + s.record_error(&err); + assert_eq!(s.rejected_missing_field, 1); + assert_eq!(s.rejected_total(), 1); + + let build_with_field = |val: RawBsonRef<'_>| { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("timestamp"), 1_717_767_000_i64); + for (name, key) in [ + ("open", cstr!("open")), + ("high", cstr!("high")), + ("low", cstr!("low")), + ("close", cstr!("close")), + ("volume", cstr!("volume")), + ] { + if name == target { + doc.append(key, val); + } else { + doc.append(key, 10.0_f64); + } + } + doc + }; + + // Null and wrong types -> WrongType + for (val, expected_type) in [ + (RawBsonRef::Null, ElementType::Null), + (RawBsonRef::String("10.0"), ElementType::String), + (RawBsonRef::Boolean(true), ElementType::Boolean), + ] { + let doc = build_with_field(val); + let err = decode_eod_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodIntradayError::WrongType { + field: target, + actual: expected_type, + } + ); + let mut st = BsonEodIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_wrong_type, 1); + assert_eq!(st.rejected_total(), 1); + } + + // Non-finite, zero, and negative -> InvalidNumber + for bad_num in [ + RawBsonRef::Double(f64::NAN), + RawBsonRef::Double(f64::INFINITY), + RawBsonRef::Double(f64::NEG_INFINITY), + RawBsonRef::Double(0.0), + RawBsonRef::Double(-0.0), + RawBsonRef::Double(-1.25), + RawBsonRef::Int32(0), + RawBsonRef::Int32(-5), + RawBsonRef::Int64(0), + RawBsonRef::Int64(-5), + ] { + let doc = build_with_field(bad_num); + let err = decode_eod_intraday_doc(&doc).unwrap_err(); + match &err { + BsonEodIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, target), + other => panic!("expected InvalidNumber for {target}, got {other:?}"), + } + let mut st = BsonEodIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_invalid_number, 1); + assert_eq!(st.rejected_total(), 1); + } + } + + // Volume: missing, Null/wrong-type, negative/NaN/inf + let mut missing_vol = RawDocumentBuf::new(); + missing_vol.append(cstr!("eodSearchCode"), "NVDA.US"); + missing_vol.append(cstr!("timestamp"), 1_717_767_000_i64); + missing_vol.append(cstr!("open"), 10.0_f64); + missing_vol.append(cstr!("high"), 11.0_f64); + missing_vol.append(cstr!("low"), 9.0_f64); + missing_vol.append(cstr!("close"), 10.5_f64); + let err = decode_eod_intraday_doc(&missing_vol).unwrap_err(); + assert_eq!(err, BsonEodIntradayError::MissingField { field: "volume" }); + + let build_with_vol = |val: RawBsonRef<'_>| { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("timestamp"), 1_717_767_000_i64); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), val); + doc + }; + + for (val, expected_type) in [ + (RawBsonRef::Null, ElementType::Null), + (RawBsonRef::String("100"), ElementType::String), + (RawBsonRef::Boolean(false), ElementType::Boolean), + ] { + let doc = build_with_vol(val); + let err = decode_eod_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodIntradayError::WrongType { + field: "volume", + actual: expected_type, + } + ); + let mut st = BsonEodIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_wrong_type, 1); + assert_eq!(st.rejected_total(), 1); + } + + for bad_vol in [ + RawBsonRef::Double(-0.01), + RawBsonRef::Double(f64::NAN), + RawBsonRef::Double(f64::INFINITY), + RawBsonRef::Double(f64::NEG_INFINITY), + RawBsonRef::Int32(-1), + RawBsonRef::Int64(-1), + ] { + let doc = build_with_vol(bad_vol); + let err = decode_eod_intraday_doc(&doc).unwrap_err(); + match &err { + BsonEodIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, "volume"), + other => panic!("expected InvalidNumber for volume, got {other:?}"), + } + let mut st = BsonEodIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_invalid_number, 1); + assert_eq!(st.rejected_total(), 1); + } +} + +#[test] +fn rejects_truncated_and_corrupt_single_doc_bytes_without_panicking() { + // Truncated header (< 4 bytes) + assert_eq!( + decode_eod_intraday_bytes(&[0x10, 0x00]), + Err(BsonEodIntradayError::TruncatedDocument { + offset: 0, + remaining: 2, + declared_len: None, + }) + ); + + // Declared length < 5 + assert_eq!( + decode_eod_intraday_bytes(&[4, 0, 0, 0]), + Err(BsonEodIntradayError::CorruptDocumentLength { + offset: 0, + declared_len: 4, + }) + ); + + // Truncated body (declared_len > remaining) + let valid = make_valid_doc("NVDA.US", 1_717_767_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let truncated = &valid.as_bytes()[..valid.as_bytes().len() - 3]; + assert_eq!( + decode_eod_intraday_bytes(truncated), + Err(BsonEodIntradayError::TruncatedDocument { + offset: 0, + remaining: truncated.len(), + declared_len: Some(valid.as_bytes().len() as i32), + }) + ); + + // Trailing extra bytes on single-doc decode -> CorruptDocumentLength + let mut with_trailing = valid.as_bytes().to_vec(); + with_trailing.push(0x00); + assert_eq!( + decode_eod_intraday_bytes(&with_trailing), + Err(BsonEodIntradayError::CorruptDocumentLength { + offset: 0, + declared_len: valid.as_bytes().len() as i32, + }) + ); + + // Malformed BSON (missing trailing null terminator) + let mut bad_term = valid.as_bytes().to_vec(); + *bad_term.last_mut().unwrap() = 0xFF; + match decode_eod_intraday_bytes(&bad_term) { + Err(BsonEodIntradayError::CorruptBson { offset: 0, .. }) => {} + other => panic!("expected CorruptBson, got {other:?}"), + } +} + +#[test] +fn decodes_mixed_buffer_preserving_order_recovering_past_corrupt_frame_and_merging_stats() { + let valid1 = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0); + let empty_key = make_valid_doc(" ", 1_717_767_060, 120.5, 121.0, 120.0, 120.8, 500.0); + let bad_ts = make_doc_with_timestamp(RawBsonRef::Double(1_717_767_120.5)); + let bad_price = make_valid_doc("NVDA.US", 1_717_767_180, 0.0, 121.0, 119.0, 120.0, 200.0); + + let mut wrong_type = RawDocumentBuf::new(); + wrong_type.append(cstr!("eodSearchCode"), "NVDA.US"); + wrong_type.append(cstr!("timestamp"), 1_717_767_240_i64); + wrong_type.append(cstr!("open"), RawBsonRef::Null); + wrong_type.append(cstr!("high"), 121.0_f64); + wrong_type.append(cstr!("low"), 119.0_f64); + wrong_type.append(cstr!("close"), 120.0_f64); + wrong_type.append(cstr!("volume"), 200.0_f64); + + let mut missing_field = RawDocumentBuf::new(); + missing_field.append(cstr!("eodSearchCode"), "NVDA.US"); + missing_field.append(cstr!("timestamp"), 1_717_767_300_i64); + missing_field.append(cstr!("open"), 120.0_f64); + missing_field.append(cstr!("high"), 121.0_f64); + missing_field.append(cstr!("low"), 119.0_f64); + missing_field.append(cstr!("close"), 120.0_f64); + + // Valid length-framed doc whose trailing terminator is corrupt -> CorruptBson, but buffer + // iteration recovers and decodes valid2 after it. + let mut corrupt_framed = valid1.as_bytes().to_vec(); + *corrupt_framed.last_mut().unwrap() = 0xAA; + + let valid2 = make_valid_doc("AAPL.US", 1_717_767_360, 195.0, 196.0, 194.5, 195.5, 0.0); + + let mut buf = Vec::new(); + buf.extend_from_slice(valid1.as_bytes()); + let off_empty = buf.len(); + buf.extend_from_slice(empty_key.as_bytes()); + let off_bad_ts = buf.len(); + buf.extend_from_slice(bad_ts.as_bytes()); + let off_bad_price = buf.len(); + buf.extend_from_slice(bad_price.as_bytes()); + let off_wrong_type = buf.len(); + buf.extend_from_slice(wrong_type.as_bytes()); + let off_missing = buf.len(); + buf.extend_from_slice(missing_field.as_bytes()); + let off_corrupt = buf.len(); + buf.extend_from_slice(&corrupt_framed); + buf.extend_from_slice(valid2.as_bytes()); + + let mut rows = Vec::new(); + let mut errors = Vec::new(); + let stats = decode_eod_intraday_buffer( + &buf, + |bar| rows.push((bar.eod_search_code.to_owned(), bar.ts, bar.close, bar.volume)), + |offset, err| errors.push((offset, err)), + ); + + assert_eq!(rows.len(), 2); + assert_eq!(rows[0], ("NVDA.US".to_owned(), 1_717_767_000_000_000, 120.5, 1000.0)); + assert_eq!(rows[1], ("AAPL.US".to_owned(), 1_717_767_360_000_000, 195.5, 0.0)); + + assert_eq!(stats.docs_seen, 8); + assert_eq!(stats.rows_decoded, 2); + assert_eq!(stats.rejected_empty_field, 1); + assert_eq!(stats.rejected_invalid_timestamp, 1); + assert_eq!(stats.rejected_invalid_number, 1); + assert_eq!(stats.rejected_wrong_type, 1); + assert_eq!(stats.rejected_missing_field, 1); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.rejected_total(), 6); + assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); + + assert_eq!(errors.len(), 6); + assert_eq!(errors[0].0, off_empty); + assert_eq!(errors[1].0, off_bad_ts); + assert_eq!(errors[2].0, off_bad_price); + assert_eq!(errors[3].0, off_wrong_type); + assert_eq!(errors[4].0, off_missing); + assert_eq!(errors[5].0, off_corrupt); + assert!(matches!( + errors[5].1, + BsonEodIntradayError::CorruptBson { offset, .. } if offset == off_corrupt + )); + + // Verify BsonEodIntradayDecodeStats::merge sums every counter. + let mut merged = BsonEodIntradayDecodeStats { + docs_seen: 10, + rows_decoded: 4, + rejected_missing_field: 1, + rejected_empty_field: 1, + rejected_wrong_type: 1, + rejected_invalid_timestamp: 1, + rejected_invalid_number: 1, + rejected_corrupt_document: 1, + }; + merged.merge(&stats); + assert_eq!( + merged, + BsonEodIntradayDecodeStats { + docs_seen: 18, + rows_decoded: 6, + rejected_missing_field: 2, + rejected_empty_field: 2, + rejected_wrong_type: 2, + rejected_invalid_timestamp: 2, + rejected_invalid_number: 2, + rejected_corrupt_document: 2, + } + ); + assert_eq!(merged.docs_seen, merged.rows_decoded + merged.rejected_total()); + + // Truncated tail stops cleanly and still maintains conservation invariant. + let mut with_trunc = buf.clone(); + let trunc_off = with_trunc.len(); + with_trunc.extend_from_slice(&valid2.as_bytes()[..10]); + let mut trunc_errs = Vec::new(); + let trunc_stats = decode_eod_intraday_buffer( + &with_trunc, + |_| {}, + |off, err| trunc_errs.push((off, err)), + ); + assert_eq!(trunc_stats.docs_seen, 9); + assert_eq!(trunc_stats.rows_decoded, 2); + assert_eq!(trunc_stats.rejected_corrupt_document, 2); + assert_eq!( + trunc_stats.docs_seen, + trunc_stats.rows_decoded + trunc_stats.rejected_total() + ); + assert_eq!(trunc_errs.last().unwrap().0, trunc_off); + assert!(matches!( + trunc_errs.last().unwrap().1, + BsonEodIntradayError::TruncatedDocument { offset, remaining: 10, declared_len: Some(_) } + if offset == trunc_off + )); +} + +#[test] +fn decoded_nvda_bars_feed_build_bars_1m_end_to_end_with_10_for_1_split() { + // NVDA 10:1 split ex-date: 2024-06-10. + // Bar 1: 2024-06-07 15:59 ET (EDT, UTC-4) = 2024-06-07 19:59:00 UTC = 1_717_790_340 s. + // Bar 2: 2024-06-10 09:30 ET (EDT, UTC-4) = 2024-06-10 13:30:00 UTC = 1_718_026_200 s. + const PRE_SPLIT_TS_SEC: i64 = 1_717_790_340; + const EX_DATE_TS_SEC: i64 = 1_718_026_200; + + // Provider's retroactively split-adjusted 1m values. + let pre_split_doc = make_valid_doc( + "NVDA.US", + PRE_SPLIT_TS_SEC, + 120.80, + 121.05, + 120.72, + 120.888, + 2_500_000.0, + ); + let ex_date_doc = make_valid_doc( + "NVDA.US", + EX_DATE_TS_SEC, + 120.37, + 121.10, + 120.15, + 120.95, + 1_800_000.0, + ); + + let mut raw_buf = Vec::new(); + raw_buf.extend_from_slice(pre_split_doc.as_bytes()); + raw_buf.extend_from_slice(ex_date_doc.as_bytes()); + + let splits = SplitTable::from_events([( + "NVDA.US".to_owned(), + SplitEvent { + ex_date: day(2024, 6, 10), + ratio: 10.0, + }, + )]) + .unwrap(); + let empty_splits = SplitTable::::default(); + + let run_once = |table: &SplitTable| { + let mut bars = Vec::new(); + let mut decode_errors = Vec::new(); + let decode_stats = decode_eod_intraday_buffer( + &raw_buf, + |raw| bars.push(raw.into_eod_intraday_bar(|code, _ts| code.to_owned())), + |off, err| decode_errors.push((off, err)), + ); + assert!(decode_errors.is_empty()); + assert_eq!(decode_stats.docs_seen, 2); + assert_eq!(decode_stats.rows_decoded, 2); + let built = build_bars_1m(bars, table); + (decode_stats, built) + }; + + let (stats_split, built_split) = run_once(&splits); + let (stats_empty, built_empty) = run_once(&empty_splits); + let (stats_replay, built_replay) = run_once(&splits); + + // Deterministic replay produces identical rows and stats. + assert_eq!(stats_split, stats_replay); + assert_eq!(built_split.rows, built_replay.rows); + assert_eq!(built_split.stats, built_replay.stats); + assert_eq!(stats_split, stats_empty); + + assert_eq!(built_split.rows.len(), 2); + assert_eq!(built_empty.rows.len(), 2); + + // Pre-split bar: OHLC * 10, volume / 10, dollar volume (close * volume) conserved. + let pre_split = &built_split.rows[0]; + let pre_empty = &built_empty.rows[0]; + assert_eq!(pre_split.key, "NVDA.US"); + assert_eq!(pre_split.ts, PRE_SPLIT_TS_SEC * 1_000_000); + assert_eq!(pre_split.session_date, day(2024, 6, 7)); + assert_eq!(pre_split.session, IntradaySession::Rth); + assert_eq!(pre_split.source, BARS_1M_SOURCE_EOD); + assert_rel_eq(pre_split.open, pre_empty.open * 10.0, 1e-12); + assert_rel_eq(pre_split.high, pre_empty.high * 10.0, 1e-12); + assert_rel_eq(pre_split.low, pre_empty.low * 10.0, 1e-12); + assert_rel_eq(pre_split.close, pre_empty.close * 10.0, 1e-12); + assert_rel_eq(pre_split.volume, pre_empty.volume / 10.0, 1e-12); + assert_rel_eq( + pre_split.close * pre_split.volume, + pre_empty.close * pre_empty.volume, + 1e-12, + ); + + // Ex-date bar: unchanged by the 2024-06-10 split (strict ex_date > session_date boundary). + let ex_split = &built_split.rows[1]; + let ex_empty = &built_empty.rows[1]; + assert_eq!(ex_split.ts, EX_DATE_TS_SEC * 1_000_000); + assert_eq!(ex_split.session_date, day(2024, 6, 10)); + assert_eq!(ex_split.session, IntradaySession::Rth); + assert_eq!(ex_split.open.to_bits(), ex_empty.open.to_bits()); + assert_eq!(ex_split.high.to_bits(), ex_empty.high.to_bits()); + assert_eq!(ex_split.low.to_bits(), ex_empty.low.to_bits()); + assert_eq!(ex_split.close.to_bits(), ex_empty.close.to_bits()); + assert_eq!(ex_split.volume.to_bits(), ex_empty.volume.to_bits()); +} diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs index b8cf17f1..df36a1bf 100644 --- a/tools/curate-etl/src/bson_stream.rs +++ b/tools/curate-etl/src/bson_stream.rs @@ -24,6 +24,10 @@ use std::io; use crate::bson_ceo_shorts::{ decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, }; +use crate::bson_eod_intraday::{ + decode_eod_intraday_buffer, BsonEodIntradayDecodeStats, BsonEodIntradayError, + RawEodIntradayBar, +}; use crate::bson_eod_prices::{ decode_eod_price_buffer, BsonEodDecodeStats, BsonEodPriceError, RawEodDailyBar, }; @@ -531,6 +535,84 @@ fn rebase_qm_error(base: u64, err: BsonQmActionError) -> BsonQmActionError { } } +#[inline] +fn rebase_eod_intraday_error(base: u64, err: BsonEodIntradayError) -> BsonEodIntradayError { + match err { + BsonEodIntradayError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonEodIntradayError::TruncatedDocument { + offset: rebase_offset(base, offset), + remaining, + declared_len, + }, + BsonEodIntradayError::CorruptDocumentLength { + offset, + declared_len, + } => BsonEodIntradayError::CorruptDocumentLength { + offset: rebase_offset(base, offset), + declared_len, + }, + BsonEodIntradayError::CorruptBson { offset, detail } => { + BsonEodIntradayError::CorruptBson { + offset: rebase_offset(base, offset), + detail, + } + } + other => other, + } +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_intraday_buffer`], +/// accumulating [`BsonEodIntradayDecodeStats`] and rebasing per-document error offsets to +/// absolute stream byte offsets. +pub fn decode_eod_intraday_chunks( + reader: &mut RawBsonChunkReader, + mut on_bar: F, + mut on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawEodIntradayBar<'a>), + E: FnMut(u64, BsonEodIntradayError), +{ + let mut total = BsonEodIntradayDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_eod_intraday_buffer( + chunk.bytes, + &mut on_bar, + |local_offset, err| { + let abs_offset = base + local_offset as u64; + on_error(abs_offset, rebase_eod_intraday_error(base, err)); + }, + ); + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `eodIntraday1M` [`std::io::Read`] source through +/// [`decode_eod_intraday_buffer`] with bounded memory. +/// +/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset +/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`. +pub fn decode_eod_intraday_stream( + reader: R, + options: BsonStreamOptions, + on_bar: F, + on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawEodIntradayBar<'a>), + E: FnMut(u64, BsonEodIntradayError), +{ + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_eod_intraday_chunks(&mut chunk_reader, on_bar, on_error) +} + /// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_price_buffer`], /// accumulating [`BsonEodDecodeStats`] and rebasing per-document error offsets to absolute stream /// byte offsets. diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs index 500300f6..5e05e142 100644 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -4,6 +4,9 @@ use std::io::{self, Cursor, Read}; use bson::raw::{cstr, RawDocumentBuf}; use bson::DateTime; +use crate::bson_eod_intraday::{ + decode_eod_intraday_buffer, BsonEodIntradayError, +}; use crate::bson_eod_prices::{ decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats, }; @@ -12,9 +15,10 @@ use crate::bson_qm_actions::{ }; use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError}; use crate::bson_stream::{ - decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_price_stream, - decode_qm_split_stream, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, - DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, + decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_stream, + decode_qm_dividend_stream, decode_qm_price_stream, decode_qm_split_stream, BsonStreamError, + BsonStreamOptions, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, + MIN_BSON_DOC_BYTES, }; #[derive(Debug, Clone, Copy)] @@ -2113,3 +2117,164 @@ fn decode_qm_price_stream_matches_buffer_rebases_offsets_and_fails_on_framing() .unwrap_err(); assert!(matches!(err, BsonStreamError::TruncatedDocument { .. })); } + +#[test] +fn decode_eod_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() { + let make_doc = |code: &str, ts: i64, open: f64, close: f64, vol: f64| -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("timestamp"), ts); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), open.max(close) + 0.5); + doc.append(cstr!("low"), open.min(close) - 0.5); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), vol); + doc.into_bytes() + }; + + let mut fixture = Vec::new(); + fixture.extend_from_slice(&make_doc("NVDA.US", 1_717_767_000, 120.0, 120.5, 1000.0)); + fixture.extend_from_slice(&make_doc("AAPL.US", 1_717_767_060, 195.0, 195.25, 0.0)); + + // Semantic error: invalid timestamp (negative) + let bad_ts_offset = fixture.len() as u64; + fixture.extend_from_slice(&make_doc("NVDA.US", -60, 120.0, 120.5, 100.0)); + + // Valid length-framed doc with corrupt trailing terminator -> CorruptBson with embedded offset + let mut corrupt_bytes = make_doc("MSFT.US", 1_717_767_120, 420.0, 421.0, 500.0); + *corrupt_bytes.last_mut().unwrap() = 0xEE; + let corrupt_offset = fixture.len() as u64; + fixture.extend_from_slice(&corrupt_bytes); + + fixture.extend_from_slice(&make_doc("SHOP.TO", 1_717_767_180, 88.0, 88.4, 2500.0)); + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_eod_intraday_buffer( + &fixture, + |b| { + expected_rows.push(( + b.eod_search_code.to_owned(), + b.ts, + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + b.volume.to_bits(), + )) + }, + |off, err| expected_errs.push((off as u64, err)), + ); + assert_eq!(expected_stats.docs_seen, 5); + assert_eq!(expected_stats.rows_decoded, 3); + assert_eq!(expected_stats.rejected_invalid_timestamp, 1); + assert_eq!(expected_stats.rejected_corrupt_document, 1); + assert_eq!(expected_stats.rejected_total(), 2); + + // Exercise decode_eod_intraday_stream across small capacities and short reads splitting + // length prefixes and document bodies. + for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (512, 13)] { + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: 4096, + }; + let mut got_rows = Vec::new(); + let mut got_errs = Vec::new(); + let got_stats = decode_eod_intraday_stream( + FixedStepReader::new(&fixture, step), + opts, + |b| { + got_rows.push(( + b.eod_search_code.to_owned(), + b.ts, + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + b.volume.to_bits(), + )) + }, + |off, err| got_errs.push((off, err)), + ) + .unwrap(); + + assert_eq!(got_stats, expected_stats); + assert_eq!(got_rows, expected_rows); + assert_eq!(got_errs, expected_errs); + assert_eq!(got_errs[0].0, bad_ts_offset); + assert!(matches!( + got_errs[1], + (off, BsonEodIntradayError::CorruptBson { offset, .. }) + if off == corrupt_offset && offset as u64 == corrupt_offset + )); + } + + // Exercise decode_eod_intraday_chunks directly with random read sizes and EINTR interrupts. + let opts = BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes: 4096, + }; + let mut chunk_reader = + RawBsonChunkReader::with_options(RandomInterruptReader::new(&fixture, 0x141, true), opts) + .unwrap(); + let mut chunk_rows = Vec::new(); + let mut chunk_errs = Vec::new(); + let chunk_stats = decode_eod_intraday_chunks( + &mut chunk_reader, + |b| { + chunk_rows.push(( + b.eod_search_code.to_owned(), + b.ts, + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + b.volume.to_bits(), + )) + }, + |off, err| chunk_errs.push((off, err)), + ) + .unwrap(); + assert_eq!(chunk_stats, expected_stats); + assert_eq!(chunk_rows, expected_rows); + assert_eq!(chunk_errs, expected_errs); + + // Truncated trailing document must deliver the complete prefix first and then return + // BsonStreamError::TruncatedDocument at the exact tail offset. + let mut truncated = fixture.clone(); + let trunc_offset = truncated.len() as u64; + truncated.extend_from_slice(&120_i32.to_le_bytes()); + truncated.extend_from_slice(&[0x02, b'a', 0x00]); + let mut prefix_rows = Vec::new(); + let mut prefix_errs = Vec::new(); + let err = decode_eod_intraday_stream( + FixedStepReader::new(&truncated, 5), + BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes: 4096, + }, + |b| { + prefix_rows.push(( + b.eod_search_code.to_owned(), + b.ts, + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + b.volume.to_bits(), + )) + }, + |off, e| prefix_errs.push((off, e)), + ) + .unwrap_err(); + assert_eq!(prefix_rows, expected_rows); + assert_eq!(prefix_errs, expected_errs); + assert!(matches!( + err, + BsonStreamError::TruncatedDocument { + offset, + remaining: 7, + declared_len: Some(120), + } if offset == trunc_offset + )); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index ced89856..2ffd3b64 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -5,6 +5,7 @@ pub mod bars; pub mod bars_1m; pub mod bench; pub mod bson_ceo_shorts; +pub mod bson_eod_intraday; pub mod bson_eod_prices; pub mod bson_qm_actions; pub mod bson_qm_events; @@ -50,6 +51,10 @@ pub use bson_ceo_shorts::{ BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD, }; +pub use bson_eod_intraday::{ + decode_eod_intraday_buffer, decode_eod_intraday_bytes, decode_eod_intraday_doc, + BsonEodIntradayDecodeStats, BsonEodIntradayError, RawEodIntradayBar, +}; pub use bson_eod_prices::{ decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs, BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar, @@ -73,8 +78,8 @@ pub use bson_qm_prices::{ BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME, }; pub use bson_stream::{ - decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_price_chunks, - decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_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_price_chunks, decode_qm_price_stream, decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks, From 30c0e51813d36d77ec85486595b664ff628281ee Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 09:37:24 -0500 Subject: [PATCH 23/36] =?UTF-8?q?T-141:=20M2.3d=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20zero-copy=20`eodIntraday1M`=20BSON=20decoder=20+=20ch?= =?UTF-8?q?unked=20stream=20decode=20into=20`EodIntradayBar`=20(pure,=20no?= =?UTF-8?q?=20new=20crates,=20no=20live=20Mongo/QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/bson_eod_intraday.rs | 14 +++- .../curate-etl/src/bson_eod_intraday_tests.rs | 79 +++++++++++++++++++ 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/tools/curate-etl/src/bson_eod_intraday.rs b/tools/curate-etl/src/bson_eod_intraday.rs index 0cd039e8..c8b9237b 100644 --- a/tools/curate-etl/src/bson_eod_intraday.rs +++ b/tools/curate-etl/src/bson_eod_intraday.rs @@ -41,7 +41,9 @@ //! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, and `< 0.0` are rejected as //! [`BsonEodIntradayError::InvalidNumber`]. //! - Unknown extra fields (`_id`, `symbol`, `exchange`, `datetime`, `gmtoffset`, `source`, nested -//! objects/arrays, etc.) are skipped without calling `elem.value()`. +//! objects/arrays, etc.) are validated as borrowed `RawBsonRef` views (zero allocation) and +//! otherwise ignored, so malformed payloads (such as invalid UTF-8 in `datetime`) still surface +//! as [`BsonEodIntradayError::CorruptBson`]. //! - Error precedence: retains the first semantic error while continuing to scan remaining //! top-level elements so any malformed BSON bytes surface immediately as `CorruptBson`. @@ -547,9 +549,15 @@ fn decode_eod_intraday_doc_at<'a>( } } } + } else { + // Validate skipped top-level payloads via borrowed `RawBsonRef` views (zero + // allocation) so malformed bytes (e.g. invalid UTF-8 in `datetime`) still reject the + // document as `CorruptBson` at its frame offset. + elem.value().map_err(|err| BsonEodIntradayError::CorruptBson { + offset, + detail: format!("field '{}': {err}", key.as_str()), + })?; } - // Unknown extra fields (`_id`, `symbol`, `exchange`, `datetime`, `gmtoffset`, `source`, - // etc.) are skipped without calling `elem.value()`. } if let Some(err) = first_semantic_err { diff --git a/tools/curate-etl/src/bson_eod_intraday_tests.rs b/tools/curate-etl/src/bson_eod_intraday_tests.rs index 099f760b..6374d2b8 100644 --- a/tools/curate-etl/src/bson_eod_intraday_tests.rs +++ b/tools/curate-etl/src/bson_eod_intraday_tests.rs @@ -580,6 +580,84 @@ fn rejects_truncated_and_corrupt_single_doc_bytes_without_panicking() { } } +#[test] +fn rejects_corrupt_utf8_in_skipped_top_level_field_and_recovers_to_next_frame() { + // Build a valid document with a skipped `datetime` string field, then corrupt one payload byte + // inside `datetime` to invalid UTF-8 (0xFF) while leaving all lengths and NUL terminators + // intact. + const DATETIME_MARKER: &[u8] = b"2024-06-07 13:30:00"; + let mut doc_with_datetime = make_valid_doc( + "NVDA.US", + 1_717_767_000, + 120.50, + 121.25, + 120.10, + 120.90, + 1_000.0, + ); + doc_with_datetime.append(cstr!("datetime"), "2024-06-07 13:30:00"); + + let mut corrupt_bytes = doc_with_datetime.as_bytes().to_vec(); + let marker_pos = corrupt_bytes + .windows(DATETIME_MARKER.len()) + .position(|w| w == DATETIME_MARKER) + .expect("datetime payload must exist in serialized BSON"); + corrupt_bytes[marker_pos + 4] = 0xFF; + + // Single-document decode must reject as CorruptBson at offset 0. + match decode_eod_intraday_bytes(&corrupt_bytes) { + Err(BsonEodIntradayError::CorruptBson { offset: 0, detail }) => { + assert!( + detail.contains("datetime"), + "expected offending field name in detail, got: {detail}" + ); + } + other => panic!("expected CorruptBson at offset 0, got {other:?}"), + } + + // Buffer decode with a preceding valid frame and a following valid frame: rejects the + // damaged frame at its exact byte offset, increments `rejected_corrupt_document`, and + // recovers cleanly to decode the next frame. + let valid_before = + make_valid_doc("AAPL.US", 1_717_766_940, 195.0, 196.0, 194.5, 195.5, 500.0); + let valid_after = + make_valid_doc("MSFT.US", 1_717_767_060, 420.0, 421.0, 419.5, 420.5, 750.0); + + let mut buf = Vec::new(); + buf.extend_from_slice(valid_before.as_bytes()); + let corrupt_offset = buf.len(); + buf.extend_from_slice(&corrupt_bytes); + buf.extend_from_slice(valid_after.as_bytes()); + + let mut rows = Vec::new(); + let mut errors = Vec::new(); + let stats = decode_eod_intraday_buffer( + &buf, + |bar| rows.push((bar.eod_search_code.to_owned(), bar.ts, bar.close)), + |off, err| errors.push((off, err)), + ); + + assert_eq!( + rows, + vec![ + ("AAPL.US".to_owned(), 1_717_766_940_000_000, 195.5), + ("MSFT.US".to_owned(), 1_717_767_060_000_000, 420.5), + ] + ); + assert_eq!(stats.docs_seen, 3); + assert_eq!(stats.rows_decoded, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.rejected_total(), 1); + assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].0, corrupt_offset); + assert!(matches!( + &errors[0].1, + BsonEodIntradayError::CorruptBson { offset, detail } + if *offset == corrupt_offset && detail.contains("datetime") + )); +} + #[test] fn decodes_mixed_buffer_preserving_order_recovering_past_corrupt_frame_and_merging_stats() { let valid1 = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0); @@ -795,6 +873,7 @@ fn decoded_nvda_bars_feed_build_bars_1m_end_to_end_with_10_for_1_split() { assert_rel_eq(pre_split.open, pre_empty.open * 10.0, 1e-12); assert_rel_eq(pre_split.high, pre_empty.high * 10.0, 1e-12); assert_rel_eq(pre_split.low, pre_empty.low * 10.0, 1e-12); + assert_rel_eq(pre_split.close, 1_208.88, 1e-12); assert_rel_eq(pre_split.close, pre_empty.close * 10.0, 1e-12); assert_rel_eq(pre_split.volume, pre_empty.volume / 10.0, 1e-12); assert_rel_eq( From 470b0a4bd9f72960f083463463b750aff3d94528 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 09:43:51 -0500 Subject: [PATCH 24/36] T-141: tests --- .../tests/bson_eod_intraday_qa_contract.rs | 438 ++++++++++++++++++ 1 file changed, 438 insertions(+) create mode 100644 tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs diff --git a/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs b/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs new file mode 100644 index 00000000..5fe00412 --- /dev/null +++ b/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs @@ -0,0 +1,438 @@ +//! QA contract tests for the public `eodIntraday1M` raw BSON decoder (T-141 / M2.3d). +//! +//! Covers gaps left by the in-crate `bson_eod_intraday_tests.rs`, using only the public API: +//! - field-order independence, case-sensitive keys, nested look-alike keys ignored; +//! - error precedence: corrupt skipped payload beats an earlier semantic error, and the first +//! semantic error in document order wins over later ones; +//! - timestamp edge values (`i32::MAX`, subnormal / half-second / huge doubles); +//! - `Display` names the offending field; empty buffer; `i32::MAX` declared length; +//! - seeded byte-mutation fuzz: never panics, conservation always holds, every buffer row equals +//! the single-document decode of the same frame, and the stream decode reproduces the buffer +//! rows, per-document errors, and terminal framing offset; +//! - stream: empty input, `max_doc_bytes` overflow, and invalid options; +//! - UTC bar-start micros map to the right `build_bars_1m` session date across the UTC midnight. + +use std::io::{self, Cursor, Read}; + +use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; +use curate_etl::{ + build_bars_1m, decode_eod_intraday_buffer, decode_eod_intraday_bytes, + decode_eod_intraday_doc, decode_eod_intraday_stream, iter_raw_bson_docs, ymd_to_epoch_days, + BsonEodIntradayDecodeStats, BsonEodIntradayError, BsonStreamError, BsonStreamOptions, + RawEodIntradayBar, SplitTable, +}; + +const TS: i64 = 1_717_767_000; + +struct SplitMix64(u64); + +impl SplitMix64 { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } +} + +/// Reader returning seeded pseudo-random short reads of 1..=61 bytes. +struct JitterReader<'a> { + data: &'a [u8], + pos: usize, + rng: SplitMix64, +} + +impl Read for JitterReader<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let remaining = self.data.len() - self.pos; + if remaining == 0 { + return Ok(0); + } + let step = (self.rng.next_u64() % 61) as usize + 1; + let take = remaining.min(step).min(buf.len()); + buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); + self.pos += take; + Ok(take) + } +} + +fn valid_doc(code: &str, ts: i64, close: f64, volume: f64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), "X"); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("datetime"), "2024-06-07 13:30:00"); + doc.append(cstr!("timestamp"), ts); + doc.append(cstr!("gmtoffset"), 0_i32); + doc.append(cstr!("open"), close - 0.25); + doc.append(cstr!("high"), close + 0.5); + doc.append(cstr!("low"), close - 0.5); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc +} + +fn with_timestamp(ts: RawBsonRef<'_>) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("timestamp"), ts); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 1.0_f64); + doc +} + +type Row = (String, i64, [u64; 5]); + +fn row(b: RawEodIntradayBar<'_>) -> Row { + ( + b.eod_search_code.to_owned(), + b.ts, + [ + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + b.volume.to_bits(), + ], + ) +} + +#[test] +fn field_order_does_not_change_the_decoded_bar() { + let forward = valid_doc("NVDA.US", TS, 120.5, 1_000.0); + let mut reversed = RawDocumentBuf::new(); + reversed.append(cstr!("volume"), 1_000.0_f64); + reversed.append(cstr!("close"), 120.5_f64); + reversed.append(cstr!("low"), 120.0_f64); + reversed.append(cstr!("high"), 121.0_f64); + reversed.append(cstr!("open"), 120.25_f64); + reversed.append(cstr!("timestamp"), TS); + reversed.append(cstr!("eodSearchCode"), "NVDA.US"); + + assert_eq!( + decode_eod_intraday_doc(&forward).unwrap(), + decode_eod_intraday_doc(&reversed).unwrap() + ); +} + +#[test] +fn keys_are_case_sensitive_and_nested_look_alikes_are_ignored() { + // `Timestamp` (capital T) is not `timestamp`; a nested `timestamp` must not satisfy it either. + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("timestamp"), TS); + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("Timestamp"), TS); + doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 1.0_f64); + + assert_eq!( + decode_eod_intraday_doc(&doc), + Err(BsonEodIntradayError::MissingField { field: "timestamp" }) + ); +} + +#[test] +fn eod_search_code_is_borrowed_verbatim_without_trimming() { + let doc = valid_doc(" NVDA.US ", TS, 10.0, 1.0); + let bar = decode_eod_intraday_bytes(doc.as_bytes()).unwrap(); + assert_eq!(bar.eod_search_code, " NVDA.US "); +} + +#[test] +fn first_semantic_error_in_document_order_wins() { + // close is invalid before eodSearchCode is blank: close error must be reported. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("close"), -1.0_f64); + doc.append(cstr!("eodSearchCode"), ""); + doc.append(cstr!("timestamp"), -5_i64); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("volume"), 1.0_f64); + + match decode_eod_intraday_doc(&doc) { + Err(BsonEodIntradayError::InvalidNumber { field: "close", value }) => { + assert_eq!(value, -1.0) + } + other => panic!("expected InvalidNumber(close), got {other:?}"), + } + + // A semantic error plus a missing field: the semantic error wins over MissingField. + let mut doc2 = RawDocumentBuf::new(); + doc2.append(cstr!("eodSearchCode"), "NVDA.US"); + doc2.append(cstr!("timestamp"), RawBsonRef::Null); + assert!(matches!( + decode_eod_intraday_doc(&doc2), + Err(BsonEodIntradayError::WrongType { field: "timestamp", .. }) + )); +} + +#[test] +fn corrupt_skipped_payload_after_semantic_error_is_reported_as_corrupt_bson() { + // Blank key (semantic) first, then a later `datetime` string with invalid UTF-8. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), " "); + doc.append(cstr!("timestamp"), TS); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 1.0_f64); + doc.append(cstr!("datetime"), "ZZZZ"); + let mut bytes = doc.into_bytes(); + let pos = bytes.windows(4).position(|w| w == b"ZZZZ").unwrap(); + bytes[pos + 1] = 0xFF; + + let mut stats = BsonEodIntradayDecodeStats::default(); + let mut errs = Vec::new(); + let s = decode_eod_intraday_buffer(&bytes, |_| panic!("no row"), |o, e| errs.push((o, e))); + stats.merge(&s); + assert_eq!(errs.len(), 1); + assert!(matches!(errs[0], (0, BsonEodIntradayError::CorruptBson { offset: 0, .. }))); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.rejected_empty_field, 0); + assert_eq!(stats.rejected_total(), 1); +} + +#[test] +fn timestamp_edge_values_are_accepted_or_rejected_exactly() { + // i32::MAX seconds (2038-01-19) is valid in Int32 form. + let bar_doc = with_timestamp(RawBsonRef::Int32(i32::MAX)); + let bar = decode_eod_intraday_doc(&bar_doc).unwrap(); + assert_eq!(bar.ts, i64::from(i32::MAX) * 1_000_000); + + let max_secs = i64::MAX / 1_000_000; + for bad in [ + RawBsonRef::Double(f64::MIN_POSITIVE), + RawBsonRef::Double(5e-324), + RawBsonRef::Double(max_secs as f64 + 0.5), + RawBsonRef::Double(1e300), + RawBsonRef::Double(f64::MAX), + RawBsonRef::Int32(i32::MIN), + RawBsonRef::Int64(i64::MIN), + ] { + let doc = with_timestamp(bad); + assert_eq!( + decode_eod_intraday_doc(&doc), + Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }), + "timestamp {bad:?}" + ); + } +} + +#[test] +fn display_messages_name_the_offending_field_and_offset() { + let cases = [ + (BsonEodIntradayError::MissingField { field: "eodSearchCode" }, "eodSearchCode"), + (BsonEodIntradayError::EmptyField { field: "eodSearchCode" }, "eodSearchCode"), + (BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }, "timestamp"), + (BsonEodIntradayError::InvalidNumber { field: "volume", value: -1.0 }, ">= 0"), + (BsonEodIntradayError::InvalidNumber { field: "close", value: 0.0 }, "> 0"), + ( + BsonEodIntradayError::CorruptBson { offset: 77, detail: "x".into() }, + "77", + ), + ]; + for (err, needle) in cases { + let msg = err.to_string(); + assert!(msg.contains(needle), "{msg:?} should contain {needle:?}"); + } +} + +#[test] +fn empty_buffer_and_huge_declared_length_never_panic() { + let stats = decode_eod_intraday_buffer(&[], |_| panic!(), |_, _| panic!()); + assert_eq!(stats, BsonEodIntradayDecodeStats::default()); + + let mut bytes = valid_doc("NVDA.US", TS, 10.0, 1.0).into_bytes(); + let first_len = bytes.len(); + bytes.extend_from_slice(&i32::MAX.to_le_bytes()); + bytes.extend_from_slice(&[0u8; 8]); + let mut rows = 0usize; + let mut errs = Vec::new(); + let stats = decode_eod_intraday_buffer(&bytes, |_| rows += 1, |o, e| errs.push((o, e))); + assert_eq!(rows, 1); + assert_eq!(stats.docs_seen, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(errs.len(), 1); + assert_eq!(errs[0].0, first_len); + assert!(matches!( + errs[0].1, + BsonEodIntradayError::TruncatedDocument { declared_len: Some(i32::MAX), .. } + )); +} + +fn is_framing(e: &BsonEodIntradayError) -> bool { + matches!( + e, + BsonEodIntradayError::TruncatedDocument { .. } + | BsonEodIntradayError::CorruptDocumentLength { .. } + ) +} + +#[test] +fn seeded_mutation_fuzz_buffer_and_stream_agree_and_conserve_counts() { + let mut clean = Vec::new(); + for i in 0..20i64 { + let doc = valid_doc(&format!("S{i:02}.US"), TS + 60 * i, 10.0 + i as f64, 100.0 * i as f64); + clean.extend_from_slice(doc.as_bytes()); + } + let mut rng = SplitMix64(0x7141_B50E); + let (mut framing_cases, mut ok_cases, mut rows_seen) = (0usize, 0usize, 0usize); + + for case in 0..400u64 { + let mut bytes = clean.clone(); + for _ in 0..1 + (rng.next_u64() % 4) as usize { + let idx = (rng.next_u64() as usize) % bytes.len(); + bytes[idx] = rng.next_u64() as u8; + } + if rng.next_u64() % 5 == 0 { + let cut = (rng.next_u64() as usize) % bytes.len(); + bytes.truncate(cut); + } + + // Buffer decode: every row must equal the single-frame decode of the same bytes. + let mut frames = Vec::new(); + let mut it = iter_raw_bson_docs(&bytes); + while let Some(item) = it.next_with_offset() { + if let Ok((off, doc)) = item { + frames.push((off, doc.as_bytes().len())); + } + } + let mut exp_rows = Vec::new(); + let mut exp_errs = Vec::new(); + let stats = decode_eod_intraday_buffer( + &bytes, + |b| { + let start = b.eod_search_code.as_ptr() as usize - bytes.as_ptr() as usize; + let &(off, len) = frames + .iter() + .find(|(o, l)| start >= *o && start < o + l) + .expect("row borrows from a framed doc"); + assert_eq!(decode_eod_intraday_bytes(&bytes[off..off + len]).unwrap(), b); + exp_rows.push(row(b)); + }, + |o, e| exp_errs.push((o as u64, e)), + ); + assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total(), "case={case}"); + assert_eq!(stats.rows_decoded, exp_rows.len()); + assert_eq!(stats.rejected_total(), exp_errs.len()); + rows_seen += exp_rows.len(); + + let exp_framing = match exp_errs.last() { + Some((off, e)) if is_framing(e) => { + let off = *off; + exp_errs.pop(); + Some(off) + } + _ => None, + }; + + let cap = [1usize, 5, 41, 300, 4096][(case % 5) as usize]; + let mut rows = Vec::new(); + let mut errs = Vec::new(); + let result = decode_eod_intraday_stream( + JitterReader { data: &bytes, pos: 0, rng: SplitMix64(case) }, + BsonStreamOptions { chunk_capacity_bytes: cap, max_doc_bytes: 1 << 20 }, + |b| rows.push(row(b)), + |o, e| errs.push((o, e)), + ); + assert_eq!(rows, exp_rows, "case={case} cap={cap}"); + assert_eq!(errs, exp_errs, "case={case} cap={cap}"); + match (exp_framing, result) { + (None, Ok(s)) => { + ok_cases += 1; + assert_eq!(s, stats, "case={case}"); + } + (Some(off), Err(BsonStreamError::CorruptDocumentLength { offset, .. })) + | (Some(off), Err(BsonStreamError::TruncatedDocument { offset, .. })) => { + framing_cases += 1; + assert_eq!(offset, off, "case={case} cap={cap}"); + } + (exp, got) => panic!("case={case}: expected framing={exp:?}, got {got:?}"), + } + } + assert!(framing_cases >= 20, "framing_cases={framing_cases}"); + assert!(ok_cases >= 20, "ok_cases={ok_cases}"); + assert!(rows_seen > 1000, "rows_seen={rows_seen}"); +} + +#[test] +fn stream_handles_empty_input_oversized_docs_and_invalid_options() { + let stats = decode_eod_intraday_stream( + Cursor::new(Vec::::new()), + BsonStreamOptions::default(), + |_| panic!(), + |_, _| panic!(), + ) + .unwrap(); + assert_eq!(stats, BsonEodIntradayDecodeStats::default()); + + let first = valid_doc("NVDA.US", TS, 10.0, 1.0).into_bytes(); + let mut big = valid_doc("BIG.US", TS, 10.0, 1.0); + big.append(cstr!("pad"), "p".repeat(256).as_str()); + let mut input = first.clone(); + input.extend_from_slice(big.as_bytes()); + + let mut rows = Vec::new(); + let err = decode_eod_intraday_stream( + Cursor::new(&input), + BsonStreamOptions { chunk_capacity_bytes: 16, max_doc_bytes: 200 }, + |b| rows.push(row(b)), + |_, e| panic!("unexpected per-doc error {e:?}"), + ) + .unwrap_err(); + assert_eq!(rows.len(), 1); + assert!(matches!( + err, + BsonStreamError::CorruptDocumentLength { offset, max_doc_bytes: 200, .. } + if offset == first.len() as u64 + )); + + for (opts, want_cap) in [ + (BsonStreamOptions { chunk_capacity_bytes: 0, max_doc_bytes: 4096 }, true), + (BsonStreamOptions { chunk_capacity_bytes: 16, max_doc_bytes: 4 }, false), + ] { + let err = decode_eod_intraday_stream(Cursor::new(&input), opts, |_| {}, |_, _| {}) + .unwrap_err(); + if want_cap { + assert!(matches!(err, BsonStreamError::InvalidChunkCapacity)); + } else { + assert!(matches!(err, BsonStreamError::InvalidMaxDocBytes)); + } + } +} + +#[test] +fn utc_bar_start_micros_assign_late_et_bars_to_the_correct_session_date() { + // 2024-06-07 19:59 EDT = 2024-06-07 23:59 UTC (same UTC date) and + // 2024-06-07 20:00 EDT = 2024-06-08 00:00 UTC (next UTC date) both belong to the 06-07 + // US session; a seconds/micros unit slip would push them to 1970 or far future dates. + let late = 1_717_804_740_i64; // 2024-06-07T23:59:00Z + let after_midnight = 1_717_804_800_i64; // 2024-06-08T00:00:00Z + let mut buf = Vec::new(); + buf.extend_from_slice(valid_doc("NVDA.US", late, 120.0, 10.0).as_bytes()); + buf.extend_from_slice(valid_doc("NVDA.US", after_midnight, 120.1, 10.0).as_bytes()); + + let mut bars = Vec::new(); + decode_eod_intraday_buffer( + &buf, + |b| bars.push(b.into_eod_intraday_bar(|c, _| c.to_owned())), + |_, e| panic!("{e:?}"), + ); + let built = build_bars_1m(bars, &SplitTable::::default()); + let june7 = ymd_to_epoch_days(2024, 6, 7).unwrap(); + let dates: Vec = built.rows.iter().map(|r| r.session_date).collect(); + assert_eq!(built.rows.len(), 2); + assert_eq!(dates, vec![june7, june7]); + assert_eq!(built.rows[0].ts, late * 1_000_000); + assert_eq!(built.rows[1].ts, after_midnight * 1_000_000); +} From d6d6bc8c8b8c8ab61b02060f33eb8cd9f3a22b7c Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:52:40 -0500 Subject: [PATCH 25/36] =?UTF-8?q?T-139:=20M2.4a=20=E2=80=94=20Versioned=20?= =?UTF-8?q?Feature=20Library=20core:=20declarative=20DuckDB=20SQL=20featur?= =?UTF-8?q?e=20definitions=20+=20`registerSignal`=20registry=20+=20version?= =?UTF-8?q?ed=20Parquet=20batch-plan=20runner=20over=20an=20injected=20`Du?= =?UTF-8?q?ckDbExecutor`=20in=20`libs/research/src/feature-library.ts`=20(?= =?UTF-8?q?pure,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 20 + libs/research/package.json | 1 + libs/research/src/feature-library.ts | 2119 ++++++++++++++++++++ libs/research/src/index.ts | 1 + libs/research/src/sha256.ts | 105 + libs/research/src/trial-ledger.ts | 101 +- libs/research/test/feature-library.test.ts | 953 +++++++++ 7 files changed, 3200 insertions(+), 100 deletions(-) create mode 100644 libs/research/src/feature-library.ts create mode 100644 libs/research/src/sha256.ts create mode 100644 libs/research/test/feature-library.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index 03973ff5..939d7fda 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -228,3 +228,23 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - SSE/HTTP transport wrapper in `apps/stock/web-api`. - Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters. + +## Versioned Feature Library + +Exported from both `@stock-bot/research` and `@stock-bot/research/feature-library` (`libs/research/src/feature-library.ts`). The module is pure, dependency-free, and browser-safe (zero `node:*` imports, zero DuckDB driver dependency); SQL execution is injected via `DuckDbExecutor` (`{ run(sql), query(sql, params) }`). + +### API & Immutability + +- **`validateFeatureDefinition(def)`** — Fail-closed validator for declarative `duckdb_sql` feature definitions using a single quote-aware tokenizer shared with hashing and placeholder expansion. Accepts a single `SELECT` or `WITH ... SELECT` statement projecting exactly `(listing_id, ts, known_at, value)` in contract order. Rejects semicolons, comments, caller bind markers (`?`, `$1`, `:name`), prohibited DDL/DML/admin keywords (`COPY`, `ATTACH`, `INSERT`, `CREATE`, `PRAGMA`, `SET`, etc.), external readers (`read_parquet`, `read_csv`, `glob`, etc.), quoted file paths/URIs, catalog relations, table functions, and non-allow-listed functions. Relation sources are restricted to declared `{{input:}}` placeholders (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`), in-scope CTEs, and validated subqueries; every declared input must be used and every placeholder must be declared. +- **`featureRef(def)` / `parseFeatureRef(ref)`** — Formats and parses canonical `@v` refs (`^[a-z][a-z0-9_]{0,62}$` and positive safe integer version; rejects non-canonical forms such as `ret_1d@v01`). +- **`featureDefinitionHash(def)`** — Deterministic 64-char SHA-256 hex digest over `{ name, version, kind, sql (canonical tokens), inputs (sorted), warmupBars, knownAtRule }`. Invariant across inter-token whitespace, object key order, and input array order; preserves whitespace inside string literals. `family` and `description` are stored as metadata from the first registration. +- **`createFeatureRegistry()`** — In-memory registry exposing `registerSignal(def)` (D11), `get(ref)`, and `list()`. Re-registering an identical hash is idempotent; re-registering `@v` with a different hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. Defensive copies isolate stored definitions from caller mutation. +- **`planFeatureBatch(def, { curatedRoot, fromYear, toYear, vaultCutoffDate })`** — Validates `curatedRoot`, four-digit ordered years, and strict UTC `YYYY-MM-DD` `vaultCutoffDate` via `applyVaultFence`. Plans one yearly ZSTD Parquet write to `/features//v/year=YYYY/part.parquet` through the last year with any pre-cutoff time (a January 1 cutoff excludes that calendar year; an entirely post-cutoff range throws `VAULT_RANGE_VIOLATION`). Expands `{{input:}}` scans with bound upper availability predicates (`ts <= ? AND known_at <= ?`, `known_at <= ?`, or `effective_known_at <= ?` for `fundamentals_pit`) strictly `< vaultCutoffDate` (last included microsecond `.999999Z`) before authored SQL runs, preserving earlier history for SQL-owned warm-up. +- **`runFeatureBatch(def, opts, executor)`** — Validates and plans upfront (0 executor calls on invalid inputs), awaits `executor.query(sql, params)` sequentially in year order, and returns `{ ref, definitionHash, knownAtRule, warmupBars, inputs, writes }`. On write failure, stops immediately and throws `FeatureLibraryError('BATCH_WRITE_FAILED')` exposing `cause`, `failedYear`, `completedYears`, and `completedWrites` (earlier completed files may remain on disk for operator inspection before retry). +- **`RET_1D_V1`** — Built-in `ret_1d@v1` example computing 1-day listing-partitioned raw-close return `(close / LAG(close)) - 1.0` with `known_at = ts` and `warmupBars: 1` (omitting rows without a positive prior close). + +### Operational & Research Governance Notes + +- **Executor & directory requirements:** Callers running plans against DuckDB must configure the executor session timezone to UTC (`TZ=UTC`) and ensure output parent directories (`/features//v/year=YYYY/`) exist before executing `COPY`. +- **Point-in-time & `adj_factors` snapshots:** Feature definitions own per-observation availability (`knownAtRule` and projected `known_at`). Because `adj_factors` stores cumulative suffix products, features referencing `{{input:adj_factors}}` require a caller-verified, immutable point-in-time snapshot compatible with `vaultCutoffDate`. +- **Economic ownership & evidence:** The Quant research role owns each feature's economic specification. `RET_1D_V1` uses a zero-return comparison baseline with no execution or transaction cost model. Any future research claim built on materialized features must retain the feature `ref` and `definitionHash`, immutable dataset identifier, sample window, `vaultCutoffDate`, baseline, and execution assumptions. diff --git a/libs/research/package.json b/libs/research/package.json index fb865726..e5cf853d 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -11,6 +11,7 @@ "./dataset-contracts": "./src/dataset-contracts.ts", "./datasets": "./src/datasets.ts", "./event-panel": "./src/event-panel.ts", + "./feature-library": "./src/feature-library.ts", "./market-data-store": "./src/market-data-store.ts", "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", "./mcp": "./src/mcp/index.ts", diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts new file mode 100644 index 00000000..658eaffb --- /dev/null +++ b/libs/research/src/feature-library.ts @@ -0,0 +1,2119 @@ +/** + * Versioned Feature Library core: declarative DuckDB SQL feature definitions, + * immutable `registerSignal` registry, and Vault-fenced yearly Parquet + * batch-plan runner (`design/PLATFORM-PLAN.md` §8 & D11, + * `design/DATA-CONTRACTS.md` §3.A). + * + * Pure, dependency-free, and browser-safe: zero `node:*` imports, zero DuckDB + * driver dependency, zero bare `process` access. SQL execution is injected via + * {@link DuckDbExecutor} from `./market-data-store-duckdb`. + * + * Output Parquet contract (`design/DATA-CONTRACTS.md` §3.A): + * - `/features//v/year=YYYY/part.parquet` + * - Columns: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, value DOUBLE)` + * - Compression: `ZSTD`, ordered by `(listing_id, ts)`. + * + * Point-in-time & `adj_factors` note: + * - Each expanded `{{input:}}` scan binds upper availability + * predicates strictly below `vaultCutoffDate` before authored SQL executes, + * while preserving earlier history for SQL-owned warm-up windows. + * - Feature definitions own per-observation availability (`knownAtRule` and + * projected `known_at`). Because `adj_factors` stores cumulative suffix + * products, any feature consuming `{{input:adj_factors}}` requires a + * caller-verified, immutable point-in-time snapshot compatible with the job + * cutoff. + * + * Economic ownership & research evidence: + * - The Quant research role owns the economic specification of each feature + * definition. + * - {@link RET_1D_V1} is a built-in 1-session raw-close return example using a + * zero-return comparison baseline and no execution or transaction cost model. + * - Any future research result claim built on materialized features must retain + * the feature ref and `definitionHash`, immutable dataset identifier, sample + * window, Vault cutoff, baseline, and execution assumptions. + */ + +import { + MarketDataStoreValidationError, + VaultHoldoutFenceError, + applyVaultFence, +} from './market-data-store'; +import { + type DuckDbExecutor, + type DuckDbParam, + validateCuratedRoot, +} from './market-data-store-duckdb'; +import { sha256HexUtf8 } from './sha256'; + +export const FEATURE_FAMILIES = [ + 'technical', + 'cross_sectional', + 'fundamental', + 'event', + 'fx', + 'regime', +] as const; +export type FeatureFamily = (typeof FEATURE_FAMILIES)[number]; + +export const FEATURE_KINDS = ['duckdb_sql'] as const; +export type FeatureKind = (typeof FEATURE_KINDS)[number]; + +export const FEATURE_INPUT_DATASETS = [ + 'bars_1d', + 'adj_factors', + 'events', + 'shorts', + 'fx_1d', + 'fundamentals_pit', +] as const; +export type FeatureInputDataset = (typeof FEATURE_INPUT_DATASETS)[number]; + +export const FEATURE_KNOWN_AT_RULES = [ + 'bar_close', + 'source_known_at', + 'max_input_known_at', +] as const; +export type FeatureKnownAtRule = (typeof FEATURE_KNOWN_AT_RULES)[number]; + +export const FEATURE_OUTPUT_COLUMNS = ['listing_id', 'ts', 'known_at', 'value'] as const; + +const FEATURE_FAMILY_SET: ReadonlySet = new Set(FEATURE_FAMILIES); +const FEATURE_INPUT_SET: ReadonlySet = new Set(FEATURE_INPUT_DATASETS); +const FEATURE_KNOWN_AT_RULE_SET: ReadonlySet = new Set(FEATURE_KNOWN_AT_RULES); + +const FEATURE_NAME_RE = /^[a-z][a-z0-9_]{0,62}$/; +const FEATURE_REF_RE = /^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$/; +const PLACEHOLDER_INNER_RE = /^input:([a-z][a-z0-9_]*)$/; +const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; + +const MIN_FOUR_DIGIT_YEAR = 1000; +const MAX_FOUR_DIGIT_YEAR = 9999; + +export type FeatureLibraryErrorCode = + | 'INVALID_DEFINITION' + | 'INVALID_NAME' + | 'INVALID_VERSION' + | 'INVALID_FAMILY' + | 'INVALID_KIND' + | 'INVALID_WARMUP_BARS' + | 'INVALID_KNOWN_AT_RULE' + | 'INVALID_FEATURE_REF' + | 'INVALID_SQL_STATEMENT' + | 'PROHIBITED_SQL_OPERATION' + | 'EXTERNAL_DATA_ACCESS' + | 'INVALID_SQL_PROJECTION' + | 'UNSUPPORTED_INPUT_DATASET' + | 'UNDECLARED_INPUT' + | 'UNUSED_INPUT' + | 'FEATURE_VERSION_IMMUTABLE' + | 'INVALID_BATCH_OPTIONS' + | 'VAULT_RANGE_VIOLATION' + | 'BATCH_WRITE_FAILED'; + +export interface FeatureBatchWriteReceipt { + readonly year: number; + readonly outputPath: string; +} + +export interface FeatureLibraryErrorDetails { + readonly cause?: unknown; + readonly failedYear?: number; + readonly completedYears?: readonly number[]; + readonly completedWrites?: readonly FeatureBatchWriteReceipt[]; + readonly ref?: string; +} + +/** Typed fail-closed error thrown by the Feature Library SDK. */ +export class FeatureLibraryError extends Error { + override readonly name = 'FeatureLibraryError'; + readonly code: FeatureLibraryErrorCode; + readonly failedYear?: number; + readonly completedYears?: readonly number[]; + readonly completedWrites?: readonly FeatureBatchWriteReceipt[]; + readonly ref?: string; + + constructor( + code: FeatureLibraryErrorCode, + message: string, + details?: FeatureLibraryErrorDetails + ) { + super(message, details?.cause !== undefined ? { cause: details.cause } : undefined); + this.code = code; + this.failedYear = details?.failedYear; + this.completedYears = + details?.completedYears !== undefined + ? Object.freeze([...details.completedYears]) + : undefined; + this.completedWrites = + details?.completedWrites !== undefined + ? Object.freeze(details.completedWrites.map(w => Object.freeze({ ...w }))) + : undefined; + this.ref = details?.ref; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export interface FeatureDefinition { + readonly name: string; + readonly version: number; + readonly family: FeatureFamily; + readonly kind: FeatureKind; + readonly sql: string; + readonly inputs: readonly FeatureInputDataset[]; + readonly warmupBars: number; + readonly knownAtRule: FeatureKnownAtRule; + readonly description?: string; +} + +export interface FeatureRefParts { + readonly name: string; + readonly version: number; +} + +export interface RegisteredFeature { + readonly ref: string; + readonly definitionHash: string; + readonly definition: FeatureDefinition; +} + +export interface FeatureRegistry { + registerSignal(def: FeatureDefinition): RegisteredFeature; + get(ref: string): FeatureDefinition | undefined; + list(): readonly string[]; +} + +export interface PlanFeatureBatchOptions { + readonly curatedRoot: string; + readonly fromYear: number; + readonly toYear: number; + readonly vaultCutoffDate: string; +} + +export interface PlannedFeatureWrite { + readonly year: number; + readonly outputPath: string; + readonly sql: string; + readonly params: readonly DuckDbParam[]; +} + +export interface FeatureBatchManifest { + readonly ref: string; + readonly definitionHash: string; + readonly knownAtRule: FeatureKnownAtRule; + readonly warmupBars: number; + readonly inputs: readonly FeatureInputDataset[]; + readonly writes: readonly FeatureBatchWriteReceipt[]; +} + +const PROHIBITED_SQL_KEYWORDS: ReadonlySet = new Set([ + 'ALTER', + 'ANALYZE', + 'ATTACH', + 'BEGIN', + 'CALL', + 'CHECKPOINT', + 'COMMIT', + 'COPY', + 'CREATE', + 'DEALLOCATE', + 'DELETE', + 'DESCRIBE', + 'DETACH', + 'DROP', + 'EXECUTE', + 'EXPLAIN', + 'EXPORT', + 'GRANT', + 'IMPORT', + 'INSERT', + 'INSTALL', + 'LOAD', + 'MERGE', + 'PIVOT', + 'PRAGMA', + 'PREPARE', + 'RESET', + 'REVOKE', + 'ROLLBACK', + 'SET', + 'SHOW', + 'SUMMARIZE', + 'TRUNCATE', + 'UNPIVOT', + 'UPDATE', + 'UPSERT', + 'USE', + 'VACUUM', +]); + +const EXTERNAL_READER_IDENTIFIERS: ReadonlySet = new Set([ + 'CURRENT_SETTING', + 'DELTA_SCAN', + 'DUCKDB_COLUMNS', + 'DUCKDB_CONSTRAINTS', + 'DUCKDB_DATABASES', + 'DUCKDB_DEPENDENCIES', + 'DUCKDB_EXTENSIONS', + 'DUCKDB_FUNCTIONS', + 'DUCKDB_INDEXES', + 'DUCKDB_KEYWORDS', + 'DUCKDB_MEMORY', + 'DUCKDB_OPTIMIZERS', + 'DUCKDB_SCHEMAS', + 'DUCKDB_SECRETS', + 'DUCKDB_SEQUENCES', + 'DUCKDB_SETTINGS', + 'DUCKDB_TABLES', + 'DUCKDB_TEMPORARY_FILES', + 'DUCKDB_TYPES', + 'DUCKDB_VIEWS', + 'GETENV', + 'GLOB', + 'HTTP_GET', + 'ICEBERG_SCAN', + 'MYSQL_SCAN', + 'PARQUET_FILE_METADATA', + 'PARQUET_KV_METADATA', + 'PARQUET_METADATA', + 'PARQUET_SCAN', + 'PARQUET_SCHEMA', + 'POSTGRES_SCAN', + 'PRAGMA_DATABASE_LIST', + 'PRAGMA_STORAGE_INFO', + 'PRAGMA_TABLE_INFO', + 'READ_BLOB', + 'READ_CSV', + 'READ_CSV_AUTO', + 'READ_EXCEL', + 'READ_JSON', + 'READ_JSON_AUTO', + 'READ_NDJSON', + 'READ_NDJSON_AUTO', + 'READ_PARQUET', + 'READ_STAT', + 'READ_TEXT', + 'SQLITE_SCAN', + 'ST_READ', +]); + +/** + * Pure built-in scalar, aggregate, window, date/time, string, and type-cast + * functions permitted in declarative feature SQL. Excludes all file, network, + * catalog, secret, and system-inspection functions. + */ +const ALLOWED_SQL_FUNCTIONS: ReadonlySet = new Set([ + // Casting & type constructors + 'BIT', + 'CAST', + 'CHAR', + 'CHARACTER', + 'DECIMAL', + 'INTERVAL', + 'NUMERIC', + 'TIME', + 'TIMESTAMP', + 'TIMESTAMPTZ', + 'TRY_CAST', + 'TYPEOF', + 'VARCHAR', + // Null / conditional + 'COALESCE', + 'GREATEST', + 'IF', + 'IFNULL', + 'ISFINITE', + 'ISINF', + 'ISNAN', + 'LEAST', + 'NULLIF', + // Math + 'ABS', + 'ACOS', + 'ASIN', + 'ATAN', + 'ATAN2', + 'CBRT', + 'CEIL', + 'CEILING', + 'COS', + 'COT', + 'DEGREES', + 'EXP', + 'FLOOR', + 'LN', + 'LOG', + 'LOG10', + 'LOG2', + 'MOD', + 'PI', + 'POW', + 'POWER', + 'RADIANS', + 'ROUND', + 'SIGN', + 'SIN', + 'SQRT', + 'TAN', + 'TRUNC', + // Aggregate + 'ANY_VALUE', + 'ARG_MAX', + 'ARG_MIN', + 'AVG', + 'CORR', + 'COUNT', + 'COVAR_POP', + 'COVAR_SAMP', + 'FIRST', + 'GEOMEAN', + 'KURTOSIS', + 'LAST', + 'MAD', + 'MAX', + 'MEDIAN', + 'MIN', + 'MODE', + 'PERCENTILE_CONT', + 'PERCENTILE_DISC', + 'PRODUCT', + 'QUANTILE', + 'QUANTILE_CONT', + 'QUANTILE_DISC', + 'REGR_INTERCEPT', + 'REGR_R2', + 'REGR_SLOPE', + 'SKEWNESS', + 'STDDEV', + 'STDDEV_POP', + 'STDDEV_SAMP', + 'SUM', + 'VAR_POP', + 'VAR_SAMP', + 'VARIANCE', + // Window + 'CUME_DIST', + 'DENSE_RANK', + 'FIRST_VALUE', + 'LAG', + 'LAST_VALUE', + 'LEAD', + 'NTH_VALUE', + 'NTILE', + 'PERCENT_RANK', + 'RANK', + 'ROW_NUMBER', + // Date / time + 'DATE_ADD', + 'DATE_DIFF', + 'DATE_PART', + 'DATE_SUB', + 'DATE_TRUNC', + 'DATEDIFF', + 'DAY', + 'DAYOFWEEK', + 'DAYOFYEAR', + 'EPOCH', + 'EPOCH_MS', + 'EPOCH_NS', + 'EPOCH_US', + 'EXTRACT', + 'HOUR', + 'LAST_DAY', + 'MAKE_DATE', + 'MAKE_TIMESTAMP', + 'MINUTE', + 'MONTH', + 'QUARTER', + 'SECOND', + 'STRFTIME', + 'STRPTIME', + 'TIME_BUCKET', + 'WEEK', + 'YEAR', + // String & pure JSON + 'CONCAT', + 'CONCAT_WS', + 'CONTAINS', + 'ENDS_WITH', + 'JSON_EXTRACT', + 'JSON_EXTRACT_PATH', + 'JSON_EXTRACT_PATH_TEXT', + 'JSON_EXTRACT_STRING', + 'LEFT', + 'LENGTH', + 'LOWER', + 'LTRIM', + 'POSITION', + 'RIGHT', + 'RTRIM', + 'SPLIT_PART', + 'STARTS_WITH', + 'STRLEN', + 'STRPOS', + 'SUBSTR', + 'SUBSTRING', + 'TRIM', + 'UPPER', +]); + +/** SQL keywords that can syntactically precede `(` without being a function call. */ +const KEYWORD_BEFORE_LPAREN: ReadonlySet = new Set([ + 'ALL', + 'AND', + 'ANY', + 'AS', + 'ASC', + 'BETWEEN', + 'BY', + 'CASE', + 'DESC', + 'DISTINCT', + 'ELSE', + 'EXISTS', + 'FILTER', + 'FIRST', + 'FROM', + 'HAVING', + 'IN', + 'IS', + 'JOIN', + 'LAST', + 'NOT', + 'NULLS', + 'ON', + 'OR', + 'ORDER', + 'OVER', + 'PARTITION', + 'QUALIFY', + 'SELECT', + 'SOME', + 'THEN', + 'USING', + 'VALUES', + 'WHEN', + 'WHERE', + 'WITHIN', +]); + +const CLAUSE_TERMINATOR_KEYWORDS: ReadonlySet = new Set([ + 'EXCEPT', + 'FETCH', + 'FROM', + 'GROUP', + 'HAVING', + 'INTERSECT', + 'LIMIT', + 'OFFSET', + 'ORDER', + 'QUALIFY', + 'UNION', + 'WHERE', + 'WINDOW', +]); + +const JOIN_MODIFIER_KEYWORDS: ReadonlySet = new Set([ + 'ANTI', + 'ASOF', + 'CROSS', + 'FULL', + 'INNER', + 'JOIN', + 'LEFT', + 'NATURAL', + 'OUTER', + 'RIGHT', + 'SEMI', +]); + +const NON_ALIAS_KEYWORDS: ReadonlySet = new Set([ + ...CLAUSE_TERMINATOR_KEYWORDS, + ...JOIN_MODIFIER_KEYWORDS, + 'ON', + 'USING', +]); + +const PATH_OR_URI_PREFIX_RE = /^(?:\/|\.\/|\.\.\/|~\/|(?:s3|gs|http|https|file|hf|az|r2):\/\/)/i; +const PATH_EXTENSION_RE = /\.(?:parquet|csv|tsv|json|jsonl|ndjson|duckdb|db|sqlite|txt|gz|zst)$/i; +const PATH_GLOB_OR_TRAVERSAL_RE = /(?:^|\/)\.\.(?:\/|$)|\/\*|\*\./; + +type SqlToken = + | { readonly kind: 'word'; readonly value: string; readonly upper: string; readonly raw: string } + | { readonly kind: 'quoted_ident'; readonly value: string; readonly raw: string } + | { readonly kind: 'string'; readonly value: string; readonly raw: string } + | { readonly kind: 'number'; readonly raw: string } + | { readonly kind: 'placeholder'; readonly dataset: string; readonly raw: string } + | { readonly kind: 'lparen'; readonly raw: '(' } + | { readonly kind: 'rparen'; readonly raw: ')' } + | { readonly kind: 'comma'; readonly raw: ',' } + | { readonly kind: 'dot'; readonly raw: '.' } + | { readonly kind: 'op'; readonly raw: string }; + +interface DatasetScanSpec { + readonly relativePath: string; + readonly hivePartitioning: boolean; + readonly predicateKind: 'ts_and_known_at' | 'known_at' | 'effective_known_at'; +} + +const DATASET_SCAN_SPECS: Readonly> = { + bars_1d: { + relativePath: 'bars_1d/year=*/part.parquet', + hivePartitioning: true, + predicateKind: 'ts_and_known_at', + }, + adj_factors: { + relativePath: 'adj_factors/part.parquet', + hivePartitioning: false, + predicateKind: 'known_at', + }, + events: { + relativePath: 'events/year=*/part.parquet', + hivePartitioning: true, + predicateKind: 'ts_and_known_at', + }, + shorts: { + relativePath: 'shorts/part.parquet', + hivePartitioning: false, + predicateKind: 'known_at', + }, + fx_1d: { + relativePath: 'fx_1d/part.parquet', + hivePartitioning: false, + predicateKind: 'ts_and_known_at', + }, + fundamentals_pit: { + relativePath: 'fundamentals_pit/year=*/part.parquet', + hivePartitioning: true, + predicateKind: 'effective_known_at', + }, +}; + +function isPlainRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function compareAscii(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +function isAsciiWhitespace(code: number): boolean { + return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d || code === 0x0c; +} + +function isIdentStart(code: number): boolean { + return ( + (code >= 0x41 && code <= 0x5a) || // A-Z + (code >= 0x61 && code <= 0x7a) || // a-z + code === 0x5f // _ + ); +} + +function isIdentContinue(code: number): boolean { + return isIdentStart(code) || (code >= 0x30 && code <= 0x39); +} + +function isDigit(code: number): boolean { + return code >= 0x30 && code <= 0x39; +} + +function looksLikeExternalPath(value: string): boolean { + return ( + PATH_OR_URI_PREFIX_RE.test(value) || + PATH_EXTENSION_RE.test(value) || + PATH_GLOB_OR_TRAVERSAL_RE.test(value) + ); +} + +/** + * Quote-aware SQL tokenizer shared by validation, canonical hashing, and + * `{{input:}}` placeholder expansion. + */ +function tokenizeFeatureSql(sql: string): SqlToken[] { + const tokens: SqlToken[] = []; + const len = sql.length; + let i = 0; + + while (i < len) { + const code = sql.charCodeAt(i); + if (isAsciiWhitespace(code)) { + i += 1; + continue; + } + + // Reject SQL comments (-- or /* ... */). + if (code === 0x2d && i + 1 < len && sql.charCodeAt(i + 1) === 0x2d) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'SQL line comments ("--") are not permitted in feature definitions.' + ); + } + if (code === 0x2f && i + 1 < len && sql.charCodeAt(i + 1) === 0x2a) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'SQL block comments ("/* ... */") are not permitted in feature definitions.' + ); + } + if (code === 0x2a && i + 1 < len && sql.charCodeAt(i + 1) === 0x2f) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unexpected SQL block comment terminator ("*/") in feature definition.' + ); + } + + // Reject statement separators (;). + if (code === 0x3b) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Multiple SQL statements or semicolons (";") are not permitted in feature definitions.' + ); + } + + // Reject caller-supplied bind markers (?, $1, $name, :name). + if (code === 0x3f) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Caller-supplied bind markers ("?") are not permitted in feature definitions.' + ); + } + if (code === 0x24) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Dollar-prefixed parameters or dollar-quoted strings ("$") are not permitted in feature definitions.' + ); + } + + // Placeholder: {{input:}} + if (code === 0x7b && i + 1 < len && sql.charCodeAt(i + 1) === 0x7b) { + const closeIdx = sql.indexOf('}}', i + 2); + if (closeIdx === -1) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unterminated placeholder "{{" in feature SQL.' + ); + } + const inner = sql.slice(i + 2, closeIdx); + const match = PLACEHOLDER_INNER_RE.exec(inner); + if (match === null) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Malformed input placeholder "{{${inner}}}". Expected "{{input:}}".` + ); + } + const dataset = match[1] as string; + const raw = sql.slice(i, closeIdx + 2); + tokens.push({ kind: 'placeholder', dataset, raw }); + i = closeIdx + 2; + continue; + } + + // Single-quoted string literal ('...'). + if (code === 0x27) { + const start = i; + i += 1; + let value = ''; + let closed = false; + while (i < len) { + const c = sql.charCodeAt(i); + if (c === 0x27) { + if (i + 1 < len && sql.charCodeAt(i + 1) === 0x27) { + value += "'"; + i += 2; + continue; + } + i += 1; + closed = true; + break; + } + value += sql[i] as string; + i += 1; + } + if (!closed) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unterminated single-quoted string literal in feature SQL.' + ); + } + tokens.push({ kind: 'string', value, raw: sql.slice(start, i) }); + continue; + } + + // Double-quoted identifier ("..."). + if (code === 0x22) { + const start = i; + i += 1; + let value = ''; + let closed = false; + while (i < len) { + const c = sql.charCodeAt(i); + if (c === 0x22) { + if (i + 1 < len && sql.charCodeAt(i + 1) === 0x22) { + value += '"'; + i += 2; + continue; + } + i += 1; + closed = true; + break; + } + value += sql[i] as string; + i += 1; + } + if (!closed || value.length === 0) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unterminated or empty double-quoted identifier in feature SQL.' + ); + } + tokens.push({ kind: 'quoted_ident', value, raw: sql.slice(start, i) }); + continue; + } + + // Unquoted word (keyword or identifier). + if (isIdentStart(code)) { + const start = i; + i += 1; + while (i < len && isIdentContinue(sql.charCodeAt(i))) { + i += 1; + } + const value = sql.slice(start, i); + tokens.push({ kind: 'word', value, upper: value.toUpperCase(), raw: value }); + continue; + } + + // Numeric literal (digits or .digits). + if (isDigit(code) || (code === 0x2e && i + 1 < len && isDigit(sql.charCodeAt(i + 1)))) { + const start = i; + let hasDot = false; + if (code === 0x2e) { + hasDot = true; + i += 1; + } + while (i < len && isDigit(sql.charCodeAt(i))) { + i += 1; + } + if (!hasDot && i < len && sql.charCodeAt(i) === 0x2e) { + i += 1; + while (i < len && isDigit(sql.charCodeAt(i))) { + i += 1; + } + } + if (i < len && (sql.charCodeAt(i) === 0x65 || sql.charCodeAt(i) === 0x45)) { + const expPos = i; + i += 1; + if (i < len && (sql.charCodeAt(i) === 0x2b || sql.charCodeAt(i) === 0x2d)) { + i += 1; + } + if (i >= len || !isDigit(sql.charCodeAt(i))) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Malformed numeric exponent at offset ${expPos} in feature SQL.` + ); + } + while (i < len && isDigit(sql.charCodeAt(i))) { + i += 1; + } + } + tokens.push({ kind: 'number', raw: sql.slice(start, i) }); + continue; + } + + // Punctuation. + if (code === 0x28) { + tokens.push({ kind: 'lparen', raw: '(' }); + i += 1; + continue; + } + if (code === 0x29) { + tokens.push({ kind: 'rparen', raw: ')' }); + i += 1; + continue; + } + if (code === 0x2c) { + tokens.push({ kind: 'comma', raw: ',' }); + i += 1; + continue; + } + if (code === 0x2e) { + tokens.push({ kind: 'dot', raw: '.' }); + i += 1; + continue; + } + + // Two-character operators. + if (i + 1 < len) { + const two = sql.slice(i, i + 2); + if ( + two === '<>' || + two === '!=' || + two === '<=' || + two === '>=' || + two === '||' || + two === '::' + ) { + tokens.push({ kind: 'op', raw: two }); + i += 2; + continue; + } + } + + // Reject single ':' (named bind marker). + if (code === 0x3a) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Colon-prefixed bind markers (":name") are not permitted in feature definitions.' + ); + } + + // Single-character operators. + if ( + code === 0x2b || // + + code === 0x2d || // - + code === 0x2a || // * + code === 0x2f || // / + code === 0x25 || // % + code === 0x3d || // = + code === 0x3c || // < + code === 0x3e // > + ) { + tokens.push({ kind: 'op', raw: sql[i] as string }); + i += 1; + continue; + } + + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Unsupported token character "${sql[i] as string}" at offset ${i} in feature SQL.` + ); + } + + return tokens; +} + +function findMatchingParen(tokens: readonly SqlToken[], openIndex: number, end: number): number { + let depth = 0; + for (let i = openIndex; i < end; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + if (depth === 0) { + return i; + } + } + } + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unbalanced parentheses in feature SQL.' + ); +} + +function assertBalancedParens(tokens: readonly SqlToken[]): void { + let depth = 0; + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + if (depth < 0) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unbalanced closing parenthesis ")" in feature SQL.' + ); + } + } + } + if (depth !== 0) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unbalanced opening parenthesis "(" in feature SQL.' + ); + } +} + +function extractIdentifierText(tok: SqlToken | undefined): string | null { + if (tok === undefined) { + return null; + } + if (tok.kind === 'word') { + return tok.value.toLowerCase(); + } + if (tok.kind === 'quoted_ident') { + return tok.value; + } + return null; +} + +function extractProjectionOutputName(tokens: readonly SqlToken[], start: number, end: number): string { + if (start >= end) { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + 'Empty projection expression in final SELECT list.' + ); + } + + // Reject wildcard projections (* or alias.*) at top level of the projection item. + let depth = 0; + for (let i = start; i < end; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + } else if (depth === 0 && tok.kind === 'op' && tok.raw === '*') { + const prev = i > start ? tokens[i - 1] : undefined; + if (prev === undefined || prev.kind === 'dot') { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + 'Wildcard projections ("*" / "alias.*") are not permitted; final SELECT must explicitly project listing_id, ts, known_at, value.' + ); + } + } + } + + // Case 1: explicit `... AS ` at top level. + if (end - start >= 3) { + const asTok = tokens[end - 2]; + const aliasTok = tokens[end - 1]; + if (asTok?.kind === 'word' && asTok.upper === 'AS') { + const alias = extractIdentifierText(aliasTok); + if (alias === null) { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + 'Expected an output column identifier after AS in final SELECT projection.' + ); + } + return alias; + } + } + + // Case 2: simple column reference `` or `.`. + if (end - start === 1) { + const name = extractIdentifierText(tokens[start]); + if (name !== null) { + return name; + } + } + if (end - start === 3 && tokens[start + 1]?.kind === 'dot') { + const qual = extractIdentifierText(tokens[start]); + const col = extractIdentifierText(tokens[start + 2]); + if (qual !== null && col !== null) { + return col; + } + } + + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + 'Every expression in the final SELECT list must be a direct column reference or use an explicit AS alias matching (listing_id, ts, known_at, value).' + ); +} + +function validateExpressionSlice( + tokens: readonly SqlToken[], + start: number, + end: number, + inScopeCtes: ReadonlySet +): void { + let i = start; + while (i < end) { + const tok = tokens[i] as SqlToken; + + // Nested subquery: (SELECT ...) or (WITH ...) + if (tok.kind === 'lparen') { + const closeIdx = findMatchingParen(tokens, i, end); + const innerFirst = tokens[i + 1]; + if ( + innerFirst?.kind === 'word' && + (innerFirst.upper === 'SELECT' || innerFirst.upper === 'WITH') + ) { + validateQuerySlice(tokens, i + 1, closeIdx, inScopeCtes, false); + i = closeIdx + 1; + continue; + } + i += 1; + continue; + } + + // Callable function check: followed by '('. + if ( + (tok.kind === 'word' || tok.kind === 'quoted_ident') && + i + 1 < end && + tokens[i + 1]?.kind === 'lparen' + ) { + const upper = tok.kind === 'word' ? tok.upper : tok.value.toUpperCase(); + if (tok.kind === 'word' && KEYWORD_BEFORE_LPAREN.has(upper)) { + i += 1; + continue; + } + // Reject schema-qualified function calls (e.g. main.read_parquet(...)). + if (i > start && tokens[i - 1]?.kind === 'dot') { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Schema-qualified function call ".${tok.raw}(...)" is not permitted in feature SQL.` + ); + } + if (!ALLOWED_SQL_FUNCTIONS.has(upper)) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Unsupported or prohibited SQL function "${tok.raw}(...)" in feature SQL.` + ); + } + } + + i += 1; + } +} + +function parseTableReference( + tokens: readonly SqlToken[], + start: number, + end: number, + inScopeCtes: ReadonlySet +): number { + if (start >= end) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Expected a relation source after FROM or JOIN in feature SQL.' + ); + } + + let pos = start; + const tok = tokens[pos] as SqlToken; + + if (tok.kind === 'placeholder') { + pos += 1; + } else if (tok.kind === 'lparen') { + const closeIdx = findMatchingParen(tokens, pos, end); + const innerFirst = tokens[pos + 1]; + if ( + innerFirst === undefined || + innerFirst.kind !== 'word' || + (innerFirst.upper !== 'SELECT' && innerFirst.upper !== 'WITH') + ) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + 'Parenthesized relation source must be a SELECT or WITH subquery.' + ); + } + validateQuerySlice(tokens, pos + 1, closeIdx, inScopeCtes, false); + pos = closeIdx + 1; + } else if (tok.kind === 'word' || tok.kind === 'quoted_ident') { + // Reject table functions (`fn(...)`) and qualified catalog relations (`schema.table`). + const next = pos + 1 < end ? tokens[pos + 1] : undefined; + if (next?.kind === 'lparen') { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Table function "${tok.raw}(...)" is not permitted as a relation source in feature SQL.` + ); + } + if (next?.kind === 'dot') { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Catalog or schema-qualified relation "${tok.raw}...." is not permitted; use {{input:}} placeholders.` + ); + } + const cteName = tok.value.toLowerCase(); + if (!inScopeCtes.has(cteName)) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Direct table reference "${tok.raw}" is not an in-scope CTE; use {{input:}} placeholders.` + ); + } + pos += 1; + } else { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Unsupported relation source "${tok.raw}" in feature SQL; use {{input:}}, an in-scope CTE, or a subquery.` + ); + } + + // Optional table alias: `[AS] [(col1, col2, ...)]`. + if (pos < end) { + const maybeAs = tokens[pos] as SqlToken; + if (maybeAs.kind === 'word' && maybeAs.upper === 'AS') { + pos += 1; + if (pos >= end || (tokens[pos]?.kind !== 'word' && tokens[pos]?.kind !== 'quoted_ident')) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Expected table alias identifier after AS.' + ); + } + pos += 1; + } else if ( + (maybeAs.kind === 'word' && !NON_ALIAS_KEYWORDS.has(maybeAs.upper)) || + maybeAs.kind === 'quoted_ident' + ) { + pos += 1; + } + + // Optional column alias list `(c1, c2)`. + if (pos < end && tokens[pos]?.kind === 'lparen') { + const closeIdx = findMatchingParen(tokens, pos, end); + pos = closeIdx + 1; + } + } + + return pos; +} + +function validateSelectBranch( + tokens: readonly SqlToken[], + start: number, + end: number, + inScopeCtes: ReadonlySet, + requireContractProjection: boolean +): void { + if (start >= end) { + throw new FeatureLibraryError('INVALID_SQL_STATEMENT', 'Empty SELECT branch in feature SQL.'); + } + + // Parenthesized SELECT branch: `(SELECT ...)` + if (tokens[start]?.kind === 'lparen') { + const closeIdx = findMatchingParen(tokens, start, end); + if (closeIdx === end - 1) { + validateQuerySlice(tokens, start + 1, closeIdx, inScopeCtes, requireContractProjection); + return; + } + } + + const first = tokens[start]; + if (first?.kind !== 'word' || first.upper !== 'SELECT') { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Expected SELECT statement, got "${first?.raw ?? ''}".` + ); + } + + let pos = start + 1; + if ( + pos < end && + tokens[pos]?.kind === 'word' && + ((tokens[pos] as { upper: string }).upper === 'DISTINCT' || + (tokens[pos] as { upper: string }).upper === 'ALL') + ) { + pos += 1; + } + + // Find end of SELECT projection list (first top-level FROM or other clause terminator). + let depth = 0; + let projEnd = end; + for (let i = pos; i < end; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + } else if (depth === 0 && tok.kind === 'word' && CLAUSE_TERMINATOR_KEYWORDS.has(tok.upper)) { + projEnd = i; + break; + } + } + + if (projEnd === pos) { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + 'SELECT clause has an empty projection list.' + ); + } + + // Validate expressions inside projection list. + validateExpressionSlice(tokens, pos, projEnd, inScopeCtes); + + if (requireContractProjection) { + const itemBounds: Array<{ start: number; end: number }> = []; + let itemStart = pos; + depth = 0; + for (let i = pos; i < projEnd; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + } else if (depth === 0 && tok.kind === 'comma') { + itemBounds.push({ start: itemStart, end: i }); + itemStart = i + 1; + } + } + itemBounds.push({ start: itemStart, end: projEnd }); + + if (itemBounds.length !== FEATURE_OUTPUT_COLUMNS.length) { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + `Final SELECT must project exactly ${FEATURE_OUTPUT_COLUMNS.length} columns (${FEATURE_OUTPUT_COLUMNS.join(', ')}), got ${itemBounds.length}.` + ); + } + + for (let idx = 0; idx < FEATURE_OUTPUT_COLUMNS.length; idx += 1) { + const bound = itemBounds[idx] as { start: number; end: number }; + const actualName = extractProjectionOutputName(tokens, bound.start, bound.end); + const expectedName = FEATURE_OUTPUT_COLUMNS[idx] as string; + if (actualName !== expectedName) { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + `Final SELECT column #${idx + 1} must be named "${expectedName}", got "${actualName}".` + ); + } + } + } + + // Scan FROM / JOIN clauses and remaining clauses at paren depth 0. + pos = projEnd; + while (pos < end) { + const tok = tokens[pos] as SqlToken; + + if (tok.kind === 'word' && tok.upper === 'FROM') { + pos += 1; + // Parse one or more comma-separated table references, plus any chained JOINs. + pos = parseTableReference(tokens, pos, end, inScopeCtes); + while (pos < end) { + const nextTok = tokens[pos] as SqlToken; + if (nextTok.kind === 'comma') { + pos += 1; + pos = parseTableReference(tokens, pos, end, inScopeCtes); + continue; + } + if (nextTok.kind === 'word' && JOIN_MODIFIER_KEYWORDS.has(nextTok.upper)) { + // Consume join modifiers up to and including JOIN. + let foundJoin = false; + while (pos < end) { + const jTok = tokens[pos] as SqlToken; + if (jTok.kind === 'word' && JOIN_MODIFIER_KEYWORDS.has(jTok.upper)) { + pos += 1; + if (jTok.upper === 'JOIN') { + foundJoin = true; + break; + } + } else { + break; + } + } + if (!foundJoin) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Malformed JOIN clause in feature SQL.' + ); + } + pos = parseTableReference(tokens, pos, end, inScopeCtes); + + // Optional ON or USING (...) before next JOIN or clause terminator. + if (pos < end && tokens[pos]?.kind === 'word') { + const condKw = (tokens[pos] as { upper: string }).upper; + if (condKw === 'ON' || condKw === 'USING') { + const condStart = pos + 1; + let condEnd = end; + let cDepth = 0; + for (let k = condStart; k < end; k += 1) { + const ct = tokens[k] as SqlToken; + if (ct.kind === 'lparen') { + cDepth += 1; + } else if (ct.kind === 'rparen') { + cDepth -= 1; + } else if ( + cDepth === 0 && + (ct.kind === 'comma' || + (ct.kind === 'word' && + (CLAUSE_TERMINATOR_KEYWORDS.has(ct.upper) || + JOIN_MODIFIER_KEYWORDS.has(ct.upper)))) + ) { + condEnd = k; + break; + } + } + validateExpressionSlice(tokens, condStart, condEnd, inScopeCtes); + pos = condEnd; + } + } + continue; + } + break; + } + continue; + } + + // Remaining clause expressions (WHERE, GROUP BY, HAVING, WINDOW, QUALIFY, ORDER BY, LIMIT, OFFSET). + const exprStart = pos; + let exprEnd = end; + let eDepth = 0; + for (let k = exprStart + 1; k < end; k += 1) { + const et = tokens[k] as SqlToken; + if (et.kind === 'lparen') { + eDepth += 1; + } else if (et.kind === 'rparen') { + eDepth -= 1; + } else if (eDepth === 0 && et.kind === 'word' && et.upper === 'FROM') { + exprEnd = k; + break; + } + } + validateExpressionSlice(tokens, exprStart, exprEnd, inScopeCtes); + pos = exprEnd; + } +} + +function validateQuerySlice( + tokens: readonly SqlToken[], + start: number, + end: number, + outerCtes: ReadonlySet, + requireContractProjection: boolean +): void { + if (start >= end) { + throw new FeatureLibraryError('INVALID_SQL_STATEMENT', 'Empty SQL query in feature definition.'); + } + + const inScopeCtes = new Set(outerCtes); + let pos = start; + + // Optional leading WITH clause. + if (tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'WITH') { + pos += 1; + let isRecursive = false; + if (pos < end && tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'RECURSIVE') { + isRecursive = true; + pos += 1; + } + + while (pos < end) { + const nameTok = tokens[pos]; + if (nameTok === undefined || (nameTok.kind !== 'word' && nameTok.kind !== 'quoted_ident')) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Expected CTE name identifier after WITH in feature SQL.' + ); + } + const cteName = nameTok.value.toLowerCase(); + pos += 1; + + // Optional CTE column list `(col1, col2)`. + if (pos < end && tokens[pos]?.kind === 'lparen') { + pos = findMatchingParen(tokens, pos, end) + 1; + } + + if (pos >= end || tokens[pos]?.kind !== 'word' || (tokens[pos] as { upper: string }).upper !== 'AS') { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Expected AS after CTE name "${nameTok.raw}" in feature SQL.` + ); + } + pos += 1; + + // Optional `[NOT] MATERIALIZED`. + if (pos < end && tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'NOT') { + pos += 1; + } + if ( + pos < end && + tokens[pos]?.kind === 'word' && + (tokens[pos] as { upper: string }).upper === 'MATERIALIZED' + ) { + pos += 1; + } + + if (pos >= end || tokens[pos]?.kind !== 'lparen') { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Expected "(" opening CTE body for "${nameTok.raw}" in feature SQL.` + ); + } + const bodyClose = findMatchingParen(tokens, pos, end); + if (isRecursive) { + inScopeCtes.add(cteName); + } + validateQuerySlice(tokens, pos + 1, bodyClose, inScopeCtes, false); + inScopeCtes.add(cteName); + pos = bodyClose + 1; + + if (pos < end && tokens[pos]?.kind === 'comma') { + pos += 1; + continue; + } + break; + } + } + + // Split remaining query by top-level set operators (UNION [ALL|DISTINCT], INTERSECT, EXCEPT). + const branches: Array<{ start: number; end: number }> = []; + let branchStart = pos; + let depth = 0; + for (let i = pos; i < end; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + } else if ( + depth === 0 && + tok.kind === 'word' && + (tok.upper === 'UNION' || tok.upper === 'INTERSECT' || tok.upper === 'EXCEPT') + ) { + branches.push({ start: branchStart, end: i }); + let nextPos = i + 1; + if ( + nextPos < end && + tokens[nextPos]?.kind === 'word' && + ((tokens[nextPos] as { upper: string }).upper === 'ALL' || + (tokens[nextPos] as { upper: string }).upper === 'DISTINCT') + ) { + nextPos += 1; + } + branchStart = nextPos; + i = nextPos - 1; + } + } + branches.push({ start: branchStart, end }); + + for (let b = 0; b < branches.length; b += 1) { + const branch = branches[b] as { start: number; end: number }; + validateSelectBranch(tokens, branch.start, branch.end, inScopeCtes, requireContractProjection); + } +} + +interface ValidatedFeatureInternal { + readonly def: FeatureDefinition; + readonly tokens: readonly SqlToken[]; + readonly normalizedInputs: readonly FeatureInputDataset[]; +} + +function validateName(name: unknown): string { + if (typeof name !== 'string' || !FEATURE_NAME_RE.test(name)) { + throw new FeatureLibraryError( + 'INVALID_NAME', + `Invalid feature name "${String(name)}". Expected ^[a-z][a-z0-9_]{0,62}$.` + ); + } + return name; +} + +function validateVersion(version: unknown): number { + if (typeof version !== 'number' || !Number.isSafeInteger(version) || version < 1) { + throw new FeatureLibraryError( + 'INVALID_VERSION', + `Invalid feature version "${String(version)}". Expected a positive safe integer.` + ); + } + return version; +} + +function validateFeatureDefinitionInternal(def: FeatureDefinition): ValidatedFeatureInternal { + if (!isPlainRecord(def)) { + throw new FeatureLibraryError( + 'INVALID_DEFINITION', + 'Feature definition must be a plain object.' + ); + } + + validateName(def.name); + validateVersion(def.version); + + if (typeof def.family !== 'string' || !FEATURE_FAMILY_SET.has(def.family)) { + throw new FeatureLibraryError( + 'INVALID_FAMILY', + `Invalid feature family "${String(def.family)}". Expected one of: ${FEATURE_FAMILIES.join(', ')}.` + ); + } + + if (def.kind !== 'duckdb_sql') { + throw new FeatureLibraryError( + 'INVALID_KIND', + `Invalid feature kind "${String(def.kind)}". Expected 'duckdb_sql'.` + ); + } + + if (typeof def.warmupBars !== 'number' || !Number.isSafeInteger(def.warmupBars) || def.warmupBars < 0) { + throw new FeatureLibraryError( + 'INVALID_WARMUP_BARS', + `Invalid warmupBars "${String(def.warmupBars)}". Expected a non-negative safe integer.` + ); + } + + if (typeof def.knownAtRule !== 'string' || !FEATURE_KNOWN_AT_RULE_SET.has(def.knownAtRule)) { + throw new FeatureLibraryError( + 'INVALID_KNOWN_AT_RULE', + `Invalid knownAtRule "${String(def.knownAtRule)}". Expected one of: ${FEATURE_KNOWN_AT_RULES.join(', ')}.` + ); + } + + if (def.description !== undefined && typeof def.description !== 'string') { + throw new FeatureLibraryError( + 'INVALID_DEFINITION', + 'Feature description must be a string when provided.' + ); + } + + if (!Array.isArray(def.inputs) || def.inputs.length === 0) { + throw new FeatureLibraryError( + 'INVALID_DEFINITION', + 'Feature definition must declare a non-empty inputs array.' + ); + } + + const declaredSet = new Set(); + const normalizedInputs: FeatureInputDataset[] = []; + for (let i = 0; i < def.inputs.length; i += 1) { + const rawInput: unknown = def.inputs[i]; + if (typeof rawInput !== 'string' || !FEATURE_INPUT_SET.has(rawInput)) { + throw new FeatureLibraryError( + 'UNSUPPORTED_INPUT_DATASET', + `Unsupported input dataset "${String(rawInput)}". Allowed datasets: ${FEATURE_INPUT_DATASETS.join(', ')}.` + ); + } + const ds = rawInput as FeatureInputDataset; + if (!declaredSet.has(ds)) { + declaredSet.add(ds); + normalizedInputs.push(ds); + } + } + + if (typeof def.sql !== 'string' || def.sql.trim().length === 0) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Feature SQL must be a non-empty string.' + ); + } + + const tokens = tokenizeFeatureSql(def.sql); + if (tokens.length === 0) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Feature SQL must contain a SELECT or WITH statement.' + ); + } + + // Pass 1: check prohibited statement/operation keywords. + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'word' && PROHIBITED_SQL_KEYWORDS.has(tok.upper)) { + throw new FeatureLibraryError( + 'PROHIBITED_SQL_OPERATION', + `Prohibited SQL operation "${tok.raw}" is not permitted in feature definitions.` + ); + } + } + + // Pass 2: check external readers and quoted file paths/URIs. + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'word' && EXTERNAL_READER_IDENTIFIERS.has(tok.upper)) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Direct external reader "${tok.raw}" is not permitted; reference datasets via {{input:}}.` + ); + } + if (tok.kind === 'quoted_ident' && EXTERNAL_READER_IDENTIFIERS.has(tok.value.toUpperCase())) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Direct external reader ${tok.raw} is not permitted; reference datasets via {{input:}}.` + ); + } + if ((tok.kind === 'string' || tok.kind === 'quoted_ident') && looksLikeExternalPath(tok.value)) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Quoted file path or URI ${tok.raw} is not permitted in feature SQL; reference datasets via {{input:}}.` + ); + } + } + + // Pass 3: check leading statement keyword and balanced parentheses. + const firstTok = tokens[0] as SqlToken; + if (firstTok.kind !== 'word' || (firstTok.upper !== 'SELECT' && firstTok.upper !== 'WITH')) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Feature SQL must begin with SELECT or WITH, got "${firstTok.raw}".` + ); + } + assertBalancedParens(tokens); + + // Pass 4: structural validation of CTEs, FROM/JOIN sources, functions, and final projection. + validateQuerySlice(tokens, 0, tokens.length, new Set(), true); + + // Pass 5: verify placeholder declarations and usage. + const usedInputs = new Set(); + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind !== 'placeholder') { + continue; + } + if (!declaredSet.has(tok.dataset as FeatureInputDataset)) { + throw new FeatureLibraryError( + 'UNDECLARED_INPUT', + `SQL placeholder "{{input:${tok.dataset}}}" is not declared in definition.inputs.` + ); + } + usedInputs.add(tok.dataset as FeatureInputDataset); + } + + for (let i = 0; i < normalizedInputs.length; i += 1) { + const declared = normalizedInputs[i] as FeatureInputDataset; + if (!usedInputs.has(declared)) { + throw new FeatureLibraryError( + 'UNUSED_INPUT', + `Declared input dataset "${declared}" is not referenced via "{{input:${declared}}}" in feature SQL.` + ); + } + } + + return { def, tokens, normalizedInputs }; +} + +/** + * Validates a declarative feature definition and throws a typed + * {@link FeatureLibraryError} on any contract, SQL safety, projection, or + * input-declaration violation. + */ +export function validateFeatureDefinition(def: FeatureDefinition): void { + validateFeatureDefinitionInternal(def); +} + +/** + * Formats the canonical versioned feature reference `'@v'`. + */ +export function featureRef(def: Pick): string { + if (!isPlainRecord(def)) { + throw new FeatureLibraryError( + 'INVALID_DEFINITION', + 'Expected an object with name and version for featureRef.' + ); + } + const name = validateName(def.name); + const version = validateVersion(def.version); + return `${name}@v${version}`; +} + +/** + * Parses a canonical versioned feature reference `'@v'`, + * rejecting non-canonical forms such as `'ret_1d@v01'` or `'RSI-14@v1'`. + */ +export function parseFeatureRef(ref: string): FeatureRefParts { + if (typeof ref !== 'string') { + throw new FeatureLibraryError( + 'INVALID_FEATURE_REF', + `Invalid feature ref "${String(ref)}". Expected "@v".` + ); + } + const match = FEATURE_REF_RE.exec(ref); + if (match === null) { + throw new FeatureLibraryError( + 'INVALID_FEATURE_REF', + `Invalid feature ref "${ref}". Expected "@v" with lowercase name and canonical positive integer version.` + ); + } + const name = match[1] as string; + const version = Number(match[2]); + if (!Number.isSafeInteger(version) || version < 1) { + throw new FeatureLibraryError( + 'INVALID_FEATURE_REF', + `Invalid feature version in ref "${ref}". Expected a positive safe integer.` + ); + } + return Object.freeze({ name, version }); +} + +function canonicalizeSqlTokens(tokens: readonly SqlToken[]): string { + const parts = new Array(tokens.length); + for (let i = 0; i < tokens.length; i += 1) { + parts[i] = (tokens[i] as SqlToken).raw; + } + return parts.join(' '); +} + +/** + * Computes a deterministic 64-character lowercase SHA-256 hex digest over the + * semantic specification of a validated feature definition (name, version, + * kind, canonicalized SQL tokens, sorted inputs, `warmupBars`, and + * `knownAtRule`). Inter-token whitespace, object key order, and input array + * order do not affect the hash; literal whitespace and semantic changes do. + */ +export function featureDefinitionHash(def: FeatureDefinition): string { + const validated = validateFeatureDefinitionInternal(def); + const sortedInputs = [...validated.normalizedInputs].sort(compareAscii); + const canonicalPayload = JSON.stringify({ + name: def.name, + version: def.version, + kind: def.kind, + sql: canonicalizeSqlTokens(validated.tokens), + inputs: sortedInputs, + warmupBars: def.warmupBars, + knownAtRule: def.knownAtRule, + }); + return sha256HexUtf8(canonicalPayload); +} + +function cloneFeatureDefinition(def: FeatureDefinition): FeatureDefinition { + const copy: FeatureDefinition = { + name: def.name, + version: def.version, + family: def.family, + kind: def.kind, + sql: def.sql, + inputs: Object.freeze([...def.inputs]), + warmupBars: def.warmupBars, + knownAtRule: def.knownAtRule, + ...(def.description !== undefined ? { description: def.description } : {}), + }; + return Object.freeze(copy); +} + +/** + * Creates an in-memory immutable versioned feature registry (`registerSignal` + * SDK entrypoint, D11). Re-registering an identical definition hash is + * idempotent; re-registering the same `@v` with a different + * semantic hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. + */ +export function createFeatureRegistry(): FeatureRegistry { + const entries = new Map(); + + return { + registerSignal(def: FeatureDefinition): RegisteredFeature { + validateFeatureDefinitionInternal(def); + const ref = featureRef(def); + const definitionHash = featureDefinitionHash(def); + const existing = entries.get(ref); + if (existing !== undefined) { + if (existing.definitionHash === definitionHash) { + return Object.freeze({ + ref: existing.ref, + definitionHash: existing.definitionHash, + definition: cloneFeatureDefinition(existing.definition), + }); + } + throw new FeatureLibraryError( + 'FEATURE_VERSION_IMMUTABLE', + `Feature "${ref}" is already registered with hash ${existing.definitionHash}; cannot overwrite with ${definitionHash}. Bump version to register a changed definition.`, + { ref } + ); + } + + const stored: RegisteredFeature = Object.freeze({ + ref, + definitionHash, + definition: cloneFeatureDefinition(def), + }); + entries.set(ref, stored); + return Object.freeze({ + ref: stored.ref, + definitionHash: stored.definitionHash, + definition: cloneFeatureDefinition(stored.definition), + }); + }, + + get(ref: string): FeatureDefinition | undefined { + if (typeof ref !== 'string') { + return undefined; + } + const existing = entries.get(ref); + return existing !== undefined ? cloneFeatureDefinition(existing.definition) : undefined; + }, + + list(): readonly string[] { + return Array.from(entries.keys()); + }, + }; +} + +function joinCuratedPath(normalizedRoot: string, relativePath: string): string { + return normalizedRoot === '/' ? `/${relativePath}` : `${normalizedRoot}/${relativePath}`; +} + +function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { + const isoMs = new Date(epochMs).toISOString(); + if (subMsMicros === 0) { + return isoMs; + } + const extra = String(subMsMicros).padStart(3, '0'); + return `${isoMs.slice(0, -1)}${extra}Z`; +} + +function validateFourDigitYear(value: unknown, field: string): number { + if ( + typeof value !== 'number' || + !Number.isSafeInteger(value) || + value < MIN_FOUR_DIGIT_YEAR || + value > MAX_FOUR_DIGIT_YEAR + ) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + `Invalid "${field}": "${String(value)}". Expected a four-digit integer year (${MIN_FOUR_DIGIT_YEAR}..${MAX_FOUR_DIGIT_YEAR}).` + ); + } + return value; +} + +function parseVaultCutoffDateMs(raw: unknown): number { + if (typeof raw !== 'string' || !DATE_ONLY_RE.test(raw)) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + `Invalid "vaultCutoffDate": "${String(raw)}". Expected strict UTC YYYY-MM-DD date string.` + ); + } + try { + const parsed = applyVaultFence( + { from: raw, to: raw, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + return parsed.fromMs; + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + `Invalid "vaultCutoffDate": ${error.message}`, + { cause: error } + ); + } + throw error; + } +} + +function expandSqlForYear( + tokens: readonly SqlToken[], + curatedRoot: string, + tsUpperIso: string, + knownAtUpperIso: string +): { sql: string; scanParams: DuckDbParam[] } { + const scanParams: DuckDbParam[] = []; + const parts: string[] = []; + + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'placeholder') { + const ds = tok.dataset as FeatureInputDataset; + const spec = DATASET_SCAN_SPECS[ds]; + const fullPath = joinCuratedPath(curatedRoot, spec.relativePath); + const readCall = spec.hivePartitioning + ? `read_parquet('${fullPath}', hive_partitioning = true)` + : `read_parquet('${fullPath}')`; + + if (spec.predicateKind === 'ts_and_known_at') { + parts.push(`(SELECT * FROM ${readCall} WHERE ts <= ? AND known_at <= ?)`); + scanParams.push(tsUpperIso, knownAtUpperIso); + } else if (spec.predicateKind === 'effective_known_at') { + parts.push(`(SELECT * FROM ${readCall} WHERE effective_known_at <= ?)`); + scanParams.push(knownAtUpperIso); + } else { + parts.push(`(SELECT * FROM ${readCall} WHERE known_at <= ?)`); + scanParams.push(knownAtUpperIso); + } + continue; + } + + parts.push(tok.raw); + } + + return { + sql: parts.join(' '), + scanParams, + }; +} + +/** + * Plans ordered yearly Vault-fenced DuckDB `COPY ... TO ... (FORMAT PARQUET, + * COMPRESSION ZSTD)` statements for a validated feature definition. + */ +export function planFeatureBatch( + def: FeatureDefinition, + options: PlanFeatureBatchOptions +): readonly PlannedFeatureWrite[] { + const validated = validateFeatureDefinitionInternal(def); + + if (!isPlainRecord(options)) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + 'Feature batch options must be a plain object.' + ); + } + + let curatedRoot: string; + try { + curatedRoot = validateCuratedRoot(options.curatedRoot); + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + throw new FeatureLibraryError('INVALID_BATCH_OPTIONS', error.message, { cause: error }); + } + throw error; + } + + const fromYear = validateFourDigitYear(options.fromYear, 'fromYear'); + const toYear = validateFourDigitYear(options.toYear, 'toYear'); + if (fromYear > toYear) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + `Invalid year range: fromYear (${fromYear}) must not exceed toYear (${toYear}).` + ); + } + + const cutoffMs = parseVaultCutoffDateMs(options.vaultCutoffDate); + const rangeFrom = `${String(fromYear).padStart(4, '0')}-01-01`; + const rangeTo = `${String(toYear).padStart(4, '0')}-12-31`; + + let fenced; + try { + fenced = applyVaultFence( + { from: rangeFrom, to: rangeTo, scope: 'vault_fenced' }, + { vaultCutoffTs: cutoffMs } + ); + } catch (error) { + if (error instanceof VaultHoldoutFenceError) { + throw new FeatureLibraryError( + 'VAULT_RANGE_VIOLATION', + `Requested year range [${fromYear}, ${toYear}] falls on or after vaultCutoffDate "${options.vaultCutoffDate}".`, + { cause: error } + ); + } + if (error instanceof MarketDataStoreValidationError) { + throw new FeatureLibraryError('INVALID_BATCH_OPTIONS', error.message, { cause: error }); + } + throw error; + } + + const lastPlannedYear = Math.min(toYear, new Date(fenced.toMs).getUTCFullYear()); + if (lastPlannedYear < fromYear) { + throw new FeatureLibraryError( + 'VAULT_RANGE_VIOLATION', + `No pre-cutoff years remain in [${fromYear}, ${toYear}] for vaultCutoffDate "${options.vaultCutoffDate}".` + ); + } + + // Last included Parquet microsecond strictly before vaultCutoffDate (00:00:00.000Z). + const vaultCeilingMs = cutoffMs - 1; + const knownAtUpperIso = formatUtcIsoWithMicros(vaultCeilingMs, 999); + + const writes: PlannedFeatureWrite[] = []; + for (let year = fromYear; year <= lastPlannedYear; year += 1) { + const yearEndMs = Date.UTC(year, 11, 31, 23, 59, 59, 999); + const effectiveTsEndMs = Math.min(yearEndMs, vaultCeilingMs); + const tsUpperIso = formatUtcIsoWithMicros(effectiveTsEndMs, 999); + + const { sql: expandedSql, scanParams } = expandSqlForYear( + validated.tokens, + curatedRoot, + tsUpperIso, + knownAtUpperIso + ); + + const outputPath = joinCuratedPath( + curatedRoot, + `features/${def.name}/v${def.version}/year=${year}/part.parquet` + ); + + const sql = + 'COPY (SELECT CAST(listing_id AS INTEGER) AS listing_id, ts, known_at, CAST(value AS DOUBLE) AS value ' + + `FROM (${expandedSql}) AS __feature_source ` + + 'WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ' + + `ORDER BY listing_id, ts) TO '${outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)`; + + const params: DuckDbParam[] = [...scanParams, year, tsUpperIso, knownAtUpperIso]; + + writes.push( + Object.freeze({ + year, + outputPath, + sql, + params: Object.freeze(params), + }) + ); + } + + return Object.freeze(writes); +} + +/** + * Validates and plans a feature batch upfront, executes each yearly Parquet + * `COPY` sequentially via `executor.query(sql, params)`, and returns a + * manifest. Stops on the first executor failure and throws + * `FeatureLibraryError('BATCH_WRITE_FAILED')` exposing `cause`, `failedYear`, + * `completedYears`, and `completedWrites`. + */ +export async function runFeatureBatch( + def: FeatureDefinition, + options: PlanFeatureBatchOptions, + executor: DuckDbExecutor +): Promise { + if ( + typeof executor !== 'object' || + executor === null || + typeof (executor as { query?: unknown }).query !== 'function' + ) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + 'Expected a DuckDbExecutor object with a query(sql, params) method.' + ); + } + + const plannedWrites = planFeatureBatch(def, options); + const ref = featureRef(def); + const definitionHash = featureDefinitionHash(def); + const sortedInputs = [...new Set(def.inputs)].sort(compareAscii); + + const completedWrites: FeatureBatchWriteReceipt[] = []; + for (let i = 0; i < plannedWrites.length; i += 1) { + const write = plannedWrites[i] as PlannedFeatureWrite; + try { + await executor.query(write.sql, write.params); + } catch (cause) { + const completedYears = completedWrites.map(w => w.year); + throw new FeatureLibraryError( + 'BATCH_WRITE_FAILED', + `Feature batch write failed for "${ref}" on year ${write.year} (completed years: ${completedYears.length > 0 ? completedYears.join(', ') : 'none'}).`, + { + cause, + failedYear: write.year, + completedYears, + completedWrites, + ref, + } + ); + } + completedWrites.push( + Object.freeze({ + year: write.year, + outputPath: write.outputPath, + }) + ); + } + + return Object.freeze({ + ref, + definitionHash, + knownAtRule: def.knownAtRule, + warmupBars: def.warmupBars, + inputs: Object.freeze(sortedInputs), + writes: Object.freeze(completedWrites), + }); +} + +/** + * Built-in example feature definition (`ret_1d@v1`): 1-day simple raw-close + * return per listing with bar-close availability (`known_at = ts`) and 1-bar + * warm-up. Omits rows without a usable positive prior close. + * + * Comparison baseline: zero return (`0.0`); no execution or transaction cost + * model is included. + */ +export const RET_1D_V1: FeatureDefinition = Object.freeze({ + name: 'ret_1d', + version: 1, + family: 'technical', + kind: 'duckdb_sql', + inputs: Object.freeze(['bars_1d'] as const), + warmupBars: 1, + knownAtRule: 'bar_close', + description: + '1-day simple raw-close return per listing with bar-close availability; comparison baseline is 0 return with no execution or cost model.', + sql: [ + 'WITH lagged AS (', + ' SELECT', + ' listing_id,', + ' ts,', + ' close,', + ' LAG(close) OVER (PARTITION BY listing_id ORDER BY ts ASC) AS prev_close', + ' FROM {{input:bars_1d}}', + ')', + 'SELECT', + ' listing_id,', + ' ts,', + ' ts AS known_at,', + ' (close / prev_close) - 1.0 AS value', + 'FROM lagged', + 'WHERE prev_close IS NOT NULL AND prev_close > 0 AND close > 0', + ].join('\n'), +}); diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index 3d57d822..0a9f6987 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -1,6 +1,7 @@ // The default entrypoint is browser safe; server validation is an explicit subpath. export * from './dataset-contracts'; export * from './event-panel'; +export * from './feature-library'; export * from './market-data-store'; export * from './market-data-store-duckdb'; export * from './signal-panel'; diff --git a/libs/research/src/sha256.ts b/libs/research/src/sha256.ts new file mode 100644 index 00000000..d4c6febc --- /dev/null +++ b/libs/research/src/sha256.ts @@ -0,0 +1,105 @@ +/** + * Browser-safe, dependency-free FIPS 180-4 SHA-256 hex digest helper. + * + * Internal module shared by `trial-ledger.ts` and `feature-library.ts`. + */ + +// FIPS 180-4 SHA-256 round constants. +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]); + +const UTF8_ENCODER = new TextEncoder(); + +export function sha256HexUtf8(text: string): string { + const bytes = UTF8_ENCODER.encode(text); + const byteLen = bytes.length; + const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0; + const buffer = new Uint8Array(paddedLen); + buffer.set(bytes); + buffer[byteLen] = 0x80; + + const view = new DataView(buffer.buffer); + const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000); + const bitLenLow = (byteLen * 8) >>> 0; + view.setUint32(paddedLen - 8, bitLenHigh, false); + view.setUint32(paddedLen - 4, bitLenLow, false); + + let h0 = 0x6a09e667; + let h1 = 0xbb67ae85; + let h2 = 0x3c6ef372; + let h3 = 0xa54ff53a; + let h4 = 0x510e527f; + let h5 = 0x9b05688c; + let h6 = 0x1f83d9ab; + let h7 = 0x5be0cd19; + + const w = new Uint32Array(64); + + for (let offset = 0; offset < paddedLen; offset += 64) { + for (let i = 0; i < 16; i += 1) { + w[i] = view.getUint32(offset + i * 4, false); + } + for (let i = 16; i < 64; i += 1) { + const w15 = w[i - 15] as number; + const w2 = w[i - 2] as number; + const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3); + const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10); + w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0; + } + + let a = h0; + let b = h1; + let c = h2; + let d = h3; + let e = h4; + let f = h5; + let g = h6; + let h = h7; + + for (let i = 0; i < 64; i += 1) { + const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); + const ch = (e & f) ^ (~e & g); + const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0; + const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); + const maj = (a & b) ^ (a & c) ^ (b & c); + const temp2 = (s0 + maj) | 0; + + h = g; + g = f; + f = e; + e = (d + temp1) | 0; + d = c; + c = b; + b = a; + a = (temp1 + temp2) | 0; + } + + h0 = (h0 + a) >>> 0; + h1 = (h1 + b) >>> 0; + h2 = (h2 + c) >>> 0; + h3 = (h3 + d) >>> 0; + h4 = (h4 + e) >>> 0; + h5 = (h5 + f) >>> 0; + h6 = (h6 + g) >>> 0; + h7 = (h7 + h) >>> 0; + } + + return ( + h0.toString(16).padStart(8, '0') + + h1.toString(16).padStart(8, '0') + + h2.toString(16).padStart(8, '0') + + h3.toString(16).padStart(8, '0') + + h4.toString(16).padStart(8, '0') + + h5.toString(16).padStart(8, '0') + + h6.toString(16).padStart(8, '0') + + h7.toString(16).padStart(8, '0') + ); +} diff --git a/libs/research/src/trial-ledger.ts b/libs/research/src/trial-ledger.ts index bc89a636..fedddfbc 100644 --- a/libs/research/src/trial-ledger.ts +++ b/libs/research/src/trial-ledger.ts @@ -18,6 +18,7 @@ import { VaultHoldoutFenceError, applyVaultFence, } from './market-data-store'; +import { sha256HexUtf8 } from './sha256'; export const TRIAL_STAGES = ['signal_ic', 'event_study', 'screen', 'engine_backtest'] as const; export type TrialStage = (typeof TRIAL_STAGES)[number]; @@ -222,106 +223,6 @@ const SELECT_TRIAL_COLUMNS = ` kurtosis, daily_series`; -// FIPS 180-4 SHA-256 round constants. -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, -]); - -const UTF8_ENCODER = new TextEncoder(); - -function sha256HexUtf8(text: string): string { - const bytes = UTF8_ENCODER.encode(text); - const byteLen = bytes.length; - const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0; - const buffer = new Uint8Array(paddedLen); - buffer.set(bytes); - buffer[byteLen] = 0x80; - - const view = new DataView(buffer.buffer); - const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000); - const bitLenLow = (byteLen * 8) >>> 0; - view.setUint32(paddedLen - 8, bitLenHigh, false); - view.setUint32(paddedLen - 4, bitLenLow, false); - - let h0 = 0x6a09e667; - let h1 = 0xbb67ae85; - let h2 = 0x3c6ef372; - let h3 = 0xa54ff53a; - let h4 = 0x510e527f; - let h5 = 0x9b05688c; - let h6 = 0x1f83d9ab; - let h7 = 0x5be0cd19; - - const w = new Uint32Array(64); - - for (let offset = 0; offset < paddedLen; offset += 64) { - for (let i = 0; i < 16; i += 1) { - w[i] = view.getUint32(offset + i * 4, false); - } - for (let i = 16; i < 64; i += 1) { - const w15 = w[i - 15] as number; - const w2 = w[i - 2] as number; - const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3); - const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10); - w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0; - } - - let a = h0; - let b = h1; - let c = h2; - let d = h3; - let e = h4; - let f = h5; - let g = h6; - let h = h7; - - for (let i = 0; i < 64; i += 1) { - const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); - const ch = (e & f) ^ (~e & g); - const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0; - const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); - const maj = (a & b) ^ (a & c) ^ (b & c); - const temp2 = (s0 + maj) | 0; - - h = g; - g = f; - f = e; - e = (d + temp1) | 0; - d = c; - c = b; - b = a; - a = (temp1 + temp2) | 0; - } - - h0 = (h0 + a) >>> 0; - h1 = (h1 + b) >>> 0; - h2 = (h2 + c) >>> 0; - h3 = (h3 + d) >>> 0; - h4 = (h4 + e) >>> 0; - h5 = (h5 + f) >>> 0; - h6 = (h6 + g) >>> 0; - h7 = (h7 + h) >>> 0; - } - - return ( - h0.toString(16).padStart(8, '0') + - h1.toString(16).padStart(8, '0') + - h2.toString(16).padStart(8, '0') + - h3.toString(16).padStart(8, '0') + - h4.toString(16).padStart(8, '0') + - h5.toString(16).padStart(8, '0') + - h6.toString(16).padStart(8, '0') + - h7.toString(16).padStart(8, '0') - ); -} - function compareAscii(a: string, b: string): number { return a < b ? -1 : a > b ? 1 : 0; } diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts new file mode 100644 index 00000000..564cf376 --- /dev/null +++ b/libs/research/test/feature-library.test.ts @@ -0,0 +1,953 @@ +import { describe, expect, it } from 'bun:test'; +import { + type DuckDbExecutor, + type DuckDbParam, + FEATURE_FAMILIES, + FEATURE_INPUT_DATASETS, + FEATURE_KINDS, + FEATURE_KNOWN_AT_RULES, + FEATURE_OUTPUT_COLUMNS, + type FeatureDefinition, + FeatureLibraryError, + type FeatureLibraryErrorCode, + RET_1D_V1, + type TableRow, + createFeatureRegistry, + featureDefinitionHash, + featureRef, + parseFeatureRef, + planFeatureBatch, + runFeatureBatch, + validateFeatureDefinition, +} from '@stock-bot/research'; +import { + FEATURE_FAMILIES as subpathFeatureFamilies, + FEATURE_INPUT_DATASETS as subpathFeatureInputDatasets, + FEATURE_KINDS as subpathFeatureKinds, + FEATURE_KNOWN_AT_RULES as subpathFeatureKnownAtRules, + FEATURE_OUTPUT_COLUMNS as subpathFeatureOutputColumns, + FeatureLibraryError as SubpathFeatureLibraryError, + RET_1D_V1 as subpathRet1dV1, + createFeatureRegistry as subpathCreateFeatureRegistry, + featureDefinitionHash as subpathFeatureDefinitionHash, + featureRef as subpathFeatureRef, + parseFeatureRef as subpathParseFeatureRef, + planFeatureBatch as subpathPlanFeatureBatch, + runFeatureBatch as subpathRunFeatureBatch, + validateFeatureDefinition as subpathValidateFeatureDefinition, +} from '@stock-bot/research/feature-library'; + +interface RecordedQuery { + readonly sql: string; + readonly params: readonly DuckDbParam[]; +} + +interface RecordingFakeExecutor { + readonly executor: DuckDbExecutor; + readonly calls: RecordedQuery[]; + readonly runCalls: string[]; +} + +function createRecordingFakeExecutor(opts?: { + onQuery?: (sql: string, params: readonly DuckDbParam[], callIndex: number) => Promise | void; +}): RecordingFakeExecutor { + const calls: RecordedQuery[] = []; + const runCalls: string[] = []; + + const executor: DuckDbExecutor = { + async run(sql: string): Promise { + runCalls.push(sql); + }, + async query(sql: string, params: readonly DuckDbParam[]): Promise { + const idx = calls.length; + calls.push({ sql, params: [...params] }); + if (opts?.onQuery !== undefined) { + await opts.onQuery(sql, params, idx); + } + return []; + }, + }; + + return { executor, calls, runCalls }; +} + +function expectFeatureErrorCode(fn: () => unknown, expectedCode: FeatureLibraryErrorCode): FeatureLibraryError { + try { + fn(); + } catch (error) { + expect(error).toBeInstanceOf(FeatureLibraryError); + const typed = error as FeatureLibraryError; + expect(typed.code).toBe(expectedCode); + return typed; + } + throw new Error(`Expected FeatureLibraryError(${expectedCode}) to be thrown, but succeeded.`); +} + +function makeSimpleDef(overrides: Partial = {}): FeatureDefinition { + return { + name: 'close_raw', + version: 1, + family: 'technical', + kind: 'duckdb_sql', + inputs: ['bars_1d'], + warmupBars: 0, + knownAtRule: 'bar_close', + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', + ...overrides, + }; +} + +describe('feature-library barrel and subpath exports', () => { + it('exposes identical symbols from @stock-bot/research and @stock-bot/research/feature-library', () => { + expect(FEATURE_FAMILIES).toBe(subpathFeatureFamilies); + expect(FEATURE_INPUT_DATASETS).toBe(subpathFeatureInputDatasets); + expect(FEATURE_KINDS).toBe(subpathFeatureKinds); + expect(FEATURE_KNOWN_AT_RULES).toBe(subpathFeatureKnownAtRules); + expect(FEATURE_OUTPUT_COLUMNS).toBe(subpathFeatureOutputColumns); + expect(FeatureLibraryError).toBe(SubpathFeatureLibraryError); + expect(RET_1D_V1).toBe(subpathRet1dV1); + expect(createFeatureRegistry).toBe(subpathCreateFeatureRegistry); + expect(featureDefinitionHash).toBe(subpathFeatureDefinitionHash); + expect(featureRef).toBe(subpathFeatureRef); + expect(parseFeatureRef).toBe(subpathParseFeatureRef); + expect(planFeatureBatch).toBe(subpathPlanFeatureBatch); + expect(runFeatureBatch).toBe(subpathRunFeatureBatch); + expect(validateFeatureDefinition).toBe(subpathValidateFeatureDefinition); + }); +}); + +describe('featureRef and parseFeatureRef', () => { + it('round-trips canonical refs such as ret_1d@v1', () => { + const ref = featureRef(RET_1D_V1); + expect(ref).toBe('ret_1d@v1'); + expect(parseFeatureRef(ref)).toEqual({ name: 'ret_1d', version: 1 }); + expect(parseFeatureRef('rsi_14@v12')).toEqual({ name: 'rsi_14', version: 12 }); + }); + + it('rejects malformed, non-canonical, and unsafe refs', () => { + const invalidRefs = [ + '', + 'ret_1d', + 'ret_1d@1', + 'ret_1d@v0', + 'ret_1d@v01', + 'ret_1d@v-1', + 'ret_1d@v1.5', + 'RSI-14@v1', + '1abc@v1', + `${'a'.repeat(64)}@v1`, + 'ret_1d@v9007199254740992', + ]; + for (const bad of invalidRefs) { + expectFeatureErrorCode(() => parseFeatureRef(bad), 'INVALID_FEATURE_REF'); + } + expectFeatureErrorCode(() => parseFeatureRef(null as unknown as string), 'INVALID_FEATURE_REF'); + expectFeatureErrorCode(() => featureRef({ name: 'RSI-14', version: 1 }), 'INVALID_NAME'); + expectFeatureErrorCode(() => featureRef({ name: 'ret_1d', version: 0 }), 'INVALID_VERSION'); + expectFeatureErrorCode(() => featureRef({ name: 'ret_1d', version: 1.5 }), 'INVALID_VERSION'); + expectFeatureErrorCode( + () => featureRef({ name: 'ret_1d', version: Number.MAX_SAFE_INTEGER + 1 }), + 'INVALID_VERSION' + ); + }); +}); + +describe('validateFeatureDefinition', () => { + it('accepts RET_1D_V1, CTE + window expressions, subqueries, and multi-input joins', () => { + expect(() => validateFeatureDefinition(RET_1D_V1)).not.toThrow(); + + const joinedDef: FeatureDefinition = { + name: 'cad_scaled_close', + version: 1, + family: 'fx', + kind: 'duckdb_sql', + inputs: ['bars_1d', 'fx_1d'], + warmupBars: 0, + knownAtRule: 'max_input_known_at', + sql: ` + WITH base AS ( + SELECT b.listing_id, b.ts, b.session_date, b.close, b.known_at + FROM {{input:bars_1d}} AS b + ) + SELECT + base.listing_id, + base.ts, + GREATEST(base.known_at, f.known_at) AS known_at, + base.close / f.close AS value + FROM base + INNER JOIN ( + SELECT session_date, close, known_at + FROM {{input:fx_1d}} + WHERE pair = 'USDCAD' + ) AS f ON base.session_date = f.session_date + `, + }; + expect(() => validateFeatureDefinition(joinedDef)).not.toThrow(); + }); + + it('rejects invalid names, versions, families, kinds, warmupBars, and knownAtRule', () => { + expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: 'RSI-14' })), 'INVALID_NAME'); + expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: '' })), 'INVALID_NAME'); + expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: '1ret' })), 'INVALID_NAME'); + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ name: 'a'.repeat(64) })), + 'INVALID_NAME' + ); + + expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: 0 })), 'INVALID_VERSION'); + expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: -2 })), 'INVALID_VERSION'); + expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: 1.5 })), 'INVALID_VERSION'); + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ version: Number.NaN })), + 'INVALID_VERSION' + ); + + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ family: 'macro' as FeatureDefinition['family'] })), + 'INVALID_FAMILY' + ); + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ kind: 'polars' as FeatureDefinition['kind'] })), + 'INVALID_KIND' + ); + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ warmupBars: -1 })), + 'INVALID_WARMUP_BARS' + ); + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ warmupBars: 0.5 })), + 'INVALID_WARMUP_BARS' + ); + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ knownAtRule: 'end_of_month' as FeatureDefinition['knownAtRule'] }) + ), + 'INVALID_KNOWN_AT_RULE' + ); + }); + + it('rejects empty SQL, semicolons/multi-statement SQL, comments, bind markers, and malformed placeholders', () => { + expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ sql: ' ' })), 'INVALID_SQL_STATEMENT'); + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}; SELECT 1', + }) + ), + 'INVALID_SQL_STATEMENT' + ); + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} -- comment', + }) + ), + 'INVALID_SQL_STATEMENT' + ); + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: '/* block */ SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', + }) + ), + 'INVALID_SQL_STATEMENT' + ); + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > ?', + }) + ), + 'INVALID_SQL_STATEMENT' + ); + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > $1', + }) + ), + 'INVALID_SQL_STATEMENT' + ); + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > :min_close', + }) + ), + 'INVALID_SQL_STATEMENT' + ); + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{bad:bars_1d}}', + }) + ), + 'INVALID_SQL_STATEMENT' + ); + }); + + it('rejects prohibited DDL/DML/admin SQL commands with PROHIBITED_SQL_OPERATION', () => { + const prohibitedSqls = [ + "COPY (SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}) TO '/tmp/out.parquet'", + "ATTACH '/tmp/evil.db' AS evil", + 'INSERT INTO t VALUES (1)', + 'CREATE TABLE t (x INT)', + 'PRAGMA database_list', + "SET memory_limit = '100GB'", + 'INSTALL httpfs', + 'LOAD httpfs', + 'DROP TABLE bars_1d', + 'DELETE FROM bars_1d', + 'UPDATE bars_1d SET close = 0', + ]; + for (const sql of prohibitedSqls) { + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ sql })), + 'PROHIBITED_SQL_OPERATION' + ); + } + }); + + it('rejects direct/mixed-case readers, quoted paths, catalog relations, table functions, and disallowed functions', () => { + const externalSqls = [ + "SELECT listing_id, ts, ts AS known_at, close AS value FROM read_parquet('/etc/x')", + "SELECT listing_id, ts, ts AS known_at, close AS value FROM ReAd_PaRqUeT('/etc/x.parquet')", + "SELECT listing_id, ts, ts AS known_at, close AS value FROM read_csv('/tmp/a.csv')", + "SELECT listing_id, ts, ts AS known_at, close AS value FROM glob('/mnt/*')", + "SELECT listing_id, ts, ts AS known_at, close AS value FROM '/etc/x.parquet'", + "SELECT listing_id, ts, ts AS known_at, '/etc/passwd' AS value FROM {{input:bars_1d}}", + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM information_schema.tables', + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM pg_catalog.pg_tables', + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM raw_table_not_a_cte', + "SELECT listing_id, ts, ts AS known_at, getenv('HOME') AS value FROM {{input:bars_1d}}", + 'SELECT listing_id, ts, ts AS known_at, custom_evil_fn(close) AS value FROM {{input:bars_1d}}', + ]; + for (const sql of externalSqls) { + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ sql })), + 'EXTERNAL_DATA_ACCESS' + ); + } + }); + + it('rejects incorrect final projections with INVALID_SQL_PROJECTION', () => { + const badProjections = [ + 'SELECT * FROM {{input:bars_1d}}', + 'SELECT listing_id, ts, close AS value FROM {{input:bars_1d}}', + 'SELECT listing_id, ts, ts AS known_at, close AS value, volume AS extra FROM {{input:bars_1d}}', + 'SELECT ts, listing_id, ts AS known_at, close AS value FROM {{input:bars_1d}}', + 'SELECT listing_id, ts, ts AS known_at, close AS ret FROM {{input:bars_1d}}', + 'SELECT listing_id, ts, ts AS known_at, close + 1 FROM {{input:bars_1d}}', + ]; + for (const sql of badProjections) { + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ sql })), + 'INVALID_SQL_PROJECTION' + ); + } + }); + + it('rejects unsupported, undeclared, and unused input datasets with distinct codes', () => { + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + inputs: ['macro' as FeatureDefinition['inputs'][number]], + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:macro}}', + }) + ), + 'UNSUPPORTED_INPUT_DATASET' + ); + + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + inputs: ['bars_1d'], + sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:events}} AS e ON b.listing_id = e.listing_id', + }) + ), + 'UNDECLARED_INPUT' + ); + + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + inputs: ['bars_1d', 'fx_1d'], + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', + }) + ), + 'UNUSED_INPUT' + ); + }); +}); + +describe('featureDefinitionHash', () => { + it('is stable across inter-token whitespace, object key order, input order, and metadata', () => { + const defA: FeatureDefinition = { + name: 'fx_ratio', + version: 1, + family: 'fx', + kind: 'duckdb_sql', + inputs: ['fx_1d', 'bars_1d'], + warmupBars: 2, + knownAtRule: 'max_input_known_at', + description: 'First description', + sql: "SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date WHERE f.pair = 'USD CAD'", + }; + + const defB: FeatureDefinition = { + sql: [ + 'SELECT', + ' b.listing_id,', + ' b.ts,', + ' GREATEST(b.known_at, f.known_at) AS known_at,', + ' b.close / f.close AS value', + 'FROM {{input:bars_1d}} AS b', + 'INNER JOIN {{input:fx_1d}} AS f', + ' ON b.session_date = f.session_date', + "WHERE f.pair = 'USD CAD'", + ].join('\n\t'), + knownAtRule: 'max_input_known_at', + warmupBars: 2, + inputs: ['bars_1d', 'fx_1d'], + kind: 'duckdb_sql', + family: 'technical', + version: 1, + name: 'fx_ratio', + description: 'Different metadata description', + }; + + const hashA = featureDefinitionHash(defA); + const hashB = featureDefinitionHash(defB); + expect(hashA).toMatch(/^[0-9a-f]{64}$/); + expect(hashA).toBe(hashB); + }); + + it('changes when string literal whitespace, SQL semantics, inputs, warmupBars, or knownAtRule change', () => { + const base = makeSimpleDef({ + sql: "SELECT listing_id, ts, ts AS known_at, CASE WHEN currency = 'US D' THEN close ELSE 0.0 END AS value FROM {{input:bars_1d}}", + }); + const baseHash = featureDefinitionHash(base); + + // Whitespace inside string literal changes hash. + const changedLiteral = makeSimpleDef({ + sql: "SELECT listing_id, ts, ts AS known_at, CASE WHEN currency = 'US D' THEN close ELSE 0.0 END AS value FROM {{input:bars_1d}}", + }); + expect(featureDefinitionHash(changedLiteral)).not.toBe(baseHash); + + // Substantive SQL change. + const changedSql = makeSimpleDef({ + sql: 'SELECT listing_id, ts, ts AS known_at, open AS value FROM {{input:bars_1d}}', + }); + expect(featureDefinitionHash(changedSql)).not.toBe(baseHash); + + // Valid input dataset change. + const changedInput = makeSimpleDef({ + inputs: ['events'], + sql: 'SELECT listing_id, ts, known_at, 1.0 AS value FROM {{input:events}}', + }); + expect(featureDefinitionHash(changedInput)).not.toBe(baseHash); + + // warmupBars change. + expect(featureDefinitionHash({ ...base, warmupBars: 5 })).not.toBe(baseHash); + + // knownAtRule change. + expect(featureDefinitionHash({ ...base, knownAtRule: 'source_known_at' })).not.toBe(baseHash); + }); +}); + +describe('createFeatureRegistry', () => { + it('supports idempotent re-registration, enforces FEATURE_VERSION_IMMUTABLE, allows version bumps, and isolates mutations', () => { + const registry = createFeatureRegistry(); + const mutableInputs: FeatureDefinition['inputs'][number][] = ['bars_1d']; + const initial: FeatureDefinition = { + ...RET_1D_V1, + inputs: mutableInputs, + }; + + const first = registry.registerSignal(initial); + expect(first.ref).toBe('ret_1d@v1'); + expect(first.definitionHash).toBe(featureDefinitionHash(RET_1D_V1)); + + // Mutate caller input after registration; stored definition must be unaffected. + mutableInputs.push('fx_1d'); + expect(registry.get('ret_1d@v1')?.inputs).toEqual(['bars_1d']); + + // Idempotent re-registration with whitespace-only SQL difference. + const sameSemantic: FeatureDefinition = { + ...RET_1D_V1, + sql: RET_1D_V1.sql.replace(/\n/g, ' '), + description: 'Updated description ignored for hash', + }; + const second = registry.registerSignal(sameSemantic); + expect(second.definitionHash).toBe(first.definitionHash); + expect(registry.list()).toEqual(['ret_1d@v1']); + + // Semantic changes at v1 must throw FEATURE_VERSION_IMMUTABLE. + const changedSql: FeatureDefinition = { + ...RET_1D_V1, + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', + }; + const errSql = expectFeatureErrorCode( + () => registry.registerSignal(changedSql), + 'FEATURE_VERSION_IMMUTABLE' + ); + expect(errSql.ref).toBe('ret_1d@v1'); + + const changedInputs: FeatureDefinition = { + ...RET_1D_V1, + inputs: ['bars_1d', 'fx_1d'], + sql: 'SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date', + }; + expectFeatureErrorCode( + () => registry.registerSignal(changedInputs), + 'FEATURE_VERSION_IMMUTABLE' + ); + + expectFeatureErrorCode( + () => registry.registerSignal({ ...RET_1D_V1, warmupBars: 2 }), + 'FEATURE_VERSION_IMMUTABLE' + ); + + expectFeatureErrorCode( + () => registry.registerSignal({ ...RET_1D_V1, knownAtRule: 'source_known_at' }), + 'FEATURE_VERSION_IMMUTABLE' + ); + + // Same change under version 2 succeeds and both refs are listed. + const v2 = registry.registerSignal({ ...changedSql, version: 2 }); + expect(v2.ref).toBe('ret_1d@v2'); + expect(registry.list()).toEqual(['ret_1d@v1', 'ret_1d@v2']); + expect(registry.get('ret_1d@v2')?.version).toBe(2); + expect(registry.get('missing@v1')).toBeUndefined(); + + // Mutating returned list array does not affect registry. + const listed = registry.list() as string[]; + listed.push('evil@v99'); + expect(registry.list()).toEqual(['ret_1d@v1', 'ret_1d@v2']); + }); +}); + +describe('planFeatureBatch', () => { + it('plans 3 yearly Parquet COPY statements for RET_1D_V1 across 2020–2022', () => { + const writes = planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 2020, + toYear: 2022, + vaultCutoffDate: '2025-06-01', + }); + + expect(writes).toHaveLength(3); + expect(writes.map(w => w.year)).toEqual([2020, 2021, 2022]); + expect(writes.map(w => w.outputPath)).toEqual([ + '/c/features/ret_1d/v1/year=2020/part.parquet', + '/c/features/ret_1d/v1/year=2021/part.parquet', + '/c/features/ret_1d/v1/year=2022/part.parquet', + ]); + + for (const write of writes) { + expect(write.sql).toStartWith( + 'COPY (SELECT CAST(listing_id AS INTEGER) AS listing_id, ts, known_at, CAST(value AS DOUBLE) AS value FROM (' + ); + expect(write.sql).toContain( + "read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?" + ); + expect(write.sql).toContain( + 'WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ORDER BY listing_id, ts)' + ); + expect(write.sql).toEndWith( + `TO '${write.outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)` + ); + const expectedTsEnd = `${write.year}-12-31T23:59:59.999999Z`; + const expectedKnownAtCeiling = '2025-05-31T23:59:59.999999Z'; + expect(write.params).toEqual([ + expectedTsEnd, + expectedKnownAtCeiling, + write.year, + expectedTsEnd, + expectedKnownAtCeiling, + ]); + + // Verify scan predicate is embedded inside the FROM subquery of the lagged CTE + // (evaluated before LAG) and outer year(ts) filter follows the authored query. + const lagIdx = write.sql.indexOf('LAG ( close )'); + const scanIdx = write.sql.indexOf( + "FROM (SELECT * FROM read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?)" + ); + const outerYearIdx = write.sql.indexOf('WHERE year(ts) = ?'); + expect(lagIdx).toBeGreaterThan(-1); + expect(scanIdx).toBeGreaterThan(lagIdx); + expect(outerYearIdx).toBeGreaterThan(scanIdx); + } + }); + + it('expands all six allow-listed dataset path shapes and predicates, normalizes roots, and rejects unsafe roots', () => { + const allSixDef: FeatureDefinition = { + name: 'all_six_check', + version: 1, + family: 'fundamental', + kind: 'duckdb_sql', + inputs: ['bars_1d', 'adj_factors', 'events', 'shorts', 'fx_1d', 'fundamentals_pit'], + warmupBars: 0, + knownAtRule: 'max_input_known_at', + sql: ` + SELECT + b.listing_id, + b.ts, + GREATEST(b.known_at, a.known_at, e.known_at, s.known_at, f.known_at, p.effective_known_at) AS known_at, + b.close AS value + FROM {{input:bars_1d}} AS b + INNER JOIN {{input:adj_factors}} AS a ON b.listing_id = a.listing_id + INNER JOIN {{input:events}} AS e ON b.listing_id = e.listing_id + INNER JOIN {{input:shorts}} AS s ON b.listing_id = s.listing_id + INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date + INNER JOIN {{input:fundamentals_pit}} AS p ON b.listing_id = p.listing_id + `, + }; + + const [write] = planFeatureBatch(allSixDef, { + curatedRoot: '/data///', + fromYear: 2021, + toYear: 2021, + vaultCutoffDate: '2024-01-01', + }); + expect(write).toBeDefined(); + expect(write?.outputPath).toBe('/data/features/all_six_check/v1/year=2021/part.parquet'); + expect(write?.sql).toContain( + "read_parquet('/data/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?" + ); + expect(write?.sql).toContain( + "read_parquet('/data/adj_factors/part.parquet') WHERE known_at <= ?" + ); + expect(write?.sql).toContain( + "read_parquet('/data/events/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?" + ); + expect(write?.sql).toContain( + "read_parquet('/data/shorts/part.parquet') WHERE known_at <= ?" + ); + expect(write?.sql).toContain( + "read_parquet('/data/fx_1d/part.parquet') WHERE ts <= ? AND known_at <= ?" + ); + expect(write?.sql).toContain( + "read_parquet('/data/fundamentals_pit/year=*/part.parquet', hive_partitioning = true) WHERE effective_known_at <= ?" + ); + + const ts2021 = '2021-12-31T23:59:59.999999Z'; + const vaultCeiling = '2023-12-31T23:59:59.999999Z'; + expect(write?.params).toEqual([ + ts2021, + vaultCeiling, // bars_1d + vaultCeiling, // adj_factors + ts2021, + vaultCeiling, // events + vaultCeiling, // shorts + ts2021, + vaultCeiling, // fx_1d + vaultCeiling, // fundamentals_pit + 2021, + ts2021, + vaultCeiling, // outer filter + ]); + + // Root '/' normalization (no double leading slash). + const [rootWrite] = planFeatureBatch(RET_1D_V1, { + curatedRoot: '/', + fromYear: 2020, + toYear: 2020, + vaultCutoffDate: '2025-01-01', + }); + expect(rootWrite?.outputPath).toBe('/features/ret_1d/v1/year=2020/part.parquet'); + expect(rootWrite?.sql).toContain("read_parquet('/bars_1d/year=*/part.parquet', hive_partitioning = true)"); + + // Unsafe curated roots rejected. + for (const badRoot of ['', 'relative/path', "/tmp/o'reilly", '/tmp/a;b', '/tmp/a*b', '/tmp/\n']) { + expectFeatureErrorCode( + () => + planFeatureBatch(RET_1D_V1, { + curatedRoot: badRoot, + fromYear: 2020, + toYear: 2020, + vaultCutoffDate: '2025-01-01', + }), + 'INVALID_BATCH_OPTIONS' + ); + } + }); + + it('enforces Vault fence for midyear cutoff, January 1 cutoff, entirely post-cutoff ranges, and invalid options', () => { + // Midyear cutoff: 2022-06-15 -> plans 2020, 2021, 2022; clamps 2022 ts and all known_at to 2022-06-14T23:59:59.999999Z. + const midyear = planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 2020, + toYear: 2024, + vaultCutoffDate: '2022-06-15', + }); + expect(midyear.map(w => w.year)).toEqual([2020, 2021, 2022]); + expect(midyear[2]?.params).toEqual([ + '2022-06-14T23:59:59.999999Z', + '2022-06-14T23:59:59.999999Z', + 2022, + '2022-06-14T23:59:59.999999Z', + '2022-06-14T23:59:59.999999Z', + ]); + + // January 1 cutoff: 2022-01-01 -> excludes 2022 completely. + const jan1 = planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 2020, + toYear: 2023, + vaultCutoffDate: '2022-01-01', + }); + expect(jan1.map(w => w.year)).toEqual([2020, 2021]); + expect(jan1[1]?.params).toEqual([ + '2021-12-31T23:59:59.999999Z', + '2021-12-31T23:59:59.999999Z', + 2021, + '2021-12-31T23:59:59.999999Z', + '2021-12-31T23:59:59.999999Z', + ]); + + // Entirely held-out ranges throw VAULT_RANGE_VIOLATION. + expectFeatureErrorCode( + () => + planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 2023, + toYear: 2025, + vaultCutoffDate: '2022-06-15', + }), + 'VAULT_RANGE_VIOLATION' + ); + expectFeatureErrorCode( + () => + planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 2022, + toYear: 2022, + vaultCutoffDate: '2022-01-01', + }), + 'VAULT_RANGE_VIOLATION' + ); + + // Invalid calendar dates and year ranges throw INVALID_BATCH_OPTIONS. + for (const badDate of ['2025-02-29', '2025-13-01', '2025-04-31', '2025-06-01T00:00:00Z', 'not-a-date']) { + expectFeatureErrorCode( + () => + planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 2020, + toYear: 2021, + vaultCutoffDate: badDate, + }), + 'INVALID_BATCH_OPTIONS' + ); + } + + expectFeatureErrorCode( + () => + planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 2022, + toYear: 2020, + vaultCutoffDate: '2025-01-01', + }), + 'INVALID_BATCH_OPTIONS' + ); + expectFeatureErrorCode( + () => + planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 999, + toYear: 2020, + vaultCutoffDate: '2025-01-01', + }), + 'INVALID_BATCH_OPTIONS' + ); + expectFeatureErrorCode( + () => + planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 2020.5, + toYear: 2021, + vaultCutoffDate: '2025-01-01', + }), + 'INVALID_BATCH_OPTIONS' + ); + }); +}); + +describe('runFeatureBatch', () => { + it('executes deterministically in sequential year order and returns a complete manifest', async () => { + const opts = { + curatedRoot: '/c', + fromYear: 2020, + toYear: 2022, + vaultCutoffDate: '2025-06-01', + }; + + const orderLog: string[] = []; + const fakeA = createRecordingFakeExecutor({ + async onQuery(_sql, params) { + const year = params[2]; + orderLog.push(`start:${String(year)}`); + await Promise.resolve(); + orderLog.push(`end:${String(year)}`); + }, + }); + const fakeB = createRecordingFakeExecutor(); + + const manifestA = await runFeatureBatch(RET_1D_V1, opts, fakeA.executor); + const manifestB = await runFeatureBatch(RET_1D_V1, opts, fakeB.executor); + + expect(orderLog).toEqual([ + 'start:2020', + 'end:2020', + 'start:2021', + 'end:2021', + 'start:2022', + 'end:2022', + ]); + expect(fakeA.runCalls).toHaveLength(0); + expect(fakeA.calls).toEqual(fakeB.calls); + expect(manifestA).toEqual(manifestB); + expect(manifestA).toEqual({ + ref: 'ret_1d@v1', + definitionHash: featureDefinitionHash(RET_1D_V1), + knownAtRule: 'bar_close', + warmupBars: 1, + inputs: ['bars_1d'], + writes: [ + { year: 2020, outputPath: '/c/features/ret_1d/v1/year=2020/part.parquet' }, + { year: 2021, outputPath: '/c/features/ret_1d/v1/year=2021/part.parquet' }, + { year: 2022, outputPath: '/c/features/ret_1d/v1/year=2022/part.parquet' }, + ], + }); + }); + + it('stops on second-year executor error, preserves cause, and reports only first year as completed', async () => { + const rootCause = new Error('disk full on year 2021'); + const fake = createRecordingFakeExecutor({ + onQuery(_sql, _params, callIndex) { + if (callIndex === 1) { + throw rootCause; + } + }, + }); + + let caught: unknown; + try { + await runFeatureBatch( + RET_1D_V1, + { + curatedRoot: '/c', + fromYear: 2020, + toYear: 2022, + vaultCutoffDate: '2025-06-01', + }, + fake.executor + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(FeatureLibraryError); + const typed = caught as FeatureLibraryError; + expect(typed.code).toBe('BATCH_WRITE_FAILED'); + expect(typed.cause).toBe(rootCause); + expect(typed.failedYear).toBe(2021); + expect(typed.completedYears).toEqual([2020]); + expect(typed.completedWrites).toEqual([ + { year: 2020, outputPath: '/c/features/ret_1d/v1/year=2020/part.parquet' }, + ]); + expect(fake.calls).toHaveLength(2); + }); + + it('issues zero executor calls when definition or batch options are invalid', async () => { + const fake = createRecordingFakeExecutor(); + let caught: unknown; + try { + await runFeatureBatch( + RET_1D_V1, + { + curatedRoot: '/c', + fromYear: 2025, + toYear: 2026, + vaultCutoffDate: '2025-01-01', + }, + fake.executor + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(FeatureLibraryError); + expect((caught as FeatureLibraryError).code).toBe('VAULT_RANGE_VIOLATION'); + expect(fake.calls).toHaveLength(0); + expect(fake.runCalls).toHaveLength(0); + }); +}); + +describe('RET_1D_V1 economic reference check (planned SQL + hand-calculated fixture, no Parquet execution)', () => { + it('matches listing-partitioned LAG raw-close return semantics across prior-year warm-up and raw split discontinuity', () => { + // Verify SQL structure enforces listing-partitioned LAG, bar-close known_at, and positive prior close guard. + expect(RET_1D_V1.sql).toContain('LAG(close) OVER (PARTITION BY listing_id ORDER BY ts ASC) AS prev_close'); + expect(RET_1D_V1.sql).toContain('ts AS known_at'); + expect(RET_1D_V1.sql).toContain('(close / prev_close) - 1.0 AS value'); + expect(RET_1D_V1.sql).toContain('WHERE prev_close IS NOT NULL AND prev_close > 0 AND close > 0'); + + // Hand-calculated reference fixture (does not evaluate DuckDB Parquet): + // Listing 101: 2019-12-31 close 100 -> 2020-01-02 close 110 (+10%) -> 2020-01-03 2-for-1 raw split close 55 (-50% raw). + // Listing 202: 2020-01-02 close 50 (no prior close -> omitted) -> 2020-01-03 close 52 (+4%). + const bars = [ + { listing_id: 101, ts: '2019-12-31T21:00:00Z', close: 100 }, + { listing_id: 101, ts: '2020-01-02T21:00:00Z', close: 110 }, + { listing_id: 101, ts: '2020-01-03T21:00:00Z', close: 55 }, + { listing_id: 202, ts: '2020-01-02T21:00:00Z', close: 50 }, + { listing_id: 202, ts: '2020-01-03T21:00:00Z', close: 52 }, + ]; + + const lastCloseByListing = new Map(); + const targetYearRows: Array<{ listing_id: number; ts: string; known_at: string; value: number }> = []; + for (const bar of bars) { + const prevClose = lastCloseByListing.get(bar.listing_id); + lastCloseByListing.set(bar.listing_id, bar.close); + if (prevClose === undefined || prevClose <= 0 || bar.close <= 0) { + continue; + } + if (bar.ts.startsWith('2020-')) { + targetYearRows.push({ + listing_id: bar.listing_id, + ts: bar.ts, + known_at: bar.ts, + value: bar.close / prevClose - 1.0, + }); + } + } + + expect(targetYearRows).toHaveLength(3); + expect(targetYearRows[0]).toEqual({ + listing_id: 101, + ts: '2020-01-02T21:00:00Z', + known_at: '2020-01-02T21:00:00Z', + value: 0.10000000000000009, + }); + expect(targetYearRows[1]).toEqual({ + listing_id: 101, + ts: '2020-01-03T21:00:00Z', + known_at: '2020-01-03T21:00:00Z', + value: -0.5, + }); + expect(targetYearRows[2]?.listing_id).toBe(202); + expect(targetYearRows[2]?.value).toBeCloseTo(0.04, 12); + }); +}); From f86e520dec6b12da5bbfef6153135777e5dbbaf0 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 08:03:04 -0500 Subject: [PATCH 26/36] =?UTF-8?q?T-139:=20M2.4a=20=E2=80=94=20Versioned=20?= =?UTF-8?q?Feature=20Library=20core:=20declarative=20DuckDB=20SQL=20featur?= =?UTF-8?q?e=20definitions=20+=20`registerSignal`=20registry=20+=20version?= =?UTF-8?q?ed=20Parquet=20batch-plan=20runner=20over=20an=20injected=20`Du?= =?UTF-8?q?ckDbExecutor`=20in=20`libs/research/src/feature-library.ts`=20(?= =?UTF-8?q?pure,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/feature-library.ts | 48 ++++++-- libs/research/test/feature-library.test.ts | 125 ++++++++++++++++++++- 2 files changed, 159 insertions(+), 14 deletions(-) diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts index 658eaffb..8bda0847 100644 --- a/libs/research/src/feature-library.ts +++ b/libs/research/src/feature-library.ts @@ -1019,7 +1019,7 @@ function validateExpressionSlice( while (i < end) { const tok = tokens[i] as SqlToken; - // Nested subquery: (SELECT ...) or (WITH ...) + // Nested subquery: (SELECT ...) or (WITH ...); reject DuckDB FROM-first / TABLE subqueries. if (tok.kind === 'lparen') { const closeIdx = findMatchingParen(tokens, i, end); const innerFirst = tokens[i + 1]; @@ -1031,6 +1031,15 @@ function validateExpressionSlice( i = closeIdx + 1; continue; } + if ( + innerFirst?.kind === 'word' && + (innerFirst.upper === 'FROM' || innerFirst.upper === 'TABLE') + ) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Unsupported subquery form "(${innerFirst.upper} ...)" in feature SQL; subqueries must begin with SELECT or WITH.` + ); + } i += 1; continue; } @@ -1157,6 +1166,21 @@ function parseTableReference( return pos; } +function isJoinClauseStart(tokens: readonly SqlToken[], start: number, end: number): boolean { + let pos = start; + while (pos < end) { + const tok = tokens[pos] as SqlToken; + if (tok.kind !== 'word' || !JOIN_MODIFIER_KEYWORDS.has(tok.upper)) { + return false; + } + if (tok.upper === 'JOIN') { + return true; + } + pos += 1; + } + return false; +} + function validateSelectBranch( tokens: readonly SqlToken[], start: number, @@ -1314,7 +1338,7 @@ function validateSelectBranch( (ct.kind === 'comma' || (ct.kind === 'word' && (CLAUSE_TERMINATOR_KEYWORDS.has(ct.upper) || - JOIN_MODIFIER_KEYWORDS.has(ct.upper)))) + isJoinClauseStart(tokens, k, end)))) ) { condEnd = k; break; @@ -1996,8 +2020,9 @@ export function planFeatureBatch( ); const sql = - 'COPY (SELECT CAST(listing_id AS INTEGER) AS listing_id, ts, known_at, CAST(value AS DOUBLE) AS value ' + - `FROM (${expandedSql}) AS __feature_source ` + + 'COPY (SELECT listing_id, ts, known_at, value ' + + 'FROM (SELECT CAST(listing_id AS INTEGER) AS listing_id, CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, CAST(value AS DOUBLE) AS value ' + + `FROM (${expandedSql}) AS __feature_source) AS __feature_typed ` + 'WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ' + `ORDER BY listing_id, ts) TO '${outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)`; @@ -2039,10 +2064,13 @@ export async function runFeatureBatch( ); } - const plannedWrites = planFeatureBatch(def, options); - const ref = featureRef(def); - const definitionHash = featureDefinitionHash(def); - const sortedInputs = [...new Set(def.inputs)].sort(compareAscii); + validateFeatureDefinitionInternal(def); + const snapshot = cloneFeatureDefinition(def); + const plannedWrites = planFeatureBatch(snapshot, options); + const ref = featureRef(snapshot); + const definitionHash = featureDefinitionHash(snapshot); + const sortedInputs = [...new Set(snapshot.inputs)].sort(compareAscii); + const { knownAtRule, warmupBars } = snapshot; const completedWrites: FeatureBatchWriteReceipt[] = []; for (let i = 0; i < plannedWrites.length; i += 1) { @@ -2074,8 +2102,8 @@ export async function runFeatureBatch( return Object.freeze({ ref, definitionHash, - knownAtRule: def.knownAtRule, - warmupBars: def.warmupBars, + knownAtRule, + warmupBars, inputs: Object.freeze(sortedInputs), writes: Object.freeze(completedWrites), }); diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index 564cf376..322c92bd 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -183,6 +183,31 @@ describe('validateFeatureDefinition', () => { `, }; expect(() => validateFeatureDefinition(joinedDef)).not.toThrow(); + + // Two-input join using LEFT(...) and RIGHT(...) string functions in the ON predicate. + const leftInJoinOnDef: FeatureDefinition = { + name: 'fx_base_ccy_close', + version: 1, + family: 'fx', + kind: 'duckdb_sql', + inputs: ['bars_1d', 'fx_1d'], + warmupBars: 0, + knownAtRule: 'max_input_known_at', + sql: ` + SELECT + b.listing_id, + b.ts, + GREATEST(b.known_at, f.known_at) AS known_at, + b.close / f.close AS value + FROM {{input:bars_1d}} AS b + INNER JOIN {{input:fx_1d}} AS f + ON b.session_date = f.session_date + AND b.currency = LEFT(f.pair, 3) + AND RIGHT(f.pair, 3) = 'USD' + WHERE f.close > 0 + `, + }; + expect(() => validateFeatureDefinition(leftInJoinOnDef)).not.toThrow(); }); it('rejects invalid names, versions, families, kinds, warmupBars, and knownAtRule', () => { @@ -336,6 +361,20 @@ describe('validateFeatureDefinition', () => { 'EXTERNAL_DATA_ACCESS' ); } + + // Reject DuckDB FROM-first and TABLE subqueries inside expressions so catalog tables cannot bypass allow-list checks. + const unsupportedSubqueries = [ + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS (FROM secret_table)', + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((FROM secret_table))', + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE listing_id IN (FROM secret_table SELECT listing_id)', + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS (TABLE secret_table)', + ]; + for (const sql of unsupportedSubqueries) { + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ sql })), + 'INVALID_SQL_STATEMENT' + ); + } }); it('rejects incorrect final projections with INVALID_SQL_PROJECTION', () => { @@ -557,13 +596,14 @@ describe('planFeatureBatch', () => { for (const write of writes) { expect(write.sql).toStartWith( - 'COPY (SELECT CAST(listing_id AS INTEGER) AS listing_id, ts, known_at, CAST(value AS DOUBLE) AS value FROM (' + 'COPY (SELECT listing_id, ts, known_at, value ' + + 'FROM (SELECT CAST(listing_id AS INTEGER) AS listing_id, CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, CAST(value AS DOUBLE) AS value FROM (' ); expect(write.sql).toContain( "read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?" ); expect(write.sql).toContain( - 'WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ORDER BY listing_id, ts)' + ') AS __feature_source) AS __feature_typed WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ORDER BY listing_id, ts)' ); expect(write.sql).toEndWith( `TO '${write.outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)` @@ -579,16 +619,45 @@ describe('planFeatureBatch', () => { ]); // Verify scan predicate is embedded inside the FROM subquery of the lagged CTE - // (evaluated before LAG) and outer year(ts) filter follows the authored query. + // (evaluated before LAG), timestamp casts precede the outer year/Vault filter, + // and outer year(ts) filter follows the authored query. + const castTsIdx = write.sql.indexOf('CAST(ts AS TIMESTAMPTZ) AS ts'); + const castKnownAtIdx = write.sql.indexOf('CAST(known_at AS TIMESTAMPTZ) AS known_at'); const lagIdx = write.sql.indexOf('LAG ( close )'); const scanIdx = write.sql.indexOf( "FROM (SELECT * FROM read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?)" ); const outerYearIdx = write.sql.indexOf('WHERE year(ts) = ?'); - expect(lagIdx).toBeGreaterThan(-1); + expect(castTsIdx).toBeGreaterThan(-1); + expect(castKnownAtIdx).toBeGreaterThan(castTsIdx); + expect(lagIdx).toBeGreaterThan(castKnownAtIdx); expect(scanIdx).toBeGreaterThan(lagIdx); expect(outerYearIdx).toBeGreaterThan(scanIdx); } + + // Daily short-interest fixture projecting DATE report_date as ts still normalizes ts & known_at to TIMESTAMPTZ. + const shortsDateDef: FeatureDefinition = { + name: 'short_interest_raw', + version: 1, + family: 'event', + kind: 'duckdb_sql', + inputs: ['shorts'], + warmupBars: 0, + knownAtRule: 'source_known_at', + sql: 'SELECT listing_id, report_date AS ts, known_at, short_interest AS value FROM {{input:shorts}}', + }; + const [shortsWrite] = planFeatureBatch(shortsDateDef, { + curatedRoot: '/c', + fromYear: 2021, + toYear: 2021, + vaultCutoffDate: '2025-01-01', + }); + expect(shortsWrite?.sql).toContain( + 'SELECT CAST(listing_id AS INTEGER) AS listing_id, CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, CAST(value AS DOUBLE) AS value FROM (' + ); + expect(shortsWrite?.sql).toContain( + ') AS __feature_source) AS __feature_typed WHERE year(ts) = ? AND ts <= ? AND known_at <= ?' + ); }); it('expands all six allow-listed dataset path shapes and predicates, normalizes roots, and rejects unsafe roots', () => { @@ -895,6 +964,54 @@ describe('runFeatureBatch', () => { expect(fake.calls).toHaveLength(0); expect(fake.runCalls).toHaveLength(0); }); + + it('snapshots definition metadata before awaiting writes so mid-run caller mutations cannot skew the manifest', async () => { + const mutableDef: { + name: string; + version: number; + family: FeatureDefinition['family']; + kind: FeatureDefinition['kind']; + inputs: FeatureDefinition['inputs'][number][]; + warmupBars: number; + knownAtRule: FeatureDefinition['knownAtRule']; + sql: string; + } = { + name: 'mutable_close', + version: 1, + family: 'technical', + kind: 'duckdb_sql', + inputs: ['bars_1d'], + warmupBars: 2, + knownAtRule: 'bar_close', + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', + }; + const expectedHash = featureDefinitionHash(mutableDef); + + const fake = createRecordingFakeExecutor({ + onQuery() { + mutableDef.warmupBars = 999; + mutableDef.knownAtRule = 'source_known_at'; + mutableDef.inputs.push('fx_1d'); + }, + }); + + const manifest = await runFeatureBatch( + mutableDef, + { + curatedRoot: '/c', + fromYear: 2020, + toYear: 2021, + vaultCutoffDate: '2025-01-01', + }, + fake.executor + ); + + expect(manifest.definitionHash).toBe(expectedHash); + expect(manifest.warmupBars).toBe(2); + expect(manifest.knownAtRule).toBe('bar_close'); + expect(manifest.inputs).toEqual(['bars_1d']); + expect(manifest.writes).toHaveLength(2); + }); }); describe('RET_1D_V1 economic reference check (planned SQL + hand-calculated fixture, no Parquet execution)', () => { From 1bbe88947dfaa007d708a7fa5938864231edfbcb Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 09:25:50 -0500 Subject: [PATCH 27/36] =?UTF-8?q?T-139:=20M2.4a=20=E2=80=94=20Versioned=20?= =?UTF-8?q?Feature=20Library=20core:=20declarative=20DuckDB=20SQL=20featur?= =?UTF-8?q?e=20definitions=20+=20`registerSignal`=20registry=20+=20version?= =?UTF-8?q?ed=20Parquet=20batch-plan=20runner=20over=20an=20injected=20`Du?= =?UTF-8?q?ckDbExecutor`=20in=20`libs/research/src/feature-library.ts`=20(?= =?UTF-8?q?pure,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/feature-library.ts | 27 +++++++++-- libs/research/test/feature-library.test.ts | 53 ++++++++++++++++++++-- 2 files changed, 74 insertions(+), 6 deletions(-) diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts index 8bda0847..d345a6ef 100644 --- a/libs/research/src/feature-library.ts +++ b/libs/research/src/feature-library.ts @@ -1009,6 +1009,25 @@ function extractProjectionOutputName(tokens: readonly SqlToken[], start: number, ); } +function hasTopLevelSetOperator(tokens: readonly SqlToken[], start: number, end: number): boolean { + let depth = 0; + for (let i = start; i < end; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + } else if ( + depth === 0 && + tok.kind === 'word' && + (tok.upper === 'UNION' || tok.upper === 'INTERSECT' || tok.upper === 'EXCEPT') + ) { + return true; + } + } + return false; +} + function validateExpressionSlice( tokens: readonly SqlToken[], start: number, @@ -1019,13 +1038,15 @@ function validateExpressionSlice( while (i < end) { const tok = tokens[i] as SqlToken; - // Nested subquery: (SELECT ...) or (WITH ...); reject DuckDB FROM-first / TABLE subqueries. + // Nested subquery: (SELECT ...), (WITH ...), or compound subquery ((SELECT ...) UNION ...); + // reject DuckDB FROM-first / TABLE subqueries. if (tok.kind === 'lparen') { const closeIdx = findMatchingParen(tokens, i, end); const innerFirst = tokens[i + 1]; if ( - innerFirst?.kind === 'word' && - (innerFirst.upper === 'SELECT' || innerFirst.upper === 'WITH') + (innerFirst?.kind === 'word' && + (innerFirst.upper === 'SELECT' || innerFirst.upper === 'WITH')) || + hasTopLevelSetOperator(tokens, i + 1, closeIdx) ) { validateQuerySlice(tokens, i + 1, closeIdx, inScopeCtes, false); i = closeIdx + 1; diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index 322c92bd..4200a10e 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -184,7 +184,8 @@ describe('validateFeatureDefinition', () => { }; expect(() => validateFeatureDefinition(joinedDef)).not.toThrow(); - // Two-input join using LEFT(...) and RIGHT(...) string functions in the ON predicate. + // Two-input join using LEFT(...) and RIGHT(...) string functions in the ON predicate, + // followed immediately by a real LEFT JOIN to verify join-boundary detection. const leftInJoinOnDef: FeatureDefinition = { name: 'fx_base_ccy_close', version: 1, @@ -198,16 +199,46 @@ describe('validateFeatureDefinition', () => { b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, - b.close / f.close AS value + b.close / COALESCE(f2.close, f.close) AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date AND b.currency = LEFT(f.pair, 3) AND RIGHT(f.pair, 3) = 'USD' + LEFT JOIN {{input:fx_1d}} AS f2 + ON b.session_date = f2.session_date + AND f2.pair = 'USDCAD' WHERE f.close > 0 `, }; expect(() => validateFeatureDefinition(leftInJoinOnDef)).not.toThrow(); + + // Valid compound subquery with parenthesized branches referencing declared inputs, + // and scalar subquery inside parenthesized arithmetic. + const compoundExistsDef: FeatureDefinition = { + name: 'eligible_close', + version: 1, + family: 'event', + kind: 'duckdb_sql', + inputs: ['bars_1d', 'events'], + warmupBars: 0, + knownAtRule: 'max_input_known_at', + sql: ` + SELECT + b.listing_id, + b.ts, + b.known_at, + b.close AS value + FROM {{input:bars_1d}} AS b + WHERE EXISTS ( + (SELECT 1 FROM {{input:bars_1d}} AS b2 WHERE b2.listing_id = b.listing_id) + UNION ALL + (SELECT 1 FROM {{input:events}} AS e WHERE e.listing_id = b.listing_id) + ) + AND ((SELECT MAX(close) FROM {{input:bars_1d}}) + 1) > b.close + `, + }; + expect(() => validateFeatureDefinition(compoundExistsDef)).not.toThrow(); }); it('rejects invalid names, versions, families, kinds, warmupBars, and knownAtRule', () => { @@ -368,6 +399,7 @@ describe('validateFeatureDefinition', () => { 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((FROM secret_table))', 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE listing_id IN (FROM secret_table SELECT listing_id)', 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS (TABLE secret_table)', + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) UNION ALL FROM staging_eligibility)', ]; for (const sql of unsupportedSubqueries) { expectFeatureErrorCode( @@ -375,6 +407,21 @@ describe('validateFeatureDefinition', () => { 'INVALID_SQL_STATEMENT' ); } + + // Reject compound subqueries with a parenthesized first branch when any later branch references an unauthorized relation. + const compoundBypassSubqueries = [ + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) UNION ALL SELECT 1 FROM staging_eligibility)', + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) UNION ALL (SELECT 1 FROM staging_eligibility))', + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) INTERSECT SELECT 1 FROM staging_eligibility)', + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) EXCEPT SELECT 1 FROM staging_eligibility)', + 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS (((SELECT 1 FROM {{input:bars_1d}}) UNION ALL SELECT 1 FROM staging_eligibility))', + ]; + for (const sql of compoundBypassSubqueries) { + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ sql })), + 'EXTERNAL_DATA_ACCESS' + ); + } }); it('rejects incorrect final projections with INVALID_SQL_PROJECTION', () => { @@ -644,7 +691,7 @@ describe('planFeatureBatch', () => { inputs: ['shorts'], warmupBars: 0, knownAtRule: 'source_known_at', - sql: 'SELECT listing_id, report_date AS ts, known_at, short_interest AS value FROM {{input:shorts}}', + sql: 'SELECT listing_id, report_date AS ts, known_at, shares_short AS value FROM {{input:shorts}}', }; const [shortsWrite] = planFeatureBatch(shortsDateDef, { curatedRoot: '/c', From 94d8631d40331a60fce44fb7ffb75ca69719ca8a Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 09:32:24 -0500 Subject: [PATCH 28/36] T-139: tests --- libs/research/test/feature-library.test.ts | 87 ++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index 4200a10e..1fe1994f 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -1115,3 +1115,90 @@ describe('RET_1D_V1 economic reference check (planned SQL + hand-calculated fixt expect(targetYearRows[2]?.value).toBeCloseTo(0.04, 12); }); }); + +describe('QA: relation-source allow-list and Vault boundary edge cases', () => { + const positionalBypassSqls = [ + // Explicit alias, then DuckDB POSITIONAL JOIN to an undeclared catalog table. + 'SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b POSITIONAL JOIN staging_tbl AS s', + // Bare alias form. + 'SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} b POSITIONAL JOIN staging_tbl s', + // Inside a CTE body. + 'WITH x AS (SELECT b.listing_id, b.ts, s.v FROM {{input:bars_1d}} AS b POSITIONAL JOIN staging_tbl AS s) SELECT listing_id, ts, ts AS known_at, v AS value FROM x', + ]; + + it('rejects POSITIONAL JOIN to an undeclared relation after an aliased input (registry and runner never execute it)', async () => { + for (const sql of positionalBypassSqls) { + const def = makeSimpleDef({ name: 'positional_leak', sql }); + let thrown: unknown; + try { + validateFeatureDefinition(def); + } catch (error) { + thrown = error; + } + expect(thrown).toBeInstanceOf(FeatureLibraryError); + expect(['EXTERNAL_DATA_ACCESS', 'INVALID_SQL_STATEMENT']).toContain( + (thrown as FeatureLibraryError).code + ); + + expect(() => createFeatureRegistry().registerSignal(def)).toThrow(FeatureLibraryError); + + const fake = createRecordingFakeExecutor(); + await expect( + runFeatureBatch( + def, + { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-06-30' }, + fake.executor + ) + ).rejects.toBeInstanceOf(FeatureLibraryError); + expect(fake.calls).toHaveLength(0); + } + }); + + it('still rejects a POSITIONAL JOIN to an undeclared relation chained after an ON predicate', () => { + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b JOIN {{input:bars_1d}} AS c ON b.ts = c.ts POSITIONAL JOIN staging_tbl', + }) + ), + 'EXTERNAL_DATA_ACCESS' + ); + }); + + it('accepts a leap-day cutoff and clamps the cutoff year to the last microsecond of the prior day', () => { + const writes = planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 2023, + toYear: 2025, + vaultCutoffDate: '2024-02-29', + }); + expect(writes.map(w => w.year)).toEqual([2023, 2024]); + const ceiling = '2024-02-28T23:59:59.999999Z'; + expect(writes[1]?.params).toEqual([ceiling, ceiling, 2024, ceiling, ceiling]); + expect(writes[0]?.params).toEqual([ + '2023-12-31T23:59:59.999999Z', + ceiling, + 2023, + '2023-12-31T23:59:59.999999Z', + ceiling, + ]); + }); + + it('plans the cutoff year when only its first day precedes a January 2 cutoff', () => { + const writes = planFeatureBatch(RET_1D_V1, { + curatedRoot: '/c', + fromYear: 2022, + toYear: 2022, + vaultCutoffDate: '2022-01-02', + }); + expect(writes.map(w => w.year)).toEqual([2022]); + const ceiling = '2022-01-01T23:59:59.999999Z'; + expect(writes[0]?.params).toEqual([ceiling, ceiling, 2022, ceiling, ceiling]); + for (const param of writes[0]?.params ?? []) { + if (typeof param === 'string') { + expect(param < '2022-01-02').toBe(true); + } + } + }); +}); From 98451ee07cb75dcdd3612ef288a34e4e734fee97 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 09:39:58 -0500 Subject: [PATCH 29/36] =?UTF-8?q?T-139:=20M2.4a=20=E2=80=94=20Versioned=20?= =?UTF-8?q?Feature=20Library=20core:=20declarative=20DuckDB=20SQL=20featur?= =?UTF-8?q?e=20definitions=20+=20`registerSignal`=20registry=20+=20version?= =?UTF-8?q?ed=20Parquet=20batch-plan=20runner=20over=20an=20injected=20`Du?= =?UTF-8?q?ckDbExecutor`=20in=20`libs/research/src/feature-library.ts`=20(?= =?UTF-8?q?pure,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/feature-library.ts | 22 +++++++++ libs/research/test/feature-library.test.ts | 53 ++++++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts index d345a6ef..8a8c9e66 100644 --- a/libs/research/src/feature-library.ts +++ b/libs/research/src/feature-library.ts @@ -522,6 +522,7 @@ const JOIN_MODIFIER_KEYWORDS: ReadonlySet = new Set([ 'LEFT', 'NATURAL', 'OUTER', + 'POSITIONAL', 'RIGHT', 'SEMI', ]); @@ -1065,6 +1066,14 @@ function validateExpressionSlice( continue; } + // Fail closed if an unparsed JOIN token appears inside an expression or clause tail. + if (tok.kind === 'word' && tok.upper === 'JOIN') { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unexpected JOIN outside a parsed FROM/JOIN clause in feature SQL.' + ); + } + // Callable function check: followed by '('. if ( (tok.kind === 'word' || tok.kind === 'quoted_ident') && @@ -1373,6 +1382,19 @@ function validateSelectBranch( } break; } + if (pos < end) { + const afterFrom = tokens[pos] as SqlToken; + if ( + afterFrom.kind !== 'word' || + !CLAUSE_TERMINATOR_KEYWORDS.has(afterFrom.upper) || + afterFrom.upper === 'FROM' + ) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Unexpected token "${afterFrom.raw}" after FROM/JOIN clause in feature SQL.` + ); + } + } continue; } diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index 1fe1994f..1bf4c185 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -1166,6 +1166,59 @@ describe('QA: relation-source allow-list and Vault boundary edge cases', () => { ); }); + it('allows POSITIONAL JOIN between declared inputs and fails closed on unknown join modifiers or unparsed JOIN tokens', () => { + expect(() => + validateFeatureDefinition( + makeSimpleDef({ + inputs: ['bars_1d', 'fx_1d'], + sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close / f.rate AS value FROM {{input:bars_1d}} AS b POSITIONAL JOIN {{input:fx_1d}} AS f', + }) + ) + ).not.toThrow(); + + expect(() => + validateFeatureDefinition( + makeSimpleDef({ + inputs: ['bars_1d', 'fx_1d'], + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} POSITIONAL JOIN {{input:fx_1d}} AS f', + }) + ) + ).not.toThrow(); + + // Unknown modifier immediately after FROM/alias must fail closed (never fall through to expression scan). + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b LATERAL_UNKNOWN JOIN staging_tbl AS s', + }) + ), + 'INVALID_SQL_STATEMENT' + ); + + // Chained JOIN after an ON predicate with an unknown modifier still hits relation allow-list validation. + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b JOIN {{input:bars_1d}} AS c ON b.ts = c.ts UNKNOWN_MOD JOIN staging_tbl AS s', + }) + ), + 'EXTERNAL_DATA_ACCESS' + ); + + // Unparsed JOIN keyword inside a WHERE expression tail must fail closed. + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b WHERE b.close > 0 JOIN staging_tbl AS s', + }) + ), + 'INVALID_SQL_STATEMENT' + ); + }); + it('accepts a leap-day cutoff and clamps the cutoff year to the last microsecond of the prior day', () => { const writes = planFeatureBatch(RET_1D_V1, { curatedRoot: '/c', From f2d56a7333d8e9e79ad642d6dc9cca32d885e4a6 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 09:49:34 -0500 Subject: [PATCH 30/36] T-139: tests --- libs/research/test/feature-library.test.ts | 182 +++++++++++++++++++++ 1 file changed, 182 insertions(+) diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index 1bf4c185..c95752e6 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -1255,3 +1255,185 @@ describe('QA: relation-source allow-list and Vault boundary edge cases', () => { } }); }); + +describe('QA round 2: undeclared-relation probes rejected before any executor call', () => { + // Each probe was also checked in a scratch in-memory DuckDB 1.4.4 session holding a + // `staging_tbl` relation; every form here is valid DuckDB that would read that table. + const undeclaredRelationProbes: ReadonlyArray<{ sql: string; code: FeatureLibraryErrorCode }> = [ + { + sql: 'SELECT b.listing_id, b.ts, b.known_at, s.v AS value FROM {{input:bars_1d}} b NATURAL JOIN staging_tbl s', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b ANTI JOIN staging_tbl s ON s.listing_id = b.listing_id', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b SEMI JOIN staging_tbl USING (listing_id)', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} AS b(listing_id) ASOF JOIN staging_tbl s ON s.listing_id <= b.listing_id', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b, LATERAL (SELECT v FROM staging_tbl) s', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + sql: 'SELECT b.listing_id, b.ts, b.known_at, (SELECT v FROM staging_tbl) AS value FROM {{input:bars_1d}} b', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b WHERE EXISTS ((FROM staging_tbl))', + code: 'INVALID_SQL_STATEMENT', + }, + { + sql: 'WITH x AS (SELECT * FROM {{input:bars_1d}}) SELECT x.listing_id, x.ts, x.known_at, x.close AS value FROM x WHERE x.listing_id IN (TABLE staging_tbl)', + code: 'INVALID_SQL_STATEMENT', + }, + { + sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b WHERE b.listing_id = ANY (SELECT listing_id FROM "staging_tbl")', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b QUALIFY b.close IN (SELECT v FROM staging_tbl)', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b WINDOW w AS (ORDER BY (SELECT 1 FROM staging_tbl))', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + // An unused CTE over a catalog table still counts as an undeclared relation source. + sql: 'WITH x AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + // DuckDB method-call syntax resolves to the table function query_table(). + sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close.query_table() AS value FROM {{input:bars_1d}} b', + code: 'EXTERNAL_DATA_ACCESS', + }, + { + sql: 'SELECT listing_id, ts, known_at, close AS value FROM {{input:bars_1d}} UNION ALL BY NAME SELECT listing_id, ts, ts AS known_at, v AS value FROM staging_tbl', + code: 'INVALID_SQL_STATEMENT', + }, + { + // DuckDB E-strings treat \' as an escaped quote; the tokenizer must not be + // desynchronised into hiding a subquery inside what it believes is a literal. + sql: "SELECT b.listing_id, b.ts, b.known_at, E'\\' ' || (SELECT max(v) FROM staging_tbl) || ' ' AS value FROM {{input:bars_1d}} b", + code: 'INVALID_SQL_STATEMENT', + }, + ]; + + it('rejects each undeclared-relation form with a specific code from validate, registerSignal and runFeatureBatch', async () => { + for (const probe of undeclaredRelationProbes) { + const def = makeSimpleDef({ name: 'probe_leak', sql: probe.sql }); + + expectFeatureErrorCode(() => validateFeatureDefinition(def), probe.code); + expectFeatureErrorCode(() => createFeatureRegistry().registerSignal(def), probe.code); + + const fake = createRecordingFakeExecutor(); + let thrown: unknown; + try { + await runFeatureBatch( + def, + { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-06-30' }, + fake.executor + ); + } catch (error) { + thrown = error; + } + expect((thrown as FeatureLibraryError).code).toBe(probe.code); + expect(fake.calls).toHaveLength(0); + } + }); + + it('plans contract-schema definitions for every input dataset with inner availability predicates bound before the outer filters', () => { + const cutoff = '2022-06-30'; + const ceiling = '2022-06-29T23:59:59.999999Z'; + const yearEnd = '2021-12-31T23:59:59.999999Z'; + const base = { version: 1, warmupBars: 0, knownAtRule: 'source_known_at' as const }; + const cases: ReadonlyArray<{ def: FeatureDefinition; scanParams: DuckDbParam[] }> = [ + { + def: makeSimpleDef({ + ...base, + name: 'fx_close', + family: 'fx', + inputs: ['bars_1d', 'fx_1d'], + sql: 'SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close * f.close AS value FROM {{input:bars_1d}} AS b JOIN {{input:fx_1d}} AS f ON f.session_date = b.session_date AND LEFT(f.pair, 3) = b.currency', + }), + scanParams: [yearEnd, ceiling, yearEnd, ceiling], + }, + { + def: makeSimpleDef({ + ...base, + name: 'short_int', + inputs: ['shorts'], + sql: 'SELECT listing_id, report_date AS ts, known_at, shares_short AS value FROM {{input:shorts}}', + }), + scanParams: [ceiling], + }, + { + def: makeSimpleDef({ + ...base, + name: 'evt', + family: 'event', + inputs: ['events'], + sql: 'SELECT listing_id, ts, known_at, 1.0 AS value FROM {{input:events}}', + }), + scanParams: [yearEnd, ceiling], + }, + { + def: makeSimpleDef({ + ...base, + name: 'adj', + inputs: ['adj_factors'], + sql: 'SELECT listing_id, ex_date AS ts, known_at, cum_split_factor AS value FROM {{input:adj_factors}}', + }), + scanParams: [ceiling], + }, + { + def: makeSimpleDef({ + ...base, + name: 'fund', + family: 'fundamental', + inputs: ['fundamentals_pit'], + sql: 'SELECT listing_id, effective_known_at AS ts, effective_known_at AS known_at, revenue_ttm AS value FROM {{input:fundamentals_pit}}', + }), + scanParams: [ceiling], + }, + ]; + + for (const { def, scanParams } of cases) { + const writes = planFeatureBatch(def, { + curatedRoot: '/c', + fromYear: 2021, + toYear: 2021, + vaultCutoffDate: cutoff, + }); + expect(writes).toHaveLength(1); + const write = writes[0] as (typeof writes)[number]; + expect(write.outputPath).toBe(`/c/features/${def.name}/v1/year=2021/part.parquet`); + expect(write.params).toEqual([...scanParams, 2021, yearEnd, ceiling]); + // Bind markers in SQL match the parameter count exactly. + expect(write.sql.split('?').length - 1).toBe(write.params.length); + // Every inner scan predicate appears before the outer year/Vault filter. + const outerFilter = write.sql.indexOf('WHERE year(ts) = ?'); + expect(outerFilter).toBeGreaterThan(0); + let lastScan = -1; + for (let at = write.sql.indexOf('read_parquet('); at !== -1; at = write.sql.indexOf('read_parquet(', at + 1)) { + lastScan = at; + } + expect(lastScan).toBeGreaterThan(-1); + expect(lastScan).toBeLessThan(outerFilter); + expect(write.sql).toContain('CAST(ts AS TIMESTAMPTZ) AS ts'); + expect(write.sql).toContain('CAST(known_at AS TIMESTAMPTZ) AS known_at'); + for (const param of write.params) { + if (typeof param === 'string') { + expect(param < cutoff).toBe(true); + } + } + } + }); +}); From 26e305f5e6a8e9cfa8545dd9a332c8d145b583e0 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 10:06:21 -0500 Subject: [PATCH 31/36] T-139: tests --- libs/research/test/feature-library.test.ts | 40 ++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index c95752e6..1ae89e24 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -1437,3 +1437,43 @@ describe('QA round 2: undeclared-relation probes rejected before any executor ca } }); }); + +describe('QA round 3: WITH RECURSIVE cannot shadow an undeclared catalog relation', () => { + // Reproduced in a scratch in-memory DuckDB 1.4.4 session holding `staging_tbl(v = 42.0)`: + // DuckDB treats a RECURSIVE CTE body without a recursive UNION term (or the anchor term of + // one that has it) as a non-recursive scope, so `FROM staging_tbl` inside the body binds to + // the catalog table. runFeatureBatch then wrote 42.0 into + // features/leak/v1/year=2021/part.parquet while the manifest reported inputs ['bars_1d']. + const recursiveShadowProbes: readonly string[] = [ + 'WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, staging_tbl AS s', + 'WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl UNION ALL SELECT * FROM staging_tbl WHERE 1 = 0) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, staging_tbl AS s', + ]; + + it('rejects a RECURSIVE CTE whose body reads a same-named catalog table, with no executor call', async () => { + for (const sql of recursiveShadowProbes) { + const def = makeSimpleDef({ name: 'leak', sql }); + + let validateError: unknown; + try { + validateFeatureDefinition(def); + } catch (error) { + validateError = error; + } + expect(validateError).toBeInstanceOf(FeatureLibraryError); + expect(['EXTERNAL_DATA_ACCESS', 'INVALID_SQL_STATEMENT']).toContain( + (validateError as FeatureLibraryError).code + ); + expect(() => createFeatureRegistry().registerSignal(def)).toThrow(FeatureLibraryError); + + const fake = createRecordingFakeExecutor(); + await expect( + runFeatureBatch( + def, + { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, + fake.executor + ) + ).rejects.toBeInstanceOf(FeatureLibraryError); + expect(fake.calls).toHaveLength(0); + } + }); +}); From 7ef16d0bc337f7f7b47f1a659d6f9d2440668a36 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 10:26:16 -0500 Subject: [PATCH 32/36] =?UTF-8?q?T-139:=20M2.4a=20=E2=80=94=20Versioned=20?= =?UTF-8?q?Feature=20Library=20core:=20declarative=20DuckDB=20SQL=20featur?= =?UTF-8?q?e=20definitions=20+=20`registerSignal`=20registry=20+=20version?= =?UTF-8?q?ed=20Parquet=20batch-plan=20runner=20over=20an=20injected=20`Du?= =?UTF-8?q?ckDbExecutor`=20in=20`libs/research/src/feature-library.ts`=20(?= =?UTF-8?q?pure,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 2 +- libs/research/src/feature-library.ts | 12 ++++----- libs/research/test/feature-library.test.ts | 30 ++++++++++------------ 3 files changed, 20 insertions(+), 24 deletions(-) diff --git a/libs/research/README.md b/libs/research/README.md index 939d7fda..8d119484 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -235,7 +235,7 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/feature-librar ### API & Immutability -- **`validateFeatureDefinition(def)`** — Fail-closed validator for declarative `duckdb_sql` feature definitions using a single quote-aware tokenizer shared with hashing and placeholder expansion. Accepts a single `SELECT` or `WITH ... SELECT` statement projecting exactly `(listing_id, ts, known_at, value)` in contract order. Rejects semicolons, comments, caller bind markers (`?`, `$1`, `:name`), prohibited DDL/DML/admin keywords (`COPY`, `ATTACH`, `INSERT`, `CREATE`, `PRAGMA`, `SET`, etc.), external readers (`read_parquet`, `read_csv`, `glob`, etc.), quoted file paths/URIs, catalog relations, table functions, and non-allow-listed functions. Relation sources are restricted to declared `{{input:}}` placeholders (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`), in-scope CTEs, and validated subqueries; every declared input must be used and every placeholder must be declared. +- **`validateFeatureDefinition(def)`** — Fail-closed validator for declarative `duckdb_sql` feature definitions using a single quote-aware tokenizer shared with hashing and placeholder expansion. Accepts a single `SELECT` or non-recursive `WITH ... SELECT` statement projecting exactly `(listing_id, ts, known_at, value)` in contract order. Rejects `WITH RECURSIVE`, semicolons, comments, caller bind markers (`?`, `$1`, `:name`), prohibited DDL/DML/admin keywords (`COPY`, `ATTACH`, `INSERT`, `CREATE`, `PRAGMA`, `SET`, etc.), external readers (`read_parquet`, `read_csv`, `glob`, etc.), quoted file paths/URIs, catalog relations, table functions, and non-allow-listed functions. Relation sources are restricted to declared `{{input:}}` placeholders (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`), in-scope non-recursive CTEs, and validated subqueries; every declared input must be used and every placeholder must be declared. - **`featureRef(def)` / `parseFeatureRef(ref)`** — Formats and parses canonical `@v` refs (`^[a-z][a-z0-9_]{0,62}$` and positive safe integer version; rejects non-canonical forms such as `ret_1d@v01`). - **`featureDefinitionHash(def)`** — Deterministic 64-char SHA-256 hex digest over `{ name, version, kind, sql (canonical tokens), inputs (sorted), warmupBars, knownAtRule }`. Invariant across inter-token whitespace, object key order, and input array order; preserves whitespace inside string literals. `family` and `description` are stored as metadata from the first registration. - **`createFeatureRegistry()`** — In-memory registry exposing `registerSignal(def)` (D11), `get(ref)`, and `list()`. Re-registering an identical hash is idempotent; re-registering `@v` with a different hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. Defensive copies isolate stored definitions from caller mutation. diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts index 8a8c9e66..131899ae 100644 --- a/libs/research/src/feature-library.ts +++ b/libs/research/src/feature-library.ts @@ -1432,13 +1432,14 @@ function validateQuerySlice( const inScopeCtes = new Set(outerCtes); let pos = start; - // Optional leading WITH clause. + // Optional leading WITH clause (non-recursive CTEs only). if (tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'WITH') { pos += 1; - let isRecursive = false; if (pos < end && tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'RECURSIVE') { - isRecursive = true; - pos += 1; + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'WITH RECURSIVE CTEs are not permitted in feature SQL; use non-recursive CTEs.' + ); } while (pos < end) { @@ -1484,9 +1485,6 @@ function validateQuerySlice( ); } const bodyClose = findMatchingParen(tokens, pos, end); - if (isRecursive) { - inScopeCtes.add(cteName); - } validateQuerySlice(tokens, pos + 1, bodyClose, inScopeCtes, false); inScopeCtes.add(cteName); pos = bodyClose + 1; diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index 1ae89e24..dd5dbd6a 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -1447,32 +1447,30 @@ describe('QA round 3: WITH RECURSIVE cannot shadow an undeclared catalog relatio const recursiveShadowProbes: readonly string[] = [ 'WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, staging_tbl AS s', 'WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl UNION ALL SELECT * FROM staging_tbl WHERE 1 = 0) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, staging_tbl AS s', + 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM (WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.close FROM {{input:bars_1d}} AS b, staging_tbl AS s) AS b', + 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b WHERE EXISTS (WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT 1 FROM staging_tbl)', ]; - it('rejects a RECURSIVE CTE whose body reads a same-named catalog table, with no executor call', async () => { + it('rejects top-level and nested WITH RECURSIVE CTEs with INVALID_SQL_STATEMENT and zero executor calls', async () => { for (const sql of recursiveShadowProbes) { const def = makeSimpleDef({ name: 'leak', sql }); - let validateError: unknown; - try { - validateFeatureDefinition(def); - } catch (error) { - validateError = error; - } - expect(validateError).toBeInstanceOf(FeatureLibraryError); - expect(['EXTERNAL_DATA_ACCESS', 'INVALID_SQL_STATEMENT']).toContain( - (validateError as FeatureLibraryError).code - ); - expect(() => createFeatureRegistry().registerSignal(def)).toThrow(FeatureLibraryError); + expectFeatureErrorCode(() => validateFeatureDefinition(def), 'INVALID_SQL_STATEMENT'); + expectFeatureErrorCode(() => createFeatureRegistry().registerSignal(def), 'INVALID_SQL_STATEMENT'); const fake = createRecordingFakeExecutor(); - await expect( - runFeatureBatch( + let execError: unknown; + try { + await runFeatureBatch( def, { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, fake.executor - ) - ).rejects.toBeInstanceOf(FeatureLibraryError); + ); + } catch (error) { + execError = error; + } + expect(execError).toBeInstanceOf(FeatureLibraryError); + expect((execError as FeatureLibraryError).code).toBe('INVALID_SQL_STATEMENT'); expect(fake.calls).toHaveLength(0); } }); From c4083a8f323d360458da7074ef3af8f7bce59ec0 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 10:36:49 -0500 Subject: [PATCH 33/36] T-139: tests --- libs/research/test/feature-library.test.ts | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index dd5dbd6a..fbb76490 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -1475,3 +1475,62 @@ describe('QA round 3: WITH RECURSIVE cannot shadow an undeclared catalog relatio } }); }); + +describe('QA round 4: CTE scope must match DuckDB identifier folding (ASCII-only)', () => { + // Reproduced in a scratch in-memory DuckDB 1.4.4 session (`SET TimeZone='UTC'`) holding catalog + // tables `kv(v = 42.0)` and `"ä"(v = 43.0)` plus one bars_1d row (listing 1, 2021-03-01). DuckDB + // folds identifier case for ASCII only, so `"Kv"` (KELVIN SIGN) is not the same name as `kv` + // and `"Ä"` is not `"ä"`; the validator's `toLowerCase()` treated them as the same in-scope CTE. + // runFeatureBatch then wrote 42.0 / 43.0 into features/leak_*/v1/year=2021/part.parquet while the + // manifest reported inputs ['bars_1d']. + const unicodeFoldProbes: readonly string[] = [ + 'WITH "Kv" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', + 'WITH "Ä" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, "ä" AS s', + 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b WHERE EXISTS (WITH "Kv" AS (SELECT 1 AS v) SELECT 1 FROM kv)', + ]; + + it('rejects a reference that only matches a CTE under Unicode case folding, with zero executor calls', async () => { + for (const sql of unicodeFoldProbes) { + const def = makeSimpleDef({ name: 'leak', sql }); + + for (const attempt of [ + () => validateFeatureDefinition(def), + () => createFeatureRegistry().registerSignal(def), + ]) { + let error: unknown; + try { + attempt(); + } catch (caught) { + error = caught; + } + expect(error).toBeInstanceOf(FeatureLibraryError); + expect(['EXTERNAL_DATA_ACCESS', 'INVALID_SQL_STATEMENT']).toContain( + (error as FeatureLibraryError).code + ); + } + + const fake = createRecordingFakeExecutor(); + let execError: unknown; + try { + await runFeatureBatch( + def, + { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, + fake.executor + ); + } catch (error) { + execError = error; + } + expect(execError).toBeInstanceOf(FeatureLibraryError); + expect(fake.calls).toHaveLength(0); + } + }); + + it('still accepts an ASCII case-insensitive quoted CTE reference, which DuckDB binds to the CTE', () => { + // Verified in DuckDB 1.4.4: `WITH "STAGING" AS (SELECT 1.0 AS v) SELECT v FROM staging` returns 1.0 + // even when a catalog table `staging(v = 42.0)` exists. + const def = makeSimpleDef({ + sql: 'WITH "BARS" AS (SELECT listing_id, ts, close FROM {{input:bars_1d}}) SELECT listing_id, ts, ts AS known_at, close AS value FROM bars', + }); + expect(() => validateFeatureDefinition(def)).not.toThrow(); + }); +}); From 0cdc231579043f48385d529fbbf0a122b89dfb49 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 10:42:19 -0500 Subject: [PATCH 34/36] =?UTF-8?q?T-139:=20M2.4a=20=E2=80=94=20Versioned=20?= =?UTF-8?q?Feature=20Library=20core:=20declarative=20DuckDB=20SQL=20featur?= =?UTF-8?q?e=20definitions=20+=20`registerSignal`=20registry=20+=20version?= =?UTF-8?q?ed=20Parquet=20batch-plan=20runner=20over=20an=20injected=20`Du?= =?UTF-8?q?ckDbExecutor`=20in=20`libs/research/src/feature-library.ts`=20(?= =?UTF-8?q?pure,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/feature-library.ts | 9 ++++++-- libs/research/test/feature-library.test.ts | 25 +++++++++------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts index 131899ae..680a3bf1 100644 --- a/libs/research/src/feature-library.ts +++ b/libs/research/src/feature-library.ts @@ -1104,6 +1104,11 @@ function validateExpressionSlice( } } +// DuckDB folds identifier case for ASCII letters only; mirror that exact rule for CTE scope. +function foldAsciiIdentifier(identifier: string): string { + return identifier.replace(/[A-Z]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) + 32)); +} + function parseTableReference( tokens: readonly SqlToken[], start: number, @@ -1152,7 +1157,7 @@ function parseTableReference( `Catalog or schema-qualified relation "${tok.raw}...." is not permitted; use {{input:}} placeholders.` ); } - const cteName = tok.value.toLowerCase(); + const cteName = foldAsciiIdentifier(tok.value); if (!inScopeCtes.has(cteName)) { throw new FeatureLibraryError( 'EXTERNAL_DATA_ACCESS', @@ -1450,7 +1455,7 @@ function validateQuerySlice( 'Expected CTE name identifier after WITH in feature SQL.' ); } - const cteName = nameTok.value.toLowerCase(); + const cteName = foldAsciiIdentifier(nameTok.value); pos += 1; // Optional CTE column list `(col1, col2)`. diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index fbb76490..d50dd14b 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -1493,21 +1493,8 @@ describe('QA round 4: CTE scope must match DuckDB identifier folding (ASCII-only for (const sql of unicodeFoldProbes) { const def = makeSimpleDef({ name: 'leak', sql }); - for (const attempt of [ - () => validateFeatureDefinition(def), - () => createFeatureRegistry().registerSignal(def), - ]) { - let error: unknown; - try { - attempt(); - } catch (caught) { - error = caught; - } - expect(error).toBeInstanceOf(FeatureLibraryError); - expect(['EXTERNAL_DATA_ACCESS', 'INVALID_SQL_STATEMENT']).toContain( - (error as FeatureLibraryError).code - ); - } + expectFeatureErrorCode(() => validateFeatureDefinition(def), 'EXTERNAL_DATA_ACCESS'); + expectFeatureErrorCode(() => createFeatureRegistry().registerSignal(def), 'EXTERNAL_DATA_ACCESS'); const fake = createRecordingFakeExecutor(); let execError: unknown; @@ -1521,6 +1508,7 @@ describe('QA round 4: CTE scope must match DuckDB identifier folding (ASCII-only execError = error; } expect(execError).toBeInstanceOf(FeatureLibraryError); + expect((execError as FeatureLibraryError).code).toBe('EXTERNAL_DATA_ACCESS'); expect(fake.calls).toHaveLength(0); } }); @@ -1533,4 +1521,11 @@ describe('QA round 4: CTE scope must match DuckDB identifier folding (ASCII-only }); expect(() => validateFeatureDefinition(def)).not.toThrow(); }); + + it('accepts an exact non-ASCII quoted CTE name match', () => { + const def = makeSimpleDef({ + sql: 'WITH "Ä" AS (SELECT listing_id, ts, close FROM {{input:bars_1d}}) SELECT listing_id, ts, ts AS known_at, close AS value FROM "Ä"', + }); + expect(() => validateFeatureDefinition(def)).not.toThrow(); + }); }); From 8fe885ec540f1914d97ed5d07fe2b170dac3231b Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 10:56:21 -0500 Subject: [PATCH 35/36] T-139: tests --- libs/research/test/feature-library.test.ts | 83 +++++++++++++++++++++- 1 file changed, 81 insertions(+), 2 deletions(-) diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index d50dd14b..1b9c3559 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -1171,7 +1171,7 @@ describe('QA: relation-source allow-list and Vault boundary edge cases', () => { validateFeatureDefinition( makeSimpleDef({ inputs: ['bars_1d', 'fx_1d'], - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close / f.rate AS value FROM {{input:bars_1d}} AS b POSITIONAL JOIN {{input:fx_1d}} AS f', + sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b POSITIONAL JOIN {{input:fx_1d}} AS f', }) ) ).not.toThrow(); @@ -1180,7 +1180,7 @@ describe('QA: relation-source allow-list and Vault boundary edge cases', () => { validateFeatureDefinition( makeSimpleDef({ inputs: ['bars_1d', 'fx_1d'], - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} POSITIONAL JOIN {{input:fx_1d}} AS f', + sql: 'WITH fx AS (SELECT close AS fx_close FROM {{input:fx_1d}}) SELECT listing_id, ts, ts AS known_at, close / fx_close AS value FROM {{input:bars_1d}} POSITIONAL JOIN fx', }) ) ).not.toThrow(); @@ -1529,3 +1529,82 @@ describe('QA round 4: CTE scope must match DuckDB identifier folding (ASCII-only expect(() => validateFeatureDefinition(def)).not.toThrow(); }); }); + +describe('QA round 5: CTE scope parity with DuckDB across nesting and UNION branches', () => { + // Each case was run in a scratch in-memory DuckDB 1.4.4 session (`SET TimeZone='UTC'`) holding a + // catalog table `kv(v = 42.0)`, with {{input:bars_1d}} replaced by a one-row bars subquery. + // Leak cases returned 42.0 (catalog) in DuckDB; accepted cases returned the CTE value 1.0. + const leakCases: ReadonlyArray<{ label: string; sql: string }> = [ + { + label: 'CTE declared inside a CTE body is not visible to the outer query', + sql: 'WITH a AS (WITH kv AS (SELECT 1.0 AS v) SELECT v FROM kv) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', + }, + { + label: 'CTE declared in an earlier parenthesized UNION branch is not visible to a later branch', + sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, 1.0 AS value FROM {{input:bars_1d}} AS b UNION ALL (WITH kv AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, 1.0 AS value FROM {{input:bars_1d}} AS b) UNION ALL SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', + }, + { + label: 'CTE declared in a derived table is not visible to a sibling FROM item', + sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, (WITH kv AS (SELECT 1.0 AS v) SELECT v FROM kv) AS x, kv AS s', + }, + ]; + + it('rejects references that DuckDB binds to the catalog table, with zero executor calls', async () => { + for (const { label, sql } of leakCases) { + const def = makeSimpleDef({ name: 'leak', sql }); + let validateError: unknown; + try { + validateFeatureDefinition(def); + } catch (error) { + validateError = error; + } + expect(validateError, label).toBeInstanceOf(FeatureLibraryError); + + const fake = createRecordingFakeExecutor(); + await expect( + runFeatureBatch( + def, + { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, + fake.executor + ) + ).rejects.toBeInstanceOf(FeatureLibraryError); + expect(fake.calls).toHaveLength(0); + } + }); + + it('rejects a CTE name that differs only by Unicode normalization or an invisible character', () => { + // DuckDB matches these names byte-for-byte after ASCII folding, so neither is the CTE. + for (const sql of [ + 'WITH "Ä" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, "Ä" AS s', + 'WITH "kv​" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, "kv" AS s', + ]) { + expectFeatureErrorCode( + () => validateFeatureDefinition(makeSimpleDef({ name: 'leak', sql })), + 'EXTERNAL_DATA_ACCESS' + ); + } + }); + + it('rejects a non-ASCII space outside quotes instead of treating it as whitespace', () => { + expectFeatureErrorCode( + () => + validateFeatureDefinition( + makeSimpleDef({ + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', + }) + ), + 'INVALID_SQL_STATEMENT' + ); + }); + + it('accepts CTE references DuckDB binds to the CTE: outer CTE shadowing, top-level WITH over UNION, column lists, MATERIALIZED', () => { + for (const sql of [ + 'WITH kv AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, (WITH kv AS (SELECT v FROM kv) SELECT v FROM kv) AS s', + 'WITH kv AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, 1.0 AS value FROM {{input:bars_1d}} AS b UNION ALL SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', + 'WITH kv(v) AS (SELECT 1.0) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', + 'WITH kv AS MATERIALIZED (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', + ]) { + expect(() => validateFeatureDefinition(makeSimpleDef({ sql }))).not.toThrow(); + } + }); +}); From 7befcaa03345f10c7df21af7db99b18d4e63663c Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 21:03:51 -0500 Subject: [PATCH 36/36] T-139: tests --- libs/research/test/feature-library.test.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index 1b9c3559..9315471d 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -1559,15 +1559,21 @@ describe('QA round 5: CTE scope parity with DuckDB across nesting and UNION bran validateError = error; } expect(validateError, label).toBeInstanceOf(FeatureLibraryError); + expect((validateError as FeatureLibraryError).code, label).toBe('EXTERNAL_DATA_ACCESS'); const fake = createRecordingFakeExecutor(); - await expect( - runFeatureBatch( + let execError: unknown; + try { + await runFeatureBatch( def, { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, fake.executor - ) - ).rejects.toBeInstanceOf(FeatureLibraryError); + ); + } catch (error) { + execError = error; + } + expect(execError, label).toBeInstanceOf(FeatureLibraryError); + expect((execError as FeatureLibraryError).code, label).toBe('EXTERNAL_DATA_ACCESS'); expect(fake.calls).toHaveLength(0); } });