diff --git a/libs/data/duckdb/src/index.ts b/libs/data/duckdb/src/index.ts index 2d3bf3d9..4eace5b6 100644 --- a/libs/data/duckdb/src/index.ts +++ b/libs/data/duckdb/src/index.ts @@ -121,7 +121,13 @@ export async function createNodeDuckDbExecutor( ): Promise { const databasePath = options.databasePath ?? ':memory:'; const instance = await DuckDBInstance.create(databasePath); - const connection: DuckDBConnection = await instance.connect(); + let connection: DuckDBConnection; + try { + connection = await instance.connect(); + } catch (err) { + instance.closeSync(); + throw err; + } let closed = false; const assertOpen = (): void => { @@ -264,3 +270,7 @@ export { type DuckDbParam, type PinnedAdjFactorsArtifact, }; +export { + openResearchCopilotStore, + type OpenResearchCopilotStoreOptions, +} from './research-copilot-store'; diff --git a/libs/data/duckdb/src/research-copilot-store.ts b/libs/data/duckdb/src/research-copilot-store.ts new file mode 100644 index 00000000..941c2c53 --- /dev/null +++ b/libs/data/duckdb/src/research-copilot-store.ts @@ -0,0 +1,49 @@ +/** + * Real DuckDB `MarketDataStore` factory for the MCP research copilot stdio host + * (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`). + * + * - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff shared + * between the host and the underlying DuckDB store, and hardcodes + * `vaultOperatorAuthorized: false` so every query remains strictly + * `'vault_fenced'`. + * - Returns a {@link ManagedMarketDataStore} (`{ store, close }`) whose + * `close()` releases the underlying DuckDB connection and instance. + * - Any failure during open (native connection creation or store validation) + * releases already-acquired DuckDB resources before rejecting. + */ + +import type { + ManagedMarketDataStore, + ResearchCopilotHostConfig, + ResearchCopilotStdioHostDeps, +} from '@stock-bot/research/mcp'; +import { openDuckDbMarketDataStore } from './index'; + +export interface OpenResearchCopilotStoreOptions { + /** Optional DuckDB database path; defaults to `':memory:'`. */ + readonly databasePath?: string; + /** Optional environment overrides for DuckDB connection budget (`STOCKBOT_DUCKDB_*`). */ + readonly env?: Readonly>; +} + +/** + * Opens a Vault-fenced DuckDB-backed {@link ManagedMarketDataStore} from a + * validated {@link ResearchCopilotHostConfig} for `ResearchCopilotStdioHostDeps.openStore`. + */ +export const openResearchCopilotStore = (async ( + config: ResearchCopilotHostConfig, + options?: OpenResearchCopilotStoreOptions +): Promise => { + const opened = await openDuckDbMarketDataStore({ + curatedRoot: config.curatedRoot, + vaultCutoffTs: config.vaultCutoffTs, + vaultOperatorAuthorized: false, + ...(options?.databasePath !== undefined ? { databasePath: options.databasePath } : {}), + ...(options?.env !== undefined ? { env: options.env } : {}), + }); + + return { + store: opened.store, + close: opened.close, + }; +}) satisfies ResearchCopilotStdioHostDeps['openStore']; diff --git a/libs/data/duckdb/test/research-copilot-store-qa.test.ts b/libs/data/duckdb/test/research-copilot-store-qa.test.ts new file mode 100644 index 00000000..fc564f4b --- /dev/null +++ b/libs/data/duckdb/test/research-copilot-store-qa.test.ts @@ -0,0 +1,394 @@ +import { afterEach, describe, expect, spyOn, test } from 'bun:test'; +import { existsSync } from 'node:fs'; +import { mkdir, mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DuckDBConnection, DuckDBInstance } from '@duckdb/node-api'; +import { createNodeDuckDbExecutor, openResearchCopilotStore } from '@stock-bot/duckdb'; +import { + MarketDataStoreValidationError, + VaultHoldoutFenceError, + type BarRecord, +} from '@stock-bot/research/market-data-store'; +import { + runResearchCopilotStdioHost, + type PostgresResearchCopilotExecutor, + type QueryDataResultPayload, + type ResearchCopilotHostConfig, + type StdioInput, + type StdioOutput, +} from '@stock-bot/research/mcp'; + +// QA coverage for T-184 beyond the implementation tests: +// - budget env (`STOCKBOT_DUCKDB_*`) is forwarded and reaches DuckDB; +// - invalid budget env fails closed without leaking native handles or the Postgres URL; +// - `openStore: openResearchCopilotStore` works unwrapped (default env resolution); +// - the Vault cutoff comes from `config.vaultCutoffTs` (not a constant); +// - `databasePath` is forwarded. +// Fixture: listing 202, rows at 2025-03-10/11/12 20:00Z (known_at == ts). + +const LISTING_ID = 202; +const DAY1_MS = Date.UTC(2025, 2, 10, 20, 0, 0, 0); +const DAY2_MS = Date.UTC(2025, 2, 11, 20, 0, 0, 0); +const DAY3_MS = Date.UTC(2025, 2, 12, 20, 0, 0, 0); +const FIXED_NOW_MS = Date.UTC(2025, 2, 11, 12, 0, 0, 0); +const PG_SECRET = 'qa_only_fake_pw_7c1e'; +const FAKE_POSTGRES_URL = `postgresql://research_ro:${PG_SECRET}@127.0.0.1:5433/trading_bot_dev`; +const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; + +const tempDirs: string[] = []; +const spies: Array<{ mockRestore(): void }> = []; + +afterEach(async () => { + while (spies.length > 0) { + spies.pop()?.mockRestore(); + } + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir !== undefined) { + await rm(dir, { recursive: true, force: true }); + } + } +}); + +function track(spy: T): T { + spies.push(spy); + return spy; +} + +function bar(ts: number, base: number): BarRecord { + return { + listingId: LISTING_ID, + ts, + open: base, + high: base + 1, + low: base - 1, + close: base + 0.5, + volume: 1000 * base, + vwap: base + 0.25, + knownAt: ts, + }; +} + +const BAR1 = bar(DAY1_MS, 10); +const BAR2 = bar(DAY2_MS, 20); +const BAR3 = bar(DAY3_MS, 30); + +function config(curatedRoot: string, vaultCutoffTs: number): ResearchCopilotHostConfig { + return { + postgresUrl: FAKE_POSTGRES_URL, + curatedRoot, + vaultCutoffTs, + principalId: AGENT_PRINCIPAL, + libraryRoot: '/tmp/unused-library-root', + referenceListingIds: { XNYS: [LISTING_ID] }, + }; +} + +async function makeRoot(): Promise { + const root = await mkdtemp(join(tmpdir(), 'stockbot-t184-qa-')); + tempDirs.push(root); + return root; +} + +function utcTs(ms: number): string { + return `${new Date(ms).toISOString().slice(0, 19).replace('T', ' ')}+00`; +} + +function utcDate(ms: number): string { + return new Date(ms).toISOString().slice(0, 10); +} + +async function writeFixture(root: string): Promise { + const curatedRoot = join(root, 'curated'); + await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); + const rows = [BAR1, BAR2, BAR3] + .map( + b => + // Explicit UTC literals: casting naive timestamps to TIMESTAMPTZ would use the host TimeZone. + `(${LISTING_ID}::INTEGER, DATE '${utcDate(b.ts)}', TIMESTAMPTZ '${utcTs(b.ts)}', ${b.open}::DOUBLE, ${b.high}::DOUBLE, ${b.low}::DOUBLE, ${b.close}::DOUBLE, ${b.volume}::DOUBLE, ${b.vwap}::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '${utcTs(b.knownAt)}')` + ) + .join(',\n'); + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES ${rows}) + AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) + ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + return curatedRoot; +} + +async function collect( + iterable: AsyncIterable<{ readonly rows: readonly BarRecord[] }> +): Promise { + const out: BarRecord[] = []; + for await (const batch of iterable) { + out.push(...batch.rows); + } + return out; +} + +async function captureError(fn: () => Promise): Promise { + try { + await fn(); + } catch (err) { + return err; + } + return undefined; +} + +function fullRangeQuery() { + return { + listingIds: [LISTING_ID], + timeframe: '1d' as const, + from: '2025-03-01', + to: '2025-03-31', + asOf: '2025-03-31', + adjustment: 'raw' as const, + }; +} + +function memoryStdio(messages: readonly unknown[]): { + readonly input: StdioInput; + readonly output: StdioOutput; + raw(): string; +} { + const chunks: string[] = []; + return { + input: { + async *[Symbol.asyncIterator]() { + for (const m of messages) { + yield `${JSON.stringify(m)}\n`; + } + }, + }, + output: { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }, + raw: () => chunks.join(''), + }; +} + +function fakePg(): { executor: PostgresResearchCopilotExecutor; calls: number } { + const state = { + calls: 0, + executor: { + async query>(): Promise<{ readonly rows: readonly Row[] }> { + state.calls += 1; + return { rows: [] }; + }, + } as PostgresResearchCopilotExecutor, + }; + return state; +} + +function hostMessages(): unknown[] { + return [ + { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2024-11-05', + capabilities: {}, + clientInfo: { name: 't184-qa', version: '1.0.0' }, + }, + }, + { jsonrpc: '2.0', method: 'notifications/initialized' }, + { + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [LISTING_ID], + from: '2025-03-01', + to: '2025-03-31', + asOf: '2025-03-31', + }, + }, + }, + ]; +} + +describe('openResearchCopilotStore QA (T-184)', () => { + test('uses config.vaultCutoffTs as the only cutoff: moving the cutoff moves the visible rows', async () => { + const curatedRoot = await writeFixture(await makeRoot()); + + // Cutoff exactly at DAY2 ts: DAY2 (ts == cutoff) is excluded, only DAY1 visible. + const atDay2 = await openResearchCopilotStore(config(curatedRoot, DAY2_MS)); + try { + expect(await collect(atDay2.store.bars(fullRangeQuery()))).toEqual([BAR1]); + } finally { + await atDay2.close(); + } + + // Cutoff 1ms after DAY2: DAY1 + DAY2 visible, DAY3 still fenced. + const afterDay2 = await openResearchCopilotStore(config(curatedRoot, DAY2_MS + 1)); + try { + expect(await collect(afterDay2.store.bars(fullRangeQuery()))).toEqual([BAR1, BAR2]); + const err = await captureError(() => + collect(afterDay2.store.bars({ ...fullRangeQuery(), from: '2025-03-12' })) + ); + expect(err).toBeInstanceOf(VaultHoldoutFenceError); + } finally { + await afterDay2.close(); + } + + // Cutoff after all rows: everything visible (proves no hidden constant cutoff). + const late = await openResearchCopilotStore(config(curatedRoot, Date.UTC(2025, 5, 1))); + try { + expect(await collect(late.store.bars(fullRangeQuery()))).toEqual([BAR1, BAR2, BAR3]); + } finally { + await late.close(); + } + }); + + test('forwards STOCKBOT_DUCKDB_* budget env so DuckDB receives the configured spill directory, threads and memory limit', async () => { + const root = await makeRoot(); + const curatedRoot = await writeFixture(root); + const spillDir = join(root, 'spill'); + await mkdir(spillDir, { recursive: true }); + + const runSpy = track(spyOn(DuckDBConnection.prototype, 'run')); + const handle = await openResearchCopilotStore(config(curatedRoot, DAY2_MS), { + env: { + STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB', + STOCKBOT_DUCKDB_THREADS: '1', + STOCKBOT_DUCKDB_TEMP_DIRECTORY: spillDir, + }, + }); + try { + expect(await collect(handle.store.bars(fullRangeQuery()))).toEqual([BAR1]); + } finally { + await handle.close(); + } + + const statements = runSpy.mock.calls.map(call => String(call[0])); + expect(statements).toContain(`SET temp_directory = '${spillDir}';`); + expect(statements).toContain('SET threads = 1;'); + expect(statements).toContain("SET memory_limit = '512MB';"); + }); + + test('invalid budget env fails closed: open rejects, native connection and instance closed once, no Postgres URL in the error', async () => { + const curatedRoot = await writeFixture(await makeRoot()); + const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync')); + + const err = await captureError(() => + openResearchCopilotStore(config(curatedRoot, DAY2_MS), { + env: { STOCKBOT_DUCKDB_THREADS: 'not-a-number' }, + }) + ); + + expect(err).toBeInstanceOf(MarketDataStoreValidationError); + expect(connClose).toHaveBeenCalledTimes(1); + expect(instClose).toHaveBeenCalledTimes(1); + const text = `${(err as Error).message} ${(err as Error).stack ?? ''}`; + expect(text).not.toContain(PG_SECRET); + expect(text).not.toContain('postgresql://'); + }); + + test('forwards databasePath: a file-backed DuckDB database is created at the given path', async () => { + const root = await makeRoot(); + const curatedRoot = await writeFixture(root); + const dbPath = join(root, 'copilot.duckdb'); + expect(existsSync(dbPath)).toBe(false); + + const handle = await openResearchCopilotStore(config(curatedRoot, DAY2_MS), { + databasePath: dbPath, + }); + try { + expect(existsSync(dbPath)).toBe(true); + expect(await collect(handle.store.bars(fullRangeQuery()))).toEqual([BAR1]); + } finally { + await handle.close(); + } + }); + + test('host wired with openStore: openResearchCopilotStore (unwrapped, default env) serves query_data fenced at config cutoff and closes DuckDB once', async () => { + const curatedRoot = await writeFixture(await makeRoot()); + const pg = fakePg(); + const io = memoryStdio(hostMessages()); + const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync')); + + await runResearchCopilotStdioHost({ + config: config(curatedRoot, DAY2_MS + 1), + openExecutor: async () => ({ executor: pg.executor, close: async () => {} }), + openStore: openResearchCopilotStore, + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'qa-id', + now: () => FIXED_NOW_MS, + stdio: { input: io.input, output: io.output }, + }); + + const lines = io + .raw() + .trimEnd() + .split('\n') + .map(l => JSON.parse(l) as { id: number; result: Record }); + expect(lines.map(l => l.id)).toEqual([1, 2]); + const envelope = lines[1]!.result as { + isError?: boolean; + content: Array<{ text: string }>; + }; + expect(envelope.isError).toBeUndefined(); + const payload = JSON.parse(envelope.content[0]!.text) as QueryDataResultPayload; + expect(payload.vaultCutoffTs).toBe(DAY2_MS + 1); + expect(payload.toMs).toBe(DAY2_MS); + expect(payload.rows).toEqual([BAR1, BAR2]); + expect(io.raw()).not.toContain(PG_SECRET); + expect(pg.calls).toBe(0); + expect(connClose).toHaveBeenCalledTimes(1); + expect(instClose).toHaveBeenCalledTimes(1); + }); + + test('host with empty curatedRoot: query_data fails without hanging, leaks no Postgres URL, and DuckDB still closes once at EOF', async () => { + const root = await makeRoot(); + const emptyRoot = join(root, 'curated'); + await mkdir(emptyRoot, { recursive: true }); + const io = memoryStdio(hostMessages()); + const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync')); + + await runResearchCopilotStdioHost({ + config: config(emptyRoot, DAY2_MS), + openExecutor: async () => ({ executor: fakePg().executor, close: async () => {} }), + openStore: openResearchCopilotStore, + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'qa-id', + now: () => FIXED_NOW_MS, + stdio: { input: io.input, output: io.output }, + }); + + const lines = io + .raw() + .trimEnd() + .split('\n') + .map( + l => + JSON.parse(l) as { + id: number; + result?: { isError?: boolean; content?: Array<{ text: string }> }; + error?: unknown; + } + ); + const toolResponse = lines.find(l => l.id === 2); + expect(toolResponse).toBeDefined(); + const failed = toolResponse!.error !== undefined || toolResponse!.result?.isError === true; + expect(failed).toBe(true); + expect(io.raw()).not.toContain(PG_SECRET); + expect(connClose).toHaveBeenCalledTimes(1); + expect(instClose).toHaveBeenCalledTimes(1); + }); +}); diff --git a/libs/data/duckdb/test/research-copilot-store.test.ts b/libs/data/duckdb/test/research-copilot-store.test.ts new file mode 100644 index 00000000..2c1acc40 --- /dev/null +++ b/libs/data/duckdb/test/research-copilot-store.test.ts @@ -0,0 +1,530 @@ +import { afterEach, describe, expect, spyOn, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { mkdir, mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DuckDBConnection, DuckDBInstance } from '@duckdb/node-api'; +import { + createNodeDuckDbExecutor, + openResearchCopilotStore, +} from '@stock-bot/duckdb'; +import { + MarketDataStoreValidationError, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, + type BarRecord, +} from '@stock-bot/research/market-data-store'; +import { + RESEARCH_COPILOT_HOST_NAME, + RESEARCH_COPILOT_HOST_VERSION, + runResearchCopilotStdioHost, + type PostgresResearchCopilotExecutor, + type QueryDataResultPayload, + type ResearchCopilotHostConfig, + type ResearchCopilotStdioHostDeps, + type StdioInput, + type StdioOutput, +} from '@stock-bot/research/mcp'; + +// Pinned synthetic fixture for T-184 (real-DuckDB store factory & stdio host wiring): +// - Listing 101 (USD), Vault cutoff 2025-06-01T00:00:00.000Z +// - Baseline visible row: 2025-05-30 20:00:00Z (known_at 2025-05-30 20:00:00Z) +// - Excluded rows: +// * at-cutoff ts: 2025-06-01 00:00:00Z (known_at 2025-05-30 20:00:00Z) +// * post-cutoff ts: 2025-06-02 20:00:00Z (known_at 2025-06-02 20:00:00Z) +// * late-known pre-cutoff ts: 2025-05-29 20:00:00Z (known_at 2025-06-01 00:00:00Z) + +const LISTING_ID = 101; +const VAULT_CUTOFF_MS = Date.UTC(2025, 5, 1, 0, 0, 0, 0); +const FIXED_NOW_MS = Date.UTC(2025, 4, 31, 12, 0, 0, 0); +const FAKE_POSTGRES_URL = + 'postgresql://research_ro:test_only_not_a_real_secret@127.0.0.1:5433/trading_bot_dev?sslmode=disable'; +const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; + +const EXPECTED_VISIBLE_BAR: BarRecord = { + listingId: LISTING_ID, + ts: Date.UTC(2025, 4, 30, 20, 0, 0, 0), + open: 100.5, + high: 102.25, + low: 99.75, + close: 101.5, + volume: 123_456, + vwap: 101.1, + knownAt: Date.UTC(2025, 4, 30, 20, 0, 0, 0), +}; + +const tempDirs: string[] = []; +const activeSpies: Array<{ mockRestore(): void }> = []; + +function trackSpy(spy: T): T { + activeSpies.push(spy); + return spy; +} + +afterEach(async () => { + while (activeSpies.length > 0) { + activeSpies.pop()?.mockRestore(); + } + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir !== undefined) { + await rm(dir, { recursive: true, force: true }); + } + } +}); + +function buildHostConfig( + curatedRoot: string, + overrides: Partial = {} +): ResearchCopilotHostConfig { + return { + postgresUrl: FAKE_POSTGRES_URL, + curatedRoot, + vaultCutoffTs: VAULT_CUTOFF_MS, + principalId: VALID_AGENT_PRINCIPAL, + libraryRoot: '/tmp/unused-library-root', + referenceListingIds: { XNYS: [LISTING_ID] }, + ...overrides, + }; +} + +function buildDuckDbBudgetEnv(duckTempDir: string): Readonly> { + return { + STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCKBOT_DUCKDB_THREADS: '2', + STOCKBOT_DUCKDB_TEMP_DIRECTORY: duckTempDir, + }; +} + +async function buildBarsFixture(): Promise<{ + readonly curatedRoot: string; + readonly duckTempDir: string; +}> { + const root = await mkdtemp(join(tmpdir(), 'stockbot-mcp-duckdb-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + + await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (${LISTING_ID}::INTEGER, DATE '2025-05-29', TIMESTAMPTZ '2025-05-29 20:00:00+00', 94.0::DOUBLE, 96.0::DOUBLE, 93.5::DOUBLE, 95.0::DOUBLE, 80000.0::DOUBLE, 94.8::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-06-01 00:00:00+00'), + (${LISTING_ID}::INTEGER, DATE '2025-05-30', TIMESTAMPTZ '2025-05-30 20:00:00+00', 100.5::DOUBLE, 102.25::DOUBLE, 99.75::DOUBLE, 101.5::DOUBLE, 123456.0::DOUBLE, 101.1::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-30 20:00:00+00'), + (${LISTING_ID}::INTEGER, DATE '2025-06-01', TIMESTAMPTZ '2025-06-01 00:00:00+00', 199.0::DOUBLE, 201.0::DOUBLE, 198.0::DOUBLE, 200.0::DOUBLE, 200000.0::DOUBLE, 199.5::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-30 20:00:00+00'), + (${LISTING_ID}::INTEGER, DATE '2025-06-02', TIMESTAMPTZ '2025-06-02 20:00:00+00', 299.0::DOUBLE, 301.0::DOUBLE, 298.0::DOUBLE, 300.0::DOUBLE, 300000.0::DOUBLE, 299.5::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-06-02 20:00:00+00') + ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) + ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + return { curatedRoot, duckTempDir }; +} + +function createMemoryOutput(): { + readonly output: StdioOutput; + jsonLines(): unknown[]; +} { + const chunks: string[] = []; + const output: StdioOutput = { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }; + return { + output, + jsonLines: () => { + const raw = chunks.join(''); + if (raw.length === 0) { + return []; + } + return raw + .trimEnd() + .split('\n') + .map(line => JSON.parse(line) as unknown); + }, + }; +} + +function createMemoryInput(messages: readonly unknown[]): StdioInput { + return { + async *[Symbol.asyncIterator]() { + for (const msg of messages) { + yield `${JSON.stringify(msg)}\n`; + } + }, + }; +} + +function createFakePostgresExecutor(): { + readonly executor: PostgresResearchCopilotExecutor; + readonly calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }>; +} { + const calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }> = []; + const executor: PostgresResearchCopilotExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return { rows: [] }; + }, + }; + return { executor, calls }; +} + +async function collectBars( + iterable: AsyncIterable<{ readonly rows: readonly BarRecord[] }> +): Promise { + const rows: BarRecord[] = []; + for await (const batch of iterable) { + rows.push(...batch.rows); + } + return rows; +} + +describe('openResearchCopilotStore (@duckdb/node-api)', () => { + test('source invariants: no pg import, no process.env read, no console logging, always vault-fenced', () => { + const sourcePath = join(import.meta.dir, '..', 'src', 'research-copilot-store.ts'); + const source = readFileSync(sourcePath, 'utf8'); + + expect(source).not.toMatch(/from\s+['"]pg['"]/); + expect(source).not.toMatch(/require\(\s*['"]pg['"]\s*\)/); + expect(source).not.toContain('process.env'); + expect(source).not.toMatch(/\bprocess\b/); + expect(source).not.toContain('console.'); + expect(source).toContain('vaultOperatorAuthorized: false'); + + // Verify typed assignability to ResearchCopilotStdioHostDeps['openStore'] without casts. + const directFactory: ResearchCopilotStdioHostDeps['openStore'] = openResearchCopilotStore; + const wrappedFactory: ResearchCopilotStdioHostDeps['openStore'] = cfg => + openResearchCopilotStore(cfg); + expect(typeof directFactory).toBe('function'); + expect(typeof wrappedFactory).toBe('function'); + }); + + test('enforces single Vault cutoff directly on store.bars(), replays identically, and blocks vault_evaluation_only even for operator principal', async () => { + const { curatedRoot, duckTempDir } = await buildBarsFixture(); + const config = buildHostConfig(curatedRoot, { principalId: 'operator' }); + + const handle = await openResearchCopilotStore(config, { + env: buildDuckDbBudgetEnv(duckTempDir), + }); + + try { + expect(Object.keys(handle).sort()).toEqual(['close', 'store']); + + // Straddling query: to and asOf exceed cutoff -> only visible pre-cutoff row returned. + const firstRun = await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-05-28', + to: '2025-06-05', + asOf: '2025-06-05', + adjustment: 'raw', + }) + ); + expect(firstRun).toEqual([EXPECTED_VISIBLE_BAR]); + + // Replay produces identical results. + const replayRun = await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-05-28', + to: '2025-06-05', + asOf: '2025-06-05', + adjustment: 'raw', + }) + ); + expect(replayRun).toEqual(firstRun); + + // Query starting at cutoff throws VaultHoldoutFenceError. + let atCutoffErr: unknown; + try { + await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-01', + to: '2025-06-05', + adjustment: 'raw', + }) + ); + } catch (err) { + atCutoffErr = err; + } + expect(atCutoffErr).toBeInstanceOf(VaultHoldoutFenceError); + + // Query starting after cutoff throws VaultHoldoutFenceError. + let afterCutoffErr: unknown; + try { + await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-02', + to: '2025-06-05', + adjustment: 'raw', + }) + ); + } catch (err) { + afterCutoffErr = err; + } + expect(afterCutoffErr).toBeInstanceOf(VaultHoldoutFenceError); + + // vault_evaluation_only is always rejected even when config.principalId is 'operator'. + let scopeErr: unknown; + try { + await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-05-28', + to: '2025-06-05', + adjustment: 'raw', + scope: 'vault_evaluation_only', + }) + ); + } catch (err) { + scopeErr = err; + } + expect(scopeErr).toBeInstanceOf(VaultScopeNotAuthorizedError); + } finally { + await handle.close(); + } + }); + + test('wires into runResearchCopilotStdioHost end-to-end, serves initialize + query_data, and closes DuckDB exactly once at EOF', async () => { + const { curatedRoot, duckTempDir } = await buildBarsFixture(); + const config = buildHostConfig(curatedRoot); + const fakePg = createFakePostgresExecutor(); + const sink = createMemoryOutput(); + const input = createMemoryInput([ + { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2024-11-05', + capabilities: {}, + clientInfo: { name: 'duckdb-host-test', version: '1.0.0' }, + }, + }, + { + jsonrpc: '2.0', + method: 'notifications/initialized', + }, + { + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [LISTING_ID], + from: '2025-05-28', + to: '2025-06-05', + asOf: '2025-06-05', + }, + }, + }, + ]); + + // Install call-through spies after fixture writer is closed so counts reflect only the host store. + const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); + + let capturedStore: Awaited>['store'] | undefined; + + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => ({ + executor: fakePg.executor, + close: async () => {}, + }), + openStore: async cfg => { + const opened = await openResearchCopilotStore(cfg, { + env: buildDuckDbBudgetEnv(duckTempDir), + }); + capturedStore = opened.store; + return opened; + }, + createLibraryCardReader: async () => ({ + listLibraryCards: async () => [], + }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input, output: sink.output }, + }); + + const responses = sink.jsonLines() as Array<{ + readonly id: number; + readonly result: Record; + }>; + expect(responses).toHaveLength(2); + + expect(responses[0]!.id).toBe(1); + expect(responses[0]!.result.serverInfo).toEqual({ + name: RESEARCH_COPILOT_HOST_NAME, + version: RESEARCH_COPILOT_HOST_VERSION, + }); + + expect(responses[1]!.id).toBe(2); + const toolEnvelope = responses[1]!.result as { + readonly isError?: boolean; + readonly content: ReadonlyArray<{ readonly type: 'text'; readonly text: string }>; + }; + expect(toolEnvelope.isError).toBeUndefined(); + + const payload = JSON.parse(toolEnvelope.content[0]!.text) as QueryDataResultPayload; + expect(payload.vaultCutoffTs).toBe(VAULT_CUTOFF_MS); + expect(payload.clampedTo).toBe(true); + expect(payload.clampedAsOf).toBe(true); + expect(payload.toMs).toBe(VAULT_CUTOFF_MS - 1); + expect(payload.asOfMs).toBe(VAULT_CUTOFF_MS - 1); + expect(payload.rows).toEqual([EXPECTED_VISIBLE_BAR]); + + expect(fakePg.calls).toHaveLength(0); + expect(connCloseSpy).toHaveBeenCalledTimes(1); + expect(instCloseSpy).toHaveBeenCalledTimes(1); + + // Confirm the host-opened store rejects subsequent queries after EOF cleanup. + expect(capturedStore).toBeDefined(); + let postCloseErr: unknown; + try { + await collectBars( + capturedStore!.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-05-28', + to: '2025-05-31', + adjustment: 'raw', + }) + ); + } catch (err) { + postCloseErr = err; + } + expect(postCloseErr).toBeInstanceOf(Error); + expect((postCloseErr as Error).message).toContain('closed'); + }); + + test('directly opened handle resolves close() and rejects subsequent valid bars() queries', async () => { + const { curatedRoot, duckTempDir } = await buildBarsFixture(); + const config = buildHostConfig(curatedRoot); + + const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); + + const handle = await openResearchCopilotStore(config, { + env: buildDuckDbBudgetEnv(duckTempDir), + }); + + await handle.close(); + await handle.close(); + + expect(connCloseSpy).toHaveBeenCalledTimes(1); + expect(instCloseSpy).toHaveBeenCalledTimes(1); + + let postCloseErr: unknown; + try { + await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-05-28', + to: '2025-05-31', + adjustment: 'raw', + }) + ); + } catch (err) { + postCloseErr = err; + } + expect(postCloseErr).toBeInstanceOf(Error); + expect((postCloseErr as Error).message).toContain('closed'); + }); + + test('fail-closed: empty curatedRoot rejects on first bars() read and closes cleanly in finally', async () => { + const root = await mkdtemp(join(tmpdir(), 'stockbot-mcp-empty-')); + tempDirs.push(root); + const emptyCuratedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(emptyCuratedRoot, { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); + + const handle = await openResearchCopilotStore(buildHostConfig(emptyCuratedRoot), { + env: buildDuckDbBudgetEnv(duckTempDir), + }); + + let readErr: unknown; + try { + await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-05-28', + to: '2025-05-31', + adjustment: 'raw', + }) + ); + } catch (err) { + readErr = err; + } finally { + await handle.close(); + } + + expect(readErr).toBeInstanceOf(Error); + expect(connCloseSpy).toHaveBeenCalledTimes(1); + expect(instCloseSpy).toHaveBeenCalledTimes(1); + }); + + test('fail-closed: invalid relative curatedRoot closes acquired connection and instance before rejecting', async () => { + const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); + + let openErr: unknown; + try { + await openResearchCopilotStore(buildHostConfig('relative/curated/root')); + } catch (err) { + openErr = err; + } + + expect(openErr).toBeInstanceOf(MarketDataStoreValidationError); + expect(connCloseSpy).toHaveBeenCalledTimes(1); + expect(instCloseSpy).toHaveBeenCalledTimes(1); + }); + + test('fail-closed: rejected native instance.connect() closes allocated DuckDBInstance before propagating error', async () => { + const connectFailure = new Error('simulated native connect failure'); + const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); + const connectSpy = trackSpy( + spyOn(DuckDBInstance.prototype, 'connect').mockImplementationOnce(async () => { + throw connectFailure; + }) + ); + + let openErr: unknown; + try { + await openResearchCopilotStore(buildHostConfig('/tmp/unused-curated-root')); + } catch (err) { + openErr = err; + } + + expect(openErr).toBe(connectFailure); + expect(connectSpy).toHaveBeenCalledTimes(1); + expect(connCloseSpy).toHaveBeenCalledTimes(0); + expect(instCloseSpy).toHaveBeenCalledTimes(1); + }); +}); diff --git a/libs/research/README.md b/libs/research/README.md index f9cd428e..44c85510 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -276,6 +276,7 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **`createPostgresListingCalendarPort({ executor, schema? })`** and **`createExchangeCalendarResolver({ listingCalendars, sessionDates, earlyCloses? })`** (exported from `@stock-bot/research/mcp` alongside `ListingCalendarPort`, `SessionDatesPort`, `EarlyCloseOverrides`, `PostgresListingCalendarError`, and `ExchangeCalendarResolverError`) implement `EventStudyExchangeCalendarResolver` for `createEventStudyTool` with zero `node:*` imports and zero runtime `pg` dependency. - **Injected ports & fail-closed validation:** `createPostgresListingCalendarPort` issues one read-only parameterized `SELECT` joining `listing.mic` to `exchange.mic` (`WHERE l.listing_id = ANY($1::integer[])`), validating `executor.query` (`INVALID_EXECUTOR`), optional `schema` (`^[a-z_][a-z0-9_]*$`, `INVALID_SCHEMA`), and returned rows (`INVALID_ROW`). `SessionDatesPort.listSessionDates({ calendarCode, fromDate, toDate })` is called once per distinct calendar code in sorted order; the resolver fails closed with no partial result on missing, unrequested, or conflicting listing mappings or on malformed, duplicate, unsorted, or out-of-window session dates. Empty `listingIds` returns empty `{ calendars, listingCalendarId }` with zero port calls. - **Supported DST range & default half-day close:** Session close timestamps convert Eastern Time (`America/New_York` / `America/Toronto`) to UTC epoch milliseconds across `1976-01-01` through `2030-12-31` inclusive (matching `tools/curate-etl/src/session_close.rs` across the `1976–1986`, `1987–2006`, and `2007–2030` DST eras) and throw `ExchangeCalendarResolverError('UNSUPPORTED_DATE')` outside that range. Optional `earlyCloses` (`{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, integer minutes in `1..=960`, e.g. `780` for `13:00 ET`) overrides the close on listed dates; when `earlyCloses` is omitted, every session closes at `16:00 ET` and exchange half-days are treated as full `16:00 ET` trading days. +- **Bar-derived `SessionDatesPort` (`createBarSessionDatesPort({ store, referenceListingIds })`):** Exported from `@stock-bot/research/mcp` alongside `BarSessionDatesPortOptions` and `BarSessionDatesError`. Keys in `referenceListingIds` are exact `exchange.calendar_code` strings (e.g. `XNYS`, `XTSE`) mapped to non-empty, duplicate-free arrays of positive INT32 reference listing IDs whose daily bars define that exchange's session dates; the caller owns reference-listing coverage so gaps do not omit real sessions. Each `listSessionDates` call queries `store.bars({ listingIds, timeframe: '1d', from, to, adjustment: 'raw' })` once with `scope` and `asOf` omitted so the store's default `'vault_fenced'` scope applies (`'vault_evaluation_only'` is never passed), propagates store errors (including `VaultHoldoutFenceError`) unchanged, derives UTC session dates from `BarRecord.ts` (`Math.floor(ts / MS_PER_DAY)`), and fails closed on unknown calendars, malformed queries, or invalid bars. ### Filesystem Library Cards Adapter @@ -286,6 +287,25 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported ### Copilot Server - **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions. +- **`createPostgresResearchCopilotServer(options)`** (exported from `@stock-bot/research/mcp` alongside `PostgresResearchCopilotServerOptions` and `PostgresResearchCopilotExecutor`) wires one shared PostgreSQL executor into `createPostgresSymbolSearchPort`, `createPostgresTrialRefPort`, `createPostgresFindingWritePort`, `createPostgresKnowledgeReaders`, `createPostgresListingCalendarPort` + `createExchangeCalendarResolver`, and `trial_ledger`, while keeping `store`, `listLibraryCards`, `sessionDates` (with optional `earlyCloses`), `newId`, and `now` caller-supplied. `vaultContext.vaultCutoffTs` is the single authoritative Vault cutoff for all Vault-fenced tools and `trial_ledger` visibility lookups. When `schema` is supplied, the schema-aware adapters qualify their tables with `"".`, while `trial_ledger` writes and cluster DSR reads resolve through the executor's `search_path`. + +### Stdio Host Composition + +- **`parseResearchCopilotHostConfig(env)`** and **`runResearchCopilotStdioHost(deps)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotHostConfig`, `ResearchCopilotHostConfigError`, `ResearchCopilotStdioHostDeps`, `RESEARCH_COPILOT_HOST_NAME`, and `RESEARCH_COPILOT_HOST_VERSION`) provide a pure, dependency-free stdio host layer (`libs/research/src/mcp/host/stdio-host.ts`) with no `pg`, DuckDB, `node:*`, or bare `process` references. +- **Environment variables (`RESEARCH_MCP_*`):** Unrelated keys are ignored; unknown `RESEARCH_MCP_*` keys, missing required variables, blank values, and malformed fields throw `ResearchCopilotHostConfigError` naming the variable without exposing raw values or credentials. + +| Variable | Required | Format | +| --- | --- | --- | +| `RESEARCH_MCP_POSTGRES_URL` | Yes | `postgres://` or `postgresql://` URL with non-empty host (never echoed in errors) | +| `RESEARCH_MCP_POSTGRES_SCHEMA` | No | PostgreSQL identifier `^[a-z_][a-z0-9_]*$` | +| `RESEARCH_MCP_CURATED_ROOT` | Yes | Non-blank path string for curated Parquet datasets (validated by the store factory) | +| `RESEARCH_MCP_VAULT_CUTOFF_TS` | Yes | Strict ISO-8601 UTC instant with seconds and `Z` suffix, optional ms (e.g. `2025-06-01T00:00:00Z`) | +| `RESEARCH_MCP_PRINCIPAL_ID` | Yes | `operator` or `agent:` (UUID v1–8, RFC variant) | +| `RESEARCH_MCP_LIBRARY_ROOT` | Yes | Non-blank directory path containing `library.yml` (validated by the reader factory) | +| `RESEARCH_MCP_SESSION_REFERENCE_LISTINGS` | Yes | JSON object `{ "": [, ...] }` (non-empty, distinct IDs), e.g. `{"XNYS":[101,102],"XTSE":[201]}` | +| `RESEARCH_MCP_EARLY_CLOSES` | No | JSON object `{ "": { "": <1..960 ET min> } }` within `1976-01-01..=2030-12-31`, e.g. `{"XNYS":{"2024-11-29":780}}` | + +- **Usage, single Vault cutoff & cleanup ownership:** Pass the parsed `config` to `runResearchCopilotStdioHost({ config, openExecutor, openStore, createLibraryCardReader, newId, now, stdio? })`. The host acquires `openExecutor` → `openStore` → `createLibraryCardReader`, builds `createBarSessionDatesPort` and `createPostgresResearchCopilotServer` (`stock-bot-research-copilot` / `0.1.0`) with `vaultContext: { vaultCutoffTs: config.vaultCutoffTs }`, and starts `runStdioServer` only after all setup succeeds. Callers' `openStore(config)` factory must configure its `MarketDataStore` with the same `config.vaultCutoffTs` so store queries and session-date derivation share one cutoff. Each factory owns internal cleanup on its own failed startup; once a handle is returned, the host awaits `close()` on every acquired handle exactly once in reverse acquisition order on EOF or error, preserving safe primary errors and replacing credential-bearing or uninspectable failures with fixed stage-specific errors. Keep all startup and runtime diagnostics off `stdout` (use `stderr` or structured logs outside stdio) so `stdout` carries only newline-delimited JSON-RPC frames. ### Remaining M2 MCP Items (Later Tasks) @@ -311,3 +331,24 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/feature-librar - **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. + +## `marimo check`-Gated Notebook Snapshot Exporter + +Exported from `@stock-bot/research` (`libs/research/src/notebook-snapshot.ts`). Subprocess execution and filesystem access are injected via `NotebookCommandRunner` and `NotebookSnapshotFs`, and `node:crypto` is loaded lazily at call time so the shared package barrel remains browser-bundleable. Command flags and JSON report validation are confirmed against **marimo `0.26.0`** (pinned in `python/uv.lock`). + +### API & Ports + +- **`exportNotebookSnapshot(options)`** — Validates options and paths, confirms `notebookPath` is an existing regular `.py` file, gates on `marimo check --format=json `, and only on a clean check reserves a unique sibling `.html` temp file via `fs.createExclusive` and runs `marimo export html -o --force` before computing byte length and lowercase SHA-256 and atomically publishing via `fs.rename(tempPath, outputPath)`. +- **Frozen receipt (`NotebookSnapshotReceipt`)** — Returns `Object.freeze({ notebookPath, outputPath, bytes, sha256, checkDiagnostics })`, where `checkDiagnostics` is the deep-frozen marimo JSON report (or `null` when `marimo check` exits `0` with empty stdout). +- **`NotebookCommandRunner`** — Must execute `command` directly with `args` as an argv array (never a shell string). On timeout (default `120_000` ms per command), implementations must terminate the subprocess and reject with `code: 'ETIMEDOUT'` **only after the process has exited and stopped writing** so cleanup cannot race with late writes. +- **`NotebookSnapshotFs`** — Minimal port requiring `stat`, `createExclusive` (must throw `code: 'EEXIST'` on collision), `readBytes`, `rename`, and idempotent `remove`. On any export, read, or publish failure, only the owned temp file is removed and any pre-existing `outputPath` keeps its original bytes. +- **Fail-closed error codes (`NotebookSnapshotError`)** — `INVALID_OPTION`, `INVALID_PATH`, `NOTEBOOK_NOT_FOUND`, `CHECK_FAILED` (nonzero check exit, `summary.errored === true`, `type: 'error'`, or `severity: 'breaking'`), `CHECK_OUTPUT_INVALID` (non-JSON stdout on exit `0` or malformed `{ issues, summary }` / `summary.total_files !== 1`), `EXPORT_FAILED`, `EXPORT_EMPTY`, and `TIMEOUT`. Formatting and runtime advisories may accompany a clean check. +- **Lexical roots & execution notice:** `allowedNotebookRoot` and `allowedOutputRoot` enforce lexical POSIX path-component containment (blocking `..` traversal and same-prefix sibling escapes); callers must supply trusted directories and keep the notebook file stable between check and export. Note that `marimo export html` **executes notebook cells**. + +### Manual Host Smoke Check (Director / Host Only) + +Automated tests use fakes and never spawn `marimo`. On a host with the pinned `python/` `uv` environment (`marimo 0.26.0`): + +1. Ensure `STOCK_BOT_TRIAL_LEDGER_DSN` is **unset** so the smoke check does not append trial rows to `trial_ledger`. +2. Target `research/notebooks/ca_shorts_filings_study.py` against a fixed Vault-fenced dataset and run `exportNotebookSnapshot` (or the two commands it issues: `uv run --project python marimo check --format=json research/notebooks/ca_shorts_filings_study.py` followed by `uv run --project python marimo export html research/notebooks/ca_shorts_filings_study.py -o --force`). +3. Record the pinned inputs, whether `marimo check` reported 0 errors, and whether the exported HTML opens cleanly. Quant owns any research claims (including notebook revision, dataset ID, sample window, Vault cutoff, baseline, and cost assumptions); any paper or live write access requires a separate scope decision. diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index bb5e7062..b2e95446 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -6,6 +6,7 @@ export * from './market-data-store'; export * from './market-data-store-duckdb'; export * from './market-data-store-questdb'; export * from './market-data-store-routed'; +export * from './notebook-snapshot'; export * from './signal-panel'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/mcp/adapters/bar-session-dates.ts b/libs/research/src/mcp/adapters/bar-session-dates.ts new file mode 100644 index 00000000..d87b1219 --- /dev/null +++ b/libs/research/src/mcp/adapters/bar-session-dates.ts @@ -0,0 +1,278 @@ +/** + * Bar-derived {@link SessionDatesPort} adapter for the MCP copilot `event_study` + * exchange-calendar resolver (`createExchangeCalendarResolver`). + * + * Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare + * `process` access, no `pg` dependency, and no DuckDB driver import. + * + * Daily bar timestamp convention: + * - In `libs/research/src/market-data-store-duckdb.ts`, `planBars1dQuery` + * projects `epoch_ms(b.ts) AS ts` and `mapBarRows` validates it as an integer + * UTC epoch millisecond value on `BarRecord.ts`. + * - In `tools/curate-etl/src/curate_bars.rs`, curated daily bars are stamped at + * `16:00:00 America/New_York` (`16:00 ET`), which converts to `20:00:00Z` + * (EDT) or `21:00:00Z` (EST) on the same UTC calendar date. + * - Therefore, `Math.floor(bar.ts / MS_PER_DAY)` yields the session's integer + * UTC day key (`formatDayKeyUtc`). Close timestamps and optional early-close + * overrides remain owned by `createExchangeCalendarResolver`. + * + * Vault fence behavior: + * - Queries `store.bars` with `timeframe: '1d'` and `adjustment: 'raw'`, + * omitting `scope` and `asOf` so the injected store applies its default + * `'vault_fenced'` scope. Never passes `'vault_evaluation_only'`. + * - Errors thrown by the store (including `VaultHoldoutFenceError`) propagate + * unchanged. + */ + +import type { MarketDataStore } from '../../market-data-store'; +import { + MS_PER_DAY, + formatDayKeyUtc, + isPlainRecord, + isValidEpochMs, + isValidInt32, + parseCalendarDayKey, +} from '../../panel-shared'; +import type { SessionDatesPort, SessionDatesQuery } from './exchange-calendars'; + +/** Error codes thrown by {@link BarSessionDatesError}. */ +export type BarSessionDatesErrorCode = + | 'invalid_options' + | 'unknown_calendar' + | 'invalid_query' + | 'invalid_bar'; + +/** Optional error constructor metadata for {@link BarSessionDatesError}. */ +export interface BarSessionDatesErrorOptions { + readonly cause?: unknown; +} + +/** Typed fail-closed error thrown by {@link createBarSessionDatesPort}. */ +export class BarSessionDatesError extends RangeError { + readonly code: BarSessionDatesErrorCode; + override readonly cause?: unknown; + + constructor( + code: BarSessionDatesErrorCode, + message: string, + options?: BarSessionDatesErrorOptions + ) { + super(message, options?.cause !== undefined ? { cause: options.cause } : undefined); + this.name = 'BarSessionDatesError'; + this.code = code; + if (options?.cause !== undefined) { + this.cause = options.cause; + } + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Factory options for {@link createBarSessionDatesPort}. */ +export interface BarSessionDatesPortOptions { + readonly store: Pick; + /** + * Caller-configured reference listing IDs per `exchange.calendar_code` + * (e.g. `XNYS`, `XTSE`). The union of their daily bars defines the exchange's + * session dates. + */ + readonly referenceListingIds: Readonly>; +} + +interface CalendarReferenceConfig { + readonly listingIds: readonly number[]; + readonly listingIdSet: ReadonlySet; +} + +function isPlainObjectRecord(value: unknown): value is Record { + if (typeof value !== 'object' || value === null) { + return false; + } + const proto: unknown = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +function parseQueryDayKey(value: unknown, field: string): number { + return parseCalendarDayKey(value, field, (message, cause) => + new BarSessionDatesError( + 'invalid_query', + message, + cause !== undefined ? { cause } : undefined + ) + ); +} + +function validateOptions(options: BarSessionDatesPortOptions): { + readonly store: Pick; + readonly calendars: ReadonlyMap; +} { + if (!isPlainRecord(options)) { + throw new BarSessionDatesError( + 'invalid_options', + 'Invalid options: expected an object with store and referenceListingIds.' + ); + } + + const { store, referenceListingIds } = options; + if (typeof store !== 'object' || store === null || typeof store.bars !== 'function') { + throw new BarSessionDatesError( + 'invalid_options', + 'Invalid "store": expected an object with a callable bars(query) method.' + ); + } + + if (!isPlainObjectRecord(referenceListingIds)) { + throw new BarSessionDatesError( + 'invalid_options', + 'Invalid "referenceListingIds": expected a plain object mapping calendar codes to positive INT32 listing ID arrays.' + ); + } + + const calendars = new Map(); + const entries = Object.entries(referenceListingIds); + + for (let i = 0; i < entries.length; i += 1) { + const [calendarCode, rawIds] = entries[i] as [string, unknown]; + if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) { + throw new BarSessionDatesError( + 'invalid_options', + `Invalid "referenceListingIds" calendar code "${calendarCode}": expected a non-empty trimmed string.` + ); + } + + if (!Array.isArray(rawIds) || rawIds.length === 0) { + throw new BarSessionDatesError( + 'invalid_options', + `Invalid "referenceListingIds.${calendarCode}": expected a non-empty array of positive 32-bit integer listing IDs.` + ); + } + + const copiedIds: number[] = []; + const idSet = new Set(); + + for (let j = 0; j < rawIds.length; j += 1) { + const id: unknown = rawIds[j]; + if (!isValidInt32(id) || id <= 0) { + throw new BarSessionDatesError( + 'invalid_options', + `Invalid "referenceListingIds.${calendarCode}[${j}]": expected a positive 32-bit integer, got ${String(id)}.` + ); + } + if (idSet.has(id)) { + throw new BarSessionDatesError( + 'invalid_options', + `Duplicate listing ID ${id} in "referenceListingIds.${calendarCode}".` + ); + } + idSet.add(id); + copiedIds.push(id); + } + + calendars.set(calendarCode, { + listingIds: copiedIds, + listingIdSet: idSet, + }); + } + + return { store, calendars }; +} + +/** + * Creates a {@link SessionDatesPort} backed by Vault-fenced daily bars + * (`timeframe: '1d'`, `adjustment: 'raw'`) for caller-configured reference + * listings per `exchange.calendar_code`. + */ +export function createBarSessionDatesPort( + options: BarSessionDatesPortOptions +): SessionDatesPort { + const { store, calendars } = validateOptions(options); + + return { + async listSessionDates(query: SessionDatesQuery): Promise { + if (!isPlainRecord(query)) { + throw new BarSessionDatesError( + 'invalid_query', + 'Invalid query: expected an object with calendarCode, fromDate, and toDate.' + ); + } + + if (typeof query.calendarCode !== 'string') { + throw new BarSessionDatesError( + 'invalid_query', + 'Invalid "calendarCode": expected a string.' + ); + } + + const config = calendars.get(query.calendarCode); + if (config === undefined) { + throw new BarSessionDatesError( + 'unknown_calendar', + `No reference listings configured for calendarCode "${query.calendarCode}".` + ); + } + + const fromDayKey = parseQueryDayKey(query.fromDate, 'fromDate'); + const toDayKey = parseQueryDayKey(query.toDate, 'toDate'); + if (fromDayKey > toDayKey) { + throw new BarSessionDatesError( + 'invalid_query', + `Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".` + ); + } + + const dayKeys = new Set(); + const stream = store.bars({ + listingIds: config.listingIds.slice(), + timeframe: '1d', + from: query.fromDate, + to: query.toDate, + adjustment: 'raw', + }); + + for await (const batch of stream) { + if (!isPlainRecord(batch) || !Array.isArray(batch.rows)) { + throw new BarSessionDatesError( + 'invalid_bar', + 'Invalid bar batch: expected an object with a rows array.' + ); + } + + const rows = batch.rows; + for (let i = 0; i < rows.length; i += 1) { + const bar: unknown = rows[i]; + if (!isPlainRecord(bar)) { + throw new BarSessionDatesError( + 'invalid_bar', + `Invalid bar row at index ${i}: expected a plain object.` + ); + } + + if (!isValidEpochMs(bar.ts)) { + throw new BarSessionDatesError( + 'invalid_bar', + `Invalid bar timestamp at index ${i}: expected a finite integer epoch ms, got ${String(bar.ts)}.` + ); + } + + if (!isValidInt32(bar.listingId) || !config.listingIdSet.has(bar.listingId)) { + throw new BarSessionDatesError( + 'invalid_bar', + `Unexpected bar listingId ${String(bar.listingId)} for calendarCode "${query.calendarCode}".` + ); + } + + const dayKey = Math.floor(bar.ts / MS_PER_DAY); + if (dayKey >= fromDayKey && dayKey <= toDayKey) { + dayKeys.add(dayKey); + } + } + } + + if (dayKeys.size === 0) { + return []; + } + + const sortedDayKeys = Array.from(dayKeys).sort((a, b) => a - b); + return sortedDayKeys.map(formatDayKeyUtc); + }, + }; +} diff --git a/libs/research/src/mcp/adapters/postgres-copilot.ts b/libs/research/src/mcp/adapters/postgres-copilot.ts new file mode 100644 index 00000000..ca571894 --- /dev/null +++ b/libs/research/src/mcp/adapters/postgres-copilot.ts @@ -0,0 +1,173 @@ +/** + * PostgreSQL composition root for the MCP research copilot server. + * + * Wires a single injected {@link PostgresResearchCopilotExecutor} into all + * PostgreSQL-backed MCP adapters (`search_symbols`, `file_finding`, + * `read_knowledge`, `event_study` listing calendars, and `trial_ledger`) with + * one authoritative Vault cutoff (`vaultContext.vaultCutoffTs`). + * + * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution, + * market data store, library-card reader, session-date port, ID generator, and + * clock are all injected by the caller. + */ + +import { + type ResearchCopilotMcpServerOptions, + createResearchCopilotMcpServer, +} from '../copilot-server'; +import type { McpServer } from '../server'; +import type { KnowledgePort } from '../tools/read-knowledge'; +import { + type EarlyCloseOverrides, + type SessionDatesPort, + createExchangeCalendarResolver, + createPostgresListingCalendarPort, +} from './exchange-calendars'; +import { + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, +} from './postgres-findings'; +import { createPostgresSymbolSearchPort } from './postgres-symbol-search'; +import { createPostgresTrialRefPort } from './postgres-trial-ref'; + +/** + * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface shared by + * all PostgreSQL-backed MCP copilot adapters and `trial_ledger`. + * + * Assignable without casts to `SymbolSearchExecutor`, `TrialRefExecutor`, + * `PostgresFindingsExecutor`, `ListingCalendarExecutor`, and + * `TrialLedgerExecutor`. + */ +export interface PostgresResearchCopilotExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** + * Composition options for {@link createPostgresResearchCopilotServer}. + * + * Uses `vaultContext.vaultCutoffTs` as the single authoritative Vault cutoff + * across all Vault-fenced tools and `trial_ledger` visibility lookups. + */ +export interface PostgresResearchCopilotServerOptions + extends Pick< + ResearchCopilotMcpServerOptions, + 'name' | 'version' | 'store' | 'vaultContext' | 'principalId' + > { + readonly executor: PostgresResearchCopilotExecutor; + /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ + readonly schema?: string; + readonly listLibraryCards: KnowledgePort['listLibraryCards']; + readonly sessionDates: SessionDatesPort; + readonly earlyCloses?: EarlyCloseOverrides; + readonly newId: () => string; + readonly now: () => Date | number; +} + +function validateOptions(options: PostgresResearchCopilotServerOptions): void { + if (typeof options !== 'object' || options === null) { + throw new Error( + 'Invalid `options`: expected a PostgresResearchCopilotServerOptions object.' + ); + } + if ( + typeof options.executor !== 'object' || + options.executor === null || + typeof options.executor.query !== 'function' + ) { + throw new Error( + 'Invalid `executor`: expected an object with a callable query(text, params?) method.' + ); + } + if (typeof options.vaultContext !== 'object' || options.vaultContext === null) { + throw new Error('Invalid `vaultContext`: expected a VaultFenceContext object.'); + } + if (typeof options.listLibraryCards !== 'function') { + throw new Error('Invalid `listLibraryCards`: expected a callable function.'); + } + if ( + typeof options.sessionDates !== 'object' || + options.sessionDates === null || + typeof options.sessionDates.listSessionDates !== 'function' + ) { + throw new Error( + 'Invalid `sessionDates`: expected an object with a callable listSessionDates(query) method.' + ); + } + if (typeof options.newId !== 'function') { + throw new Error('Invalid `newId`: expected a callable function.'); + } + if (typeof options.now !== 'function') { + throw new Error('Invalid `now`: expected a callable function.'); + } +} + +/** + * Composes all six research copilot MCP tools into a single {@link McpServer} + * backed by one shared PostgreSQL executor and one authoritative Vault cutoff. + * + * Schema-aware adapters (`search_symbols`, `trial_ledger` visibility lookup, + * `findings`, `provider_caveats`, and listing-to-exchange calendars) qualify + * their tables with `options.schema` when supplied; `trial_ledger` writes and + * cluster DSR reads resolve through the executor's `search_path`. + */ +export function createPostgresResearchCopilotServer( + options: PostgresResearchCopilotServerOptions +): McpServer { + validateOptions(options); + + const pgAdapterOptions = + options.schema === undefined + ? { executor: options.executor } + : { executor: options.executor, schema: options.schema }; + + const symbolSearchPort = createPostgresSymbolSearchPort(pgAdapterOptions); + const trialRefPort = createPostgresTrialRefPort({ + ...pgAdapterOptions, + vaultCutoffTs: options.vaultContext.vaultCutoffTs, + }); + const findingWritePort = createPostgresFindingWritePort(pgAdapterOptions); + const knowledgeReaders = createPostgresKnowledgeReaders(pgAdapterOptions); + const listingCalendars = createPostgresListingCalendarPort(pgAdapterOptions); + + const resolveExchangeCalendars = createExchangeCalendarResolver( + options.earlyCloses === undefined + ? { listingCalendars, sessionDates: options.sessionDates } + : { + listingCalendars, + sessionDates: options.sessionDates, + earlyCloses: options.earlyCloses, + } + ); + + const knowledgePort: KnowledgePort = { + listLibraryCards: options.listLibraryCards, + ...knowledgeReaders, + }; + + return createResearchCopilotMcpServer({ + name: options.name, + version: options.version, + store: options.store, + vaultContext: options.vaultContext, + ledger: options.executor, + principalId: options.principalId, + searchSymbols: { + port: symbolSearchPort, + }, + eventStudy: { + resolveExchangeCalendars, + }, + fileFinding: { + port: findingWritePort, + trialLookup: trialRefPort, + newId: options.newId, + now: options.now, + }, + readKnowledge: { + port: knowledgePort, + }, + }); +} diff --git a/libs/research/src/mcp/host/stdio-host.ts b/libs/research/src/mcp/host/stdio-host.ts new file mode 100644 index 00000000..b7ff3c3a --- /dev/null +++ b/libs/research/src/mcp/host/stdio-host.ts @@ -0,0 +1,835 @@ +/** + * Dependency-free stdio host composition for the MCP research copilot. + * + * Parses `RESEARCH_MCP_*` environment variables into a strict typed + * {@link ResearchCopilotHostConfig} and composes injected PostgreSQL executor, + * market data store, and library-card reader factories with + * {@link createBarSessionDatesPort}, {@link createPostgresResearchCopilotServer}, + * and {@link runStdioServer}. + * + * Pure and dependency-free: zero `node:*` imports, zero bare `process` access, + * no `pg` dependency, and no DuckDB driver import. + */ + +import { z } from 'zod'; +import type { MarketDataStore } from '../../market-data-store'; +import { + MAX_ECMASCRIPT_EPOCH_MS, + isValidInt32, + parseCalendarDayKey, +} from '../../panel-shared'; +import { + type BarSessionDatesPortOptions, + createBarSessionDatesPort, +} from '../adapters/bar-session-dates'; +import { + EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET, + EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE, + EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET, + EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE, + type EarlyCloseOverrides, +} from '../adapters/exchange-calendars'; +import { + type PostgresResearchCopilotExecutor, + createPostgresResearchCopilotServer, +} from '../adapters/postgres-copilot'; +import type { McpServer } from '../server'; +import { type StdioServerOptions, runStdioServer } from '../stdio'; +import type { KnowledgePort } from '../tools/read-knowledge'; + +/** Environment variable prefix owned by {@link parseResearchCopilotHostConfig}. */ +export const RESEARCH_MCP_ENV_PREFIX = 'RESEARCH_MCP_'; + +/** Headless MCP server name announced during `initialize`. */ +export const RESEARCH_COPILOT_HOST_NAME = 'stock-bot-research-copilot'; + +/** Headless MCP server version announced during `initialize`. */ +export const RESEARCH_COPILOT_HOST_VERSION = '0.1.0'; + +const ENV_POSTGRES_URL = 'RESEARCH_MCP_POSTGRES_URL'; +const ENV_POSTGRES_SCHEMA = 'RESEARCH_MCP_POSTGRES_SCHEMA'; +const ENV_CURATED_ROOT = 'RESEARCH_MCP_CURATED_ROOT'; +const ENV_VAULT_CUTOFF_TS = 'RESEARCH_MCP_VAULT_CUTOFF_TS'; +const ENV_PRINCIPAL_ID = 'RESEARCH_MCP_PRINCIPAL_ID'; +const ENV_LIBRARY_ROOT = 'RESEARCH_MCP_LIBRARY_ROOT'; +const ENV_SESSION_REFERENCE_LISTINGS = 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS'; +const ENV_EARLY_CLOSES = 'RESEARCH_MCP_EARLY_CLOSES'; + +const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; +const AGENT_PRINCIPAL_RE = + /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +const STRICT_UTC_INSTANT_RE = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/; + +const nonBlankEnvString = z.string().refine(value => value.trim().length > 0, { + message: 'blank', +}); + +const rawHostEnvSchema = z + .object({ + [ENV_POSTGRES_URL]: nonBlankEnvString, + [ENV_POSTGRES_SCHEMA]: nonBlankEnvString.optional(), + [ENV_CURATED_ROOT]: nonBlankEnvString, + [ENV_VAULT_CUTOFF_TS]: nonBlankEnvString, + [ENV_PRINCIPAL_ID]: nonBlankEnvString, + [ENV_LIBRARY_ROOT]: nonBlankEnvString, + [ENV_SESSION_REFERENCE_LISTINGS]: nonBlankEnvString, + [ENV_EARLY_CLOSES]: nonBlankEnvString.optional(), + }) + .strict(); + +/** Validated configuration parsed from `RESEARCH_MCP_*` environment variables. */ +export interface ResearchCopilotHostConfig { + readonly postgresUrl: string; + readonly postgresSchema?: string; + readonly curatedRoot: string; + readonly vaultCutoffTs: number; + readonly principalId: string; + readonly libraryRoot: string; + readonly referenceListingIds: BarSessionDatesPortOptions['referenceListingIds']; + readonly earlyCloses?: EarlyCloseOverrides; +} + +/** + * Typed configuration error thrown by {@link parseResearchCopilotHostConfig}. + * + * Always names the offending `RESEARCH_MCP_*` variable with a fixed reason and + * never embeds raw environment values, DSNs, JSON parser output, or Zod dumps. + */ +export class ResearchCopilotHostConfigError extends RangeError { + readonly variable: string; + + constructor(variable: string, message: string) { + super(message); + this.name = 'ResearchCopilotHostConfigError'; + this.variable = variable; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Managed PostgreSQL executor handle returned by `deps.openExecutor`. */ +export interface ManagedPostgresExecutor { + readonly executor: PostgresResearchCopilotExecutor; + close(): Promise | void; +} + +/** Managed market data store handle returned by `deps.openStore`. */ +export interface ManagedMarketDataStore { + readonly store: MarketDataStore; + close(): Promise | void; +} + +/** Library-card reader handle returned by `deps.createLibraryCardReader`. */ +export interface LibraryCardReaderHandle { + readonly listLibraryCards: KnowledgePort['listLibraryCards']; +} + +/** Injected dependencies for {@link runResearchCopilotStdioHost}. */ +export interface ResearchCopilotStdioHostDeps { + readonly config: ResearchCopilotHostConfig; + readonly openExecutor: ( + config: ResearchCopilotHostConfig + ) => Promise | ManagedPostgresExecutor; + readonly openStore: ( + config: ResearchCopilotHostConfig + ) => Promise | ManagedMarketDataStore; + readonly createLibraryCardReader: ( + config: ResearchCopilotHostConfig + ) => Promise | LibraryCardReaderHandle; + readonly newId: () => string; + readonly now: () => Date | number; + readonly stdio?: StdioServerOptions; +} + +type HostStage = + | 'executor_open' + | 'store_open' + | 'library_reader' + | 'server_init' + | 'stdio_serve' + | 'cleanup'; + +const STAGE_ERROR_MESSAGES: Readonly> = { + executor_open: 'Research copilot stdio host failed while opening the PostgreSQL executor.', + store_open: 'Research copilot stdio host failed while opening the market data store.', + library_reader: 'Research copilot stdio host failed while creating the library card reader.', + server_init: 'Research copilot stdio host failed while initializing the MCP server.', + stdio_serve: 'Research copilot stdio host failed while serving MCP stdio.', + cleanup: 'Research copilot stdio host failed while closing host resources.', +}; + +function isPlainObjectRecord(value: unknown): value is Record { + if (typeof value !== 'object' || value === null) { + return false; + } + const proto: unknown = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +function defineDataProperty(target: Record, key: string, value: T): void { + Object.defineProperty(target, key, { + value, + enumerable: true, + writable: true, + configurable: true, + }); +} + +function parsePostgresUrl(raw: string): string { + if (raw !== raw.trim()) { + throw new ResearchCopilotHostConfigError( + ENV_POSTGRES_URL, + `Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.` + ); + } + let parsed: URL; + try { + parsed = new URL(raw); + } catch { + throw new ResearchCopilotHostConfigError( + ENV_POSTGRES_URL, + `Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL.` + ); + } + if ( + (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') || + parsed.hostname.length === 0 + ) { + throw new ResearchCopilotHostConfigError( + ENV_POSTGRES_URL, + `Invalid configuration variable "${ENV_POSTGRES_URL}": expected a postgres:// or postgresql:// URL with a non-empty host.` + ); + } + try { + if (parsed.username.length > 0) { + decodeURIComponent(parsed.username); + } + if (parsed.password.length > 0) { + decodeURIComponent(parsed.password); + } + } catch { + throw new ResearchCopilotHostConfigError( + ENV_POSTGRES_URL, + `Invalid configuration variable "${ENV_POSTGRES_URL}": URL credentials contain invalid percent-encoding.` + ); + } + return raw; +} + +function parsePostgresSchema(raw: string): string { + if (!SCHEMA_IDENT_RE.test(raw)) { + throw new ResearchCopilotHostConfigError( + ENV_POSTGRES_SCHEMA, + `Invalid configuration variable "${ENV_POSTGRES_SCHEMA}": expected a PostgreSQL identifier matching ^[a-z_][a-z0-9_]*$.` + ); + } + return raw; +} + +function parsePrincipalId(raw: string): string { + if (raw !== 'operator' && !AGENT_PRINCIPAL_RE.test(raw)) { + throw new ResearchCopilotHostConfigError( + ENV_PRINCIPAL_ID, + `Invalid configuration variable "${ENV_PRINCIPAL_ID}": expected "operator" or "agent:".` + ); + } + return raw; +} + +function parseVaultCutoffTs(raw: string): number { + const match = STRICT_UTC_INSTANT_RE.exec(raw); + if (match === null) { + throw new ResearchCopilotHostConfigError( + ENV_VAULT_CUTOFF_TS, + `Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": expected a strict ISO-8601 UTC instant ending in Z.` + ); + } + + 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 fracRaw = match[7]; + const millis = fracRaw === undefined ? 0 : Number(fracRaw.padEnd(3, '0')); + + if ( + month < 1 || + month > 12 || + day < 1 || + day > 31 || + hour > 23 || + minute > 59 || + second > 59 + ) { + throw new ResearchCopilotHostConfigError( + ENV_VAULT_CUTOFF_TS, + `Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is not a valid UTC calendar instant.` + ); + } + + const epochMs = Date.UTC(year, month - 1, day, hour, minute, second, millis); + if (!Number.isSafeInteger(epochMs) || Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS) { + throw new ResearchCopilotHostConfigError( + ENV_VAULT_CUTOFF_TS, + `Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is out of supported epoch range.` + ); + } + + const check = new Date(epochMs); + if ( + check.getUTCFullYear() !== year || + check.getUTCMonth() !== month - 1 || + check.getUTCDate() !== day || + check.getUTCHours() !== hour || + check.getUTCMinutes() !== minute || + check.getUTCSeconds() !== second || + check.getUTCMilliseconds() !== millis + ) { + throw new ResearchCopilotHostConfigError( + ENV_VAULT_CUTOFF_TS, + `Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is not a valid UTC calendar instant.` + ); + } + + return epochMs; +} + +function parseReferenceListingIds( + raw: string +): BarSessionDatesPortOptions['referenceListingIds'] { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new ResearchCopilotHostConfigError( + ENV_SESSION_REFERENCE_LISTINGS, + `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": expected valid JSON.` + ); + } + + if (!isPlainObjectRecord(parsed)) { + throw new ResearchCopilotHostConfigError( + ENV_SESSION_REFERENCE_LISTINGS, + `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": expected a JSON object mapping calendar codes to listing ID arrays.` + ); + } + + const result: Record = {}; + const entries = Object.entries(parsed); + + for (let i = 0; i < entries.length; i += 1) { + const [calendarCode, rawIds] = entries[i] as [string, unknown]; + if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) { + throw new ResearchCopilotHostConfigError( + ENV_SESSION_REFERENCE_LISTINGS, + `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": calendar codes must be non-empty trimmed strings.` + ); + } + + if (!Array.isArray(rawIds) || rawIds.length === 0) { + throw new ResearchCopilotHostConfigError( + ENV_SESSION_REFERENCE_LISTINGS, + `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": each calendar must map to a non-empty array of positive INT32 listing IDs.` + ); + } + + const copiedIds: number[] = []; + const seen = new Set(); + + for (let j = 0; j < rawIds.length; j += 1) { + const id: unknown = rawIds[j]; + if (!isValidInt32(id) || id <= 0) { + throw new ResearchCopilotHostConfigError( + ENV_SESSION_REFERENCE_LISTINGS, + `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": listing IDs must be positive 32-bit integers.` + ); + } + if (seen.has(id)) { + throw new ResearchCopilotHostConfigError( + ENV_SESSION_REFERENCE_LISTINGS, + `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": listing IDs within a calendar must be distinct.` + ); + } + seen.add(id); + copiedIds.push(id); + } + + defineDataProperty(result, calendarCode, copiedIds); + } + + return result; +} + +function parseEarlyClosesEnv(raw: string): EarlyCloseOverrides { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new ResearchCopilotHostConfigError( + ENV_EARLY_CLOSES, + `Invalid configuration variable "${ENV_EARLY_CLOSES}": expected valid JSON.` + ); + } + + if (!isPlainObjectRecord(parsed)) { + throw new ResearchCopilotHostConfigError( + ENV_EARLY_CLOSES, + `Invalid configuration variable "${ENV_EARLY_CLOSES}": expected a JSON object mapping calendar codes to date/minute overrides.` + ); + } + + const result: Record>> = {}; + const calendarEntries = Object.entries(parsed); + + for (let i = 0; i < calendarEntries.length; i += 1) { + const [calendarCode, rawDates] = calendarEntries[i] as [string, unknown]; + if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) { + throw new ResearchCopilotHostConfigError( + ENV_EARLY_CLOSES, + `Invalid configuration variable "${ENV_EARLY_CLOSES}": calendar codes must be non-empty trimmed strings.` + ); + } + + if (!isPlainObjectRecord(rawDates)) { + throw new ResearchCopilotHostConfigError( + ENV_EARLY_CLOSES, + `Invalid configuration variable "${ENV_EARLY_CLOSES}": each calendar must map to an object of YYYY-MM-DD dates and Eastern close minutes.` + ); + } + + const dates: Record = {}; + const dateEntries = Object.entries(rawDates); + + for (let j = 0; j < dateEntries.length; j += 1) { + const [dateStr, minute] = dateEntries[j] as [string, unknown]; + parseCalendarDayKey(dateStr, ENV_EARLY_CLOSES, () => + new ResearchCopilotHostConfigError( + ENV_EARLY_CLOSES, + `Invalid configuration variable "${ENV_EARLY_CLOSES}": override dates must be valid YYYY-MM-DD calendar dates.` + ) + ); + + if ( + dateStr < EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE || + dateStr > EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE + ) { + throw new ResearchCopilotHostConfigError( + ENV_EARLY_CLOSES, + `Invalid configuration variable "${ENV_EARLY_CLOSES}": override dates must fall within ${EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE}..=${EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE}.` + ); + } + + if ( + typeof minute !== 'number' || + !Number.isSafeInteger(minute) || + minute < EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET || + minute > EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET + ) { + throw new ResearchCopilotHostConfigError( + ENV_EARLY_CLOSES, + `Invalid configuration variable "${ENV_EARLY_CLOSES}": close minutes must be integers from ${EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET} through ${EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET}.` + ); + } + + defineDataProperty(dates, dateStr, minute); + } + + defineDataProperty(result, calendarCode, dates); + } + + return result; +} + +/** + * Purely parses and validates `RESEARCH_MCP_*` environment variables into a + * typed {@link ResearchCopilotHostConfig}. + * + * Unrelated environment keys are ignored. Unknown `RESEARCH_MCP_*` keys, + * missing required variables, blank values, and malformed fields fail closed + * with {@link ResearchCopilotHostConfigError} naming the variable without + * exposing raw values or credentials. + */ +export function parseResearchCopilotHostConfig( + env: Readonly> +): ResearchCopilotHostConfig { + if (typeof env !== 'object' || env === null) { + throw new ResearchCopilotHostConfigError( + RESEARCH_MCP_ENV_PREFIX, + 'Invalid environment object: expected a key-value record.' + ); + } + + const scopedEnv: Record = {}; + const entries = Object.entries(env); + for (let i = 0; i < entries.length; i += 1) { + const [key, value] = entries[i] as [string, unknown]; + if (key.startsWith(RESEARCH_MCP_ENV_PREFIX) && value !== undefined) { + defineDataProperty(scopedEnv, key, value); + } + } + + const parsedEnv = rawHostEnvSchema.safeParse(scopedEnv); + if (!parsedEnv.success) { + const firstIssue = parsedEnv.error.issues[0]; + if (firstIssue !== undefined) { + if (firstIssue.code === 'unrecognized_keys') { + const unknownKey = firstIssue.keys[0] ?? RESEARCH_MCP_ENV_PREFIX; + throw new ResearchCopilotHostConfigError( + unknownKey, + `Unknown configuration variable "${unknownKey}".` + ); + } + + const variable = + typeof firstIssue.path[0] === 'string' ? firstIssue.path[0] : RESEARCH_MCP_ENV_PREFIX; + + if (firstIssue.code === 'invalid_type' && firstIssue.received === 'undefined') { + throw new ResearchCopilotHostConfigError( + variable, + `Missing required configuration variable "${variable}".` + ); + } + + if (firstIssue.code === 'custom') { + throw new ResearchCopilotHostConfigError( + variable, + `Invalid configuration variable "${variable}": value must not be empty or whitespace.` + ); + } + + throw new ResearchCopilotHostConfigError( + variable, + `Invalid configuration variable "${variable}": expected a non-empty string.` + ); + } + + throw new ResearchCopilotHostConfigError( + RESEARCH_MCP_ENV_PREFIX, + 'Invalid research copilot host configuration.' + ); + } + + const data = parsedEnv.data; + const postgresUrl = parsePostgresUrl(data[ENV_POSTGRES_URL]); + const postgresSchema = + data[ENV_POSTGRES_SCHEMA] !== undefined + ? parsePostgresSchema(data[ENV_POSTGRES_SCHEMA]) + : undefined; + const curatedRoot = data[ENV_CURATED_ROOT].trim(); + const vaultCutoffTs = parseVaultCutoffTs(data[ENV_VAULT_CUTOFF_TS]); + const principalId = parsePrincipalId(data[ENV_PRINCIPAL_ID]); + const libraryRoot = data[ENV_LIBRARY_ROOT].trim(); + const referenceListingIds = parseReferenceListingIds(data[ENV_SESSION_REFERENCE_LISTINGS]); + const earlyCloses = + data[ENV_EARLY_CLOSES] !== undefined + ? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES]) + : undefined; + + return { + postgresUrl, + ...(postgresSchema !== undefined ? { postgresSchema } : {}), + curatedRoot, + vaultCutoffTs, + principalId, + libraryRoot, + referenceListingIds, + ...(earlyCloses !== undefined ? { earlyCloses } : {}), + }; +} + +function addRawAndDecodedNeedle(needles: Set, raw: string): void { + if (raw.length === 0) { + return; + } + needles.add(raw); + try { + const decoded = decodeURIComponent(raw); + if (decoded.length > 0) { + needles.add(decoded); + } + } catch { + // Malformed percent-encoding: raw needle is already registered. + } +} + +function collectSecretNeedles(postgresUrl: string): readonly string[] { + const needles = new Set(); + if (postgresUrl.length > 0) { + needles.add(postgresUrl); + } + try { + const parsed = new URL(postgresUrl); + if (parsed.href.length > 0) { + needles.add(parsed.href); + } + addRawAndDecodedNeedle(needles, parsed.password); + for (const [key, value] of parsed.searchParams.entries()) { + if (key.toLowerCase() === 'password' && value.length > 0) { + needles.add(value); + } + } + if (parsed.search.length > 1) { + const pairs = parsed.search.slice(1).split('&'); + for (let i = 0; i < pairs.length; i += 1) { + const pair = pairs[i] as string; + const eqIdx = pair.indexOf('='); + if (eqIdx <= 0) { + continue; + } + const rawKey = pair.slice(0, eqIdx); + let decodedKey = rawKey; + try { + decodedKey = decodeURIComponent(rawKey); + } catch { + // Keep rawKey if percent-decoding fails. + } + if (decodedKey.toLowerCase() === 'password') { + addRawAndDecodedNeedle(needles, pair.slice(eqIdx + 1)); + } + } + } + } catch { + // Non-URL postgresUrl passed directly to runResearchCopilotStdioHost: raw string is covered. + } + return Array.from(needles); +} + +function containsAnyNeedle(text: string, needles: readonly string[]): boolean { + for (let i = 0; i < needles.length; i += 1) { + if (text.includes(needles[i] as string)) { + return true; + } + } + return false; +} + +function isErrorSafeToSurface( + error: unknown, + needles: readonly string[], + visited: Set = new Set(), + depth = 0 +): error is Error { + if (!(error instanceof Error) || depth > 8) { + return false; + } + if (visited.has(error)) { + return true; + } + visited.add(error); + + try { + const message = error.message; + if (typeof message !== 'string' || containsAnyNeedle(message, needles)) { + return false; + } + const stack = error.stack; + if (typeof stack === 'string' && containsAnyNeedle(stack, needles)) { + return false; + } + const cause = (error as { readonly cause?: unknown }).cause; + if (cause !== undefined && !isErrorSafeToSurface(cause, needles, visited, depth + 1)) { + return false; + } + if (error instanceof AggregateError || 'errors' in error) { + const nested = (error as { readonly errors?: unknown }).errors; + if (nested !== undefined) { + if (!Array.isArray(nested)) { + return false; + } + for (let i = 0; i < nested.length; i += 1) { + if (!isErrorSafeToSurface(nested[i], needles, visited, depth + 1)) { + return false; + } + } + } + } + return true; + } catch { + return false; + } +} + +function sanitizeHostError( + error: unknown, + stage: HostStage, + needles: readonly string[] +): Error { + if (isErrorSafeToSurface(error, needles)) { + return error; + } + return new Error(STAGE_ERROR_MESSAGES[stage]); +} + +function validateHostDeps(deps: ResearchCopilotStdioHostDeps): void { + if (typeof deps !== 'object' || deps === null) { + throw new Error('Invalid `deps`: expected a ResearchCopilotStdioHostDeps object.'); + } + if (typeof deps.config !== 'object' || deps.config === null) { + throw new Error('Invalid `deps.config`: expected a ResearchCopilotHostConfig object.'); + } + if (typeof deps.openExecutor !== 'function') { + throw new Error('Invalid `deps.openExecutor`: expected a callable factory function.'); + } + if (typeof deps.openStore !== 'function') { + throw new Error('Invalid `deps.openStore`: expected a callable factory function.'); + } + if (typeof deps.createLibraryCardReader !== 'function') { + throw new Error( + 'Invalid `deps.createLibraryCardReader`: expected a callable factory function.' + ); + } + if (typeof deps.newId !== 'function') { + throw new Error('Invalid `deps.newId`: expected a callable ID generator function.'); + } + if (typeof deps.now !== 'function') { + throw new Error('Invalid `deps.now`: expected a callable clock function.'); + } +} + +/** + * Composes and runs the headless MCP research copilot over stdio using + * caller-injected resource factories. + * + * - Acquires resources sequentially (`openExecutor` -> `openStore` -> + * `createLibraryCardReader`) before serving any stdio input. + * - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff; the + * caller's `openStore` factory must configure the store with that same cutoff. + * - Always closes every acquired resource exactly once in reverse acquisition + * order on EOF or error, preserving the primary failure when safe and + * replacing credential-bearing or uninspectable errors with a fixed + * stage-specific error without a raw `cause`. + */ +export async function runResearchCopilotStdioHost( + deps: ResearchCopilotStdioHostDeps +): Promise { + validateHostDeps(deps); + + const { config } = deps; + const secretNeedles = collectSecretNeedles( + typeof config.postgresUrl === 'string' ? config.postgresUrl : '' + ); + + const closers: Array<() => Promise | void> = []; + let primaryError: { readonly error: unknown; readonly stage: HostStage } | null = null; + + try { + let executorHandle: ManagedPostgresExecutor; + try { + executorHandle = await deps.openExecutor(config); + } catch (error) { + primaryError = { error, stage: 'executor_open' }; + throw error; + } + + if ( + typeof executorHandle !== 'object' || + executorHandle === null || + typeof executorHandle.close !== 'function' + ) { + const error = new Error( + 'Invalid executor handle: expected an object with executor and close().' + ); + primaryError = { error, stage: 'executor_open' }; + throw error; + } + closers.push(() => executorHandle.close()); + + let storeHandle: ManagedMarketDataStore; + try { + storeHandle = await deps.openStore(config); + } catch (error) { + primaryError = { error, stage: 'store_open' }; + throw error; + } + + if ( + typeof storeHandle !== 'object' || + storeHandle === null || + typeof storeHandle.close !== 'function' + ) { + const error = new Error( + 'Invalid store handle: expected an object with store and close().' + ); + primaryError = { error, stage: 'store_open' }; + throw error; + } + closers.push(() => storeHandle.close()); + + let libraryReader: LibraryCardReaderHandle; + try { + libraryReader = await deps.createLibraryCardReader(config); + } catch (error) { + primaryError = { error, stage: 'library_reader' }; + throw error; + } + + if ( + typeof libraryReader !== 'object' || + libraryReader === null || + typeof libraryReader.listLibraryCards !== 'function' + ) { + const error = new Error( + 'Invalid library card reader: expected an object with listLibraryCards().' + ); + primaryError = { error, stage: 'library_reader' }; + throw error; + } + + let server: McpServer; + try { + const sessionDates = createBarSessionDatesPort({ + store: storeHandle.store, + referenceListingIds: config.referenceListingIds, + }); + + server = createPostgresResearchCopilotServer({ + name: RESEARCH_COPILOT_HOST_NAME, + version: RESEARCH_COPILOT_HOST_VERSION, + executor: executorHandle.executor, + ...(config.postgresSchema !== undefined ? { schema: config.postgresSchema } : {}), + store: storeHandle.store, + vaultContext: { vaultCutoffTs: config.vaultCutoffTs }, + principalId: config.principalId, + listLibraryCards: query => libraryReader.listLibraryCards(query), + sessionDates, + ...(config.earlyCloses !== undefined ? { earlyCloses: config.earlyCloses } : {}), + newId: deps.newId, + now: deps.now, + }); + } catch (error) { + primaryError = { error, stage: 'server_init' }; + throw error; + } + + try { + await runStdioServer(server, deps.stdio); + } catch (error) { + primaryError = { error, stage: 'stdio_serve' }; + throw error; + } + } catch (error) { + if (primaryError === null) { + primaryError = { error, stage: 'server_init' }; + } + } + + let firstCloseError: { readonly error: unknown } | null = null; + for (let i = closers.length - 1; i >= 0; i -= 1) { + try { + await closers[i]?.(); + } catch (closeErr) { + if (firstCloseError === null) { + firstCloseError = { error: closeErr }; + } + } + } + + if (primaryError !== null) { + throw sanitizeHostError(primaryError.error, primaryError.stage, secretNeedles); + } + if (firstCloseError !== null) { + throw sanitizeHostError(firstCloseError.error, 'cleanup', secretNeedles); + } +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 910af37e..9ffe9a0a 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -13,3 +13,6 @@ export * from './tools/file-finding'; export * from './tools/query-data'; export * from './tools/read-knowledge'; export * from './tools/search-symbols'; +export * from './adapters/postgres-copilot'; +export * from './adapters/bar-session-dates'; +export * from './host/stdio-host'; diff --git a/libs/research/src/notebook-snapshot.ts b/libs/research/src/notebook-snapshot.ts new file mode 100644 index 00000000..f6af2521 --- /dev/null +++ b/libs/research/src/notebook-snapshot.ts @@ -0,0 +1,804 @@ +/** + * `marimo check`-gated static HTML snapshot exporter for research notebooks. + * + * Enforces the D9 rule (`design/PLATFORM-PLAN.md`): a notebook must pass + * `marimo check --format=json` with zero errors before `marimo export html` + * runs, and exported HTML is published atomically via a sibling temp file. + * + * All subprocess execution and filesystem access are injected via ports + * (`NotebookCommandRunner`, `NotebookSnapshotFs`). `node:crypto` is loaded + * lazily at call time so `@stock-bot/research` remains browser-bundleable. + * + * Command flags and JSON diagnostic shape are confirmed against marimo 0.26.0 + * (pinned in `python/uv.lock`). + */ + +export const DEFAULT_MARIMO_COMMAND = 'marimo'; +export const DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS = 120_000; + +const MAX_TEMP_RESERVATION_ATTEMPTS = 16; +let tempSequence = 0; + +/** Stable machine-readable error codes thrown by {@link NotebookSnapshotError}. */ +export type NotebookSnapshotErrorCode = + | 'INVALID_OPTION' + | 'INVALID_PATH' + | 'NOTEBOOK_NOT_FOUND' + | 'CHECK_FAILED' + | 'CHECK_OUTPUT_INVALID' + | 'EXPORT_FAILED' + | 'EXPORT_EMPTY' + | 'TIMEOUT'; + +export interface NotebookSnapshotErrorOptions { + readonly details?: unknown; + readonly cause?: unknown; +} + +/** Typed fail-closed error thrown by {@link exportNotebookSnapshot}. */ +export class NotebookSnapshotError extends Error { + readonly code: NotebookSnapshotErrorCode; + readonly details?: unknown; + override readonly cause?: unknown; + + constructor( + code: NotebookSnapshotErrorCode, + message: string, + options?: NotebookSnapshotErrorOptions + ) { + super(message); + this.name = 'NotebookSnapshotError'; + this.code = code; + if (options && 'details' in options) { + this.details = options.details; + } + if (options && 'cause' in options) { + this.cause = options.cause; + } + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export interface NotebookCommandRunOptions { + readonly cwd?: string; + readonly timeoutMs: number; +} + +export interface NotebookCommandResult { + readonly exitCode: number; + readonly stdout: string; + readonly stderr: string; +} + +/** + * Injected command-runner port. + * + * Implementations MUST execute `command` directly with `args` as an argv array + * (never via a shell string or shell interpolation). + * + * Timeout contract: on timeout, implementations MUST terminate the subprocess + * and settle (rejecting with an error carrying `code: 'ETIMEDOUT'`) only after + * the process has exited and stopped writing to disk. + */ +export interface NotebookCommandRunner { + run( + command: string, + args: readonly string[], + options: NotebookCommandRunOptions + ): Promise; +} + +export interface NotebookSnapshotFileStat { + readonly isFile: boolean; + readonly size: number; +} + +/** + * Minimal injected filesystem port for {@link exportNotebookSnapshot}. + */ +export interface NotebookSnapshotFs { + /** Returns file metadata for `path`, or `null` when `path` does not exist. */ + stat(path: string): Promise; + /** + * Exclusively creates an empty file at `path` (`O_CREAT | O_EXCL`). + * MUST throw an error carrying `code: 'EEXIST'` if `path` already exists. + */ + createExclusive(path: string): Promise; + /** Reads the complete byte contents of `path`. */ + readBytes(path: string): Promise; + /** Atomically replaces `destinationPath` with `sourcePath`. */ + rename(sourcePath: string, destinationPath: string): Promise; + /** Idempotently removes `path` (succeeds as a no-op if already absent). */ + remove(path: string): Promise; +} + +/** Parsed marimo 0.26.0 `marimo check --format=json` summary object. */ +export interface MarimoCheckSummary { + readonly errored: boolean; + readonly total_files: number; + readonly [key: string]: unknown; +} + +/** Parsed marimo 0.26.0 `marimo check --format=json` report object. */ +export interface MarimoCheckReport { + readonly issues: readonly Readonly>[]; + readonly summary: MarimoCheckSummary; + readonly [key: string]: unknown; +} + +export interface ExportNotebookSnapshotOptions { + readonly notebookPath: string; + readonly outputPath: string; + readonly runner: NotebookCommandRunner; + readonly fs: NotebookSnapshotFs; + /** Executable name or path for marimo (default `'marimo'`). */ + readonly marimoCommand?: string; + /** Per-command timeout in milliseconds (default `120_000`). */ + readonly timeoutMs?: number; + /** Optional working directory passed to `runner.run`. */ + readonly cwd?: string; + /** Optional absolute root directory that `notebookPath` must lexically reside within. */ + readonly allowedNotebookRoot?: string; + /** Optional absolute root directory that `outputPath` must lexically reside within. */ + readonly allowedOutputRoot?: string; +} + +/** Frozen receipt returned when a notebook snapshot is cleanly checked and published. */ +export interface NotebookSnapshotReceipt { + readonly notebookPath: string; + readonly outputPath: string; + readonly bytes: number; + readonly sha256: string; + readonly checkDiagnostics: MarimoCheckReport | null; +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function getErrorCode(err: unknown): string | undefined { + if (typeof err === 'object' && err !== null && 'code' in err) { + const code = (err as { code?: unknown }).code; + if (typeof code === 'string') { + return code; + } + } + return undefined; +} + +function normalizePosixAbsolutePath(rawPath: string): string { + const segments = rawPath.split('/'); + const stack: string[] = []; + for (let i = 0; i < segments.length; i += 1) { + const seg = segments[i]; + if (seg === undefined || seg === '' || seg === '.') { + continue; + } + if (seg === '..') { + if (stack.length > 0) { + stack.pop(); + } + continue; + } + stack.push(seg); + } + return `/${stack.join('/')}`; +} + +function validateAbsolutePath( + rawPath: unknown, + label: string, + options?: { readonly requiredExtension?: string } +): string { + if (typeof rawPath !== 'string' || rawPath.length === 0) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${label}: expected a non-empty string.` + ); + } + if (rawPath.includes('\0')) { + throw new NotebookSnapshotError('INVALID_PATH', `Invalid ${label}: NUL bytes are not allowed.`); + } + if (rawPath.startsWith('-')) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${label}: path must not start with '-'.` + ); + } + if (!rawPath.startsWith('/')) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${label}: path must be an absolute POSIX path.` + ); + } + + if (options?.requiredExtension !== undefined) { + if (rawPath.endsWith('/')) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${label}: path must reference a ${options.requiredExtension} file, not a directory.` + ); + } + } + + const normalized = normalizePosixAbsolutePath(rawPath); + + if (options?.requiredExtension !== undefined) { + const ext = options.requiredExtension; + if (!normalized.endsWith(ext) || normalized === `/${ext}` || normalized.endsWith(`/${ext}`)) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${label}: path must end with '${ext}'.` + ); + } + } + + return normalized; +} + +function assertWithinRoot( + normalizedPath: string, + rawRoot: unknown, + pathLabel: string, + rootLabel: string +): void { + const normalizedRoot = validateAbsolutePath(rawRoot, rootLabel); + if (normalizedRoot === '/') { + return; + } + const requiredPrefix = `${normalizedRoot}/`; + if (!normalizedPath.startsWith(requiredPrefix)) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${pathLabel}: resolved path '${normalizedPath}' escapes ${rootLabel} '${normalizedRoot}'.` + ); + } +} + +function dirnamePosix(normalizedFilePath: string): string { + const lastSlash = normalizedFilePath.lastIndexOf('/'); + return lastSlash <= 0 ? '/' : normalizedFilePath.slice(0, lastSlash); +} + +function validatePortsAndOptions(options: ExportNotebookSnapshotOptions): { + readonly notebookPath: string; + readonly outputPath: string; + readonly runner: NotebookCommandRunner; + readonly fs: NotebookSnapshotFs; + readonly marimoCommand: string; + readonly timeoutMs: number; + readonly cwd?: string; +} { + if (!isPlainObject(options)) { + throw new NotebookSnapshotError('INVALID_OPTION', 'Invalid options: expected an object.'); + } + + const { runner, fs } = options; + if (!isPlainObject(runner) || typeof runner.run !== 'function') { + throw new NotebookSnapshotError( + 'INVALID_OPTION', + 'Invalid runner: expected an object with a callable run(command, args, options) method.' + ); + } + if ( + !isPlainObject(fs) || + typeof fs.stat !== 'function' || + typeof fs.createExclusive !== 'function' || + typeof fs.readBytes !== 'function' || + typeof fs.rename !== 'function' || + typeof fs.remove !== 'function' + ) { + throw new NotebookSnapshotError( + 'INVALID_OPTION', + 'Invalid fs: expected an object implementing stat, createExclusive, readBytes, rename, and remove.' + ); + } + + const marimoCommand = + options.marimoCommand === undefined ? DEFAULT_MARIMO_COMMAND : options.marimoCommand; + if ( + typeof marimoCommand !== 'string' || + marimoCommand.trim().length === 0 || + marimoCommand.includes('\0') || + marimoCommand.startsWith('-') + ) { + throw new NotebookSnapshotError( + 'INVALID_OPTION', + 'Invalid marimoCommand: expected a non-empty command name or path without NUL bytes or leading "-".' + ); + } + + const timeoutMs = + options.timeoutMs === undefined ? DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS : options.timeoutMs; + if (typeof timeoutMs !== 'number' || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) { + throw new NotebookSnapshotError( + 'INVALID_OPTION', + 'Invalid timeoutMs: expected a positive safe integer.' + ); + } + + const notebookPath = validateAbsolutePath(options.notebookPath, 'notebookPath', { + requiredExtension: '.py', + }); + const outputPath = validateAbsolutePath(options.outputPath, 'outputPath', { + requiredExtension: '.html', + }); + + if (options.allowedNotebookRoot !== undefined) { + assertWithinRoot( + notebookPath, + options.allowedNotebookRoot, + 'notebookPath', + 'allowedNotebookRoot' + ); + } + if (options.allowedOutputRoot !== undefined) { + assertWithinRoot(outputPath, options.allowedOutputRoot, 'outputPath', 'allowedOutputRoot'); + } + + let cwd: string | undefined; + if (options.cwd !== undefined) { + cwd = validateAbsolutePath(options.cwd, 'cwd'); + } + + return { + notebookPath, + outputPath, + runner, + fs, + marimoCommand, + timeoutMs, + ...(cwd !== undefined ? { cwd } : {}), + }; +} + +function validateCommandResult(result: unknown, phase: 'check' | 'export'): NotebookCommandResult { + if ( + !isPlainObject(result) || + typeof result.exitCode !== 'number' || + !Number.isSafeInteger(result.exitCode) || + typeof result.stdout !== 'string' || + typeof result.stderr !== 'string' + ) { + throw new NotebookSnapshotError( + phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED', + `Invalid runner result for marimo ${phase}: expected { exitCode, stdout, stderr }.` + ); + } + return { + exitCode: result.exitCode, + stdout: result.stdout, + stderr: result.stderr, + }; +} + +function issueHasBlockingError(issue: Record): boolean { + if (issue.type === 'error' || issue.severity === 'breaking') { + return true; + } + const nested = issue.diagnostics; + if (Array.isArray(nested)) { + for (let i = 0; i < nested.length; i += 1) { + const diag = nested[i]; + if (isPlainObject(diag) && (diag.type === 'error' || diag.severity === 'breaking')) { + return true; + } + } + } + return false; +} + +function parseAndValidateCheckReport(parsed: unknown): { + readonly report: MarimoCheckReport; + readonly hasBlockingError: boolean; +} { + if (!isPlainObject(parsed)) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + 'marimo check JSON output must be an object with { issues, summary }.' + ); + } + + const { issues, summary } = parsed; + if (!Array.isArray(issues) || !isPlainObject(summary)) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + 'marimo check JSON output must contain an issues array and a summary object.' + ); + } + + if ( + typeof summary.errored !== 'boolean' || + typeof summary.total_files !== 'number' || + !Number.isSafeInteger(summary.total_files) + ) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + 'marimo check summary must include boolean errored and integer total_files.' + ); + } + + if (summary.total_files !== 1) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check reported summary.total_files=${summary.total_files}; expected exactly 1 checked file.`, + { details: { diagnostics: parsed } } + ); + } + + let hasBlockingError = summary.errored; + + for (let i = 0; i < issues.length; i += 1) { + const issue = issues[i]; + if (!isPlainObject(issue)) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}] must be an object.`, + { details: { diagnostics: parsed } } + ); + } + if (issue.type !== undefined && typeof issue.type !== 'string') { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].type must be a string when present.`, + { details: { diagnostics: parsed } } + ); + } + if (issue.severity !== undefined && typeof issue.severity !== 'string') { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].severity must be a string when present.`, + { details: { diagnostics: parsed } } + ); + } + if (issue.diagnostics !== undefined) { + if (!Array.isArray(issue.diagnostics)) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].diagnostics must be an array when present.`, + { details: { diagnostics: parsed } } + ); + } + for (let j = 0; j < issue.diagnostics.length; j += 1) { + const diag = issue.diagnostics[j]; + if (!isPlainObject(diag)) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].diagnostics[${j}] must be an object.`, + { details: { diagnostics: parsed } } + ); + } + if (diag.type !== undefined && typeof diag.type !== 'string') { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].diagnostics[${j}].type must be a string when present.`, + { details: { diagnostics: parsed } } + ); + } + if (diag.severity !== undefined && typeof diag.severity !== 'string') { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].diagnostics[${j}].severity must be a string when present.`, + { details: { diagnostics: parsed } } + ); + } + } + } + + if (issueHasBlockingError(issue)) { + hasBlockingError = true; + } + } + + return { + report: parsed as MarimoCheckReport, + hasBlockingError, + }; +} + +function deepFreeze(value: T): T { + if (typeof value !== 'object' || value === null || Object.isFrozen(value)) { + return value; + } + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + deepFreeze(value[i]); + } + return Object.freeze(value); + } + const record = value as Record; + const keys = Object.keys(record); + for (let i = 0; i < keys.length; i += 1) { + const key = keys[i] as string; + deepFreeze(record[key]); + } + return Object.freeze(value); +} + +function generateTempToken(): string { + tempSequence += 1; + const randomPart = + typeof globalThis.crypto !== 'undefined' && typeof globalThis.crypto.randomUUID === 'function' + ? globalThis.crypto.randomUUID().replace(/-/g, '') + : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; + return `${tempSequence}-${randomPart}`; +} + +async function reserveSiblingTempHtml(fs: NotebookSnapshotFs, outputPath: string): Promise { + const dir = dirnamePosix(outputPath); + const dirPrefix = dir === '/' ? '' : dir; + + for (let attempt = 0; attempt < MAX_TEMP_RESERVATION_ATTEMPTS; attempt += 1) { + const candidate = `${dirPrefix}/.marimo-snapshot-${generateTempToken()}.tmp.html`; + try { + await fs.createExclusive(candidate); + return candidate; + } catch (err) { + if (getErrorCode(err) === 'EEXIST') { + continue; + } + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `Failed to reserve temporary HTML sibling for '${outputPath}'.`, + { cause: err } + ); + } + } + + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `Failed to reserve a unique temporary HTML sibling for '${outputPath}' after ${MAX_TEMP_RESERVATION_ATTEMPTS} attempts.` + ); +} + +async function sha256HexNodeCrypto(bytes: Uint8Array): Promise { + // Keep the Node built-in specifier non-literal so browser bundlers do not try + // to statically resolve `node:crypto` when bundling `@stock-bot/research`. + const cryptoSpecifier = 'node:crypto'; + const nodeCrypto = (await import(cryptoSpecifier)) as typeof import('node:crypto'); + return nodeCrypto.createHash('sha256').update(bytes).digest('hex'); +} + +async function runPhaseCommand( + runner: NotebookCommandRunner, + command: string, + args: readonly string[], + runOptions: NotebookCommandRunOptions, + phase: 'check' | 'export' +): Promise { + let rawResult: unknown; + try { + rawResult = await runner.run(command, args, runOptions); + } catch (err) { + if (getErrorCode(err) === 'ETIMEDOUT') { + throw new NotebookSnapshotError( + 'TIMEOUT', + `marimo ${phase} timed out after ${runOptions.timeoutMs}ms.`, + { cause: err, details: { phase, timeoutMs: runOptions.timeoutMs } } + ); + } + throw new NotebookSnapshotError( + phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED', + `marimo ${phase} command failed to execute.`, + { cause: err, details: { phase } } + ); + } + return validateCommandResult(rawResult, phase); +} + +/** + * Validates a marimo notebook with `marimo check --format=json` and, only when + * the check is clean, exports a static HTML snapshot via `marimo export html` + * and publishes it atomically via sibling temp-file rename. + */ +export async function exportNotebookSnapshot( + options: ExportNotebookSnapshotOptions +): Promise { + const { notebookPath, outputPath, runner, fs, marimoCommand, timeoutMs, cwd } = + validatePortsAndOptions(options); + + let notebookStat: NotebookSnapshotFileStat | null; + try { + notebookStat = await fs.stat(notebookPath); + } catch (err) { + if (getErrorCode(err) === 'ENOENT') { + notebookStat = null; + } else { + throw new NotebookSnapshotError( + 'NOTEBOOK_NOT_FOUND', + `Unable to stat notebook '${notebookPath}'.`, + { cause: err } + ); + } + } + + if (notebookStat === null || !notebookStat.isFile) { + throw new NotebookSnapshotError( + 'NOTEBOOK_NOT_FOUND', + `Notebook file not found or is not a regular file: '${notebookPath}'.` + ); + } + + const runOptions: NotebookCommandRunOptions = + cwd !== undefined ? { cwd, timeoutMs } : { timeoutMs }; + + // Step 1: Gate on `marimo check --format=json `. + const checkResult = await runPhaseCommand( + runner, + marimoCommand, + ['check', '--format=json', notebookPath], + runOptions, + 'check' + ); + + const hasCheckStdout = checkResult.stdout.length > 0; + let parsedCheckJson: unknown = undefined; + let checkJsonParseError: unknown = undefined; + if (hasCheckStdout) { + try { + parsedCheckJson = JSON.parse(checkResult.stdout); + } catch (err) { + checkJsonParseError = err; + } + } + + if (checkResult.exitCode !== 0) { + throw new NotebookSnapshotError( + 'CHECK_FAILED', + `marimo check exited with code ${checkResult.exitCode}.`, + { + details: { + exitCode: checkResult.exitCode, + stderr: checkResult.stderr, + stdout: checkResult.stdout, + ...(checkJsonParseError === undefined && parsedCheckJson !== undefined + ? { diagnostics: parsedCheckJson } + : {}), + }, + } + ); + } + + let checkDiagnostics: MarimoCheckReport | null = null; + if (hasCheckStdout) { + if (checkJsonParseError !== undefined) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + 'marimo check exited 0 but emitted non-JSON stdout.', + { + cause: checkJsonParseError, + details: { stdout: checkResult.stdout, stderr: checkResult.stderr }, + } + ); + } + + const { report, hasBlockingError } = parseAndValidateCheckReport(parsedCheckJson); + if (hasBlockingError) { + throw new NotebookSnapshotError( + 'CHECK_FAILED', + 'marimo check reported blocking errors in diagnostics.', + { + details: { + exitCode: checkResult.exitCode, + stderr: checkResult.stderr, + diagnostics: report, + }, + } + ); + } + checkDiagnostics = deepFreeze(report); + } + + // Step 2: Reserve an exclusive sibling `.html` temp file and run `marimo export html`. + const tempPath = await reserveSiblingTempHtml(fs, outputPath); + let tempOwned = true; + + try { + const exportResult = await runPhaseCommand( + runner, + marimoCommand, + ['export', 'html', notebookPath, '-o', tempPath, '--force'], + runOptions, + 'export' + ); + + if (exportResult.exitCode !== 0) { + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `marimo export html exited with code ${exportResult.exitCode}.`, + { + details: { + exitCode: exportResult.exitCode, + stderr: exportResult.stderr, + stdout: exportResult.stdout, + }, + } + ); + } + + let tempStat: NotebookSnapshotFileStat | null; + try { + tempStat = await fs.stat(tempPath); + } catch (err) { + if (getErrorCode(err) === 'ENOENT') { + tempStat = null; + } else { + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `Failed to stat exported snapshot temp file '${tempPath}'.`, + { cause: err } + ); + } + } + + if (tempStat === null || !tempStat.isFile || tempStat.size <= 0) { + throw new NotebookSnapshotError( + 'EXPORT_EMPTY', + `marimo export html produced missing or empty output at '${tempPath}'.` + ); + } + + let exportedBytes: Uint8Array; + try { + exportedBytes = await fs.readBytes(tempPath); + } catch (err) { + if (getErrorCode(err) === 'ENOENT') { + throw new NotebookSnapshotError( + 'EXPORT_EMPTY', + `Exported snapshot temp file '${tempPath}' disappeared before read.`, + { cause: err } + ); + } + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `Failed to read exported snapshot temp file '${tempPath}'.`, + { cause: err } + ); + } + + if (!(exportedBytes instanceof Uint8Array) || exportedBytes.byteLength === 0) { + throw new NotebookSnapshotError( + 'EXPORT_EMPTY', + `marimo export html produced zero bytes at '${tempPath}'.` + ); + } + + const sha256 = await sha256HexNodeCrypto(exportedBytes); + const receipt: NotebookSnapshotReceipt = Object.freeze({ + notebookPath, + outputPath, + bytes: exportedBytes.byteLength, + sha256, + checkDiagnostics, + }); + + try { + await fs.rename(tempPath, outputPath); + tempOwned = false; + } catch (err) { + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `Failed to atomically publish snapshot from '${tempPath}' to '${outputPath}'.`, + { cause: err } + ); + } + + return receipt; + } catch (err) { + if (tempOwned) { + try { + await fs.remove(tempPath); + } catch { + // Preserve the primary error if temp cleanup also fails. + } + } + if (err instanceof NotebookSnapshotError) { + throw err; + } + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + 'Unexpected failure during notebook snapshot export.', + { cause: err } + ); + } +} diff --git a/libs/research/test/mcp-bar-session-dates-qa.test.ts b/libs/research/test/mcp-bar-session-dates-qa.test.ts new file mode 100644 index 00000000..1685e47f --- /dev/null +++ b/libs/research/test/mcp-bar-session-dates-qa.test.ts @@ -0,0 +1,249 @@ +import { describe, expect, test } from 'bun:test'; +import { VaultHoldoutFenceError } from '../src/market-data-store'; +import { + type DuckDbExecutor, + type DuckDbParam, + createDuckDbMarketDataStore, +} from '../src/market-data-store-duckdb'; +import { + type ListingCalendarPort, + createBarSessionDatesPort, + createExchangeCalendarResolver, +} from '@stock-bot/research/mcp'; + +/** + * QA: the bar-derived SessionDatesPort composed with the real DuckDB store + * planner (`planBars1dQuery` + `mapBarRows`) over a recording fake executor that + * emulates the raw 1d SQL predicate (`listing_id IN (...) AND ts >= ? AND ts <= ? + * AND known_at <= ?` ordered by `listing_id, ts`) on a pinned in-memory dataset. + */ + +const CURATED_ROOT = '/mnt/data/stockbot/curated'; +const CUTOFF_MS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); // 2026-05-28T00:00:00.000Z +const MAX_ALLOWED_ISO_MICROS = '2026-05-27T23:59:59.999999Z'; + +interface FixtureBar { + readonly listingId: number; + readonly ts: number; + readonly knownAt: number; +} + +function utcMs(dateStr: string, hour: number, minute = 0): number { + const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number]; + return Date.UTC(y, m - 1, d, hour, minute, 0, 0); +} + +/** 16:00 ET daily stamp (curate_bars.rs convention): 20:00Z in EDT. Known shortly after close. */ +function edtBar(listingId: number, date: string, knownAt?: number): FixtureBar { + const ts = utcMs(date, 20); + return { listingId, ts, knownAt: knownAt ?? ts + 60_000 }; +} + +/** Parses `YYYY-MM-DDTHH:MM:SS(.ffffff)?Z` to fractional epoch ms (µs precision kept). */ +function isoToMs(iso: string): number { + const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/.exec(iso); + if (m === null) { + throw new Error(`Unexpected ISO bound: ${iso}`); + } + const frac = Number(`0.${(m[7] ?? '0').padEnd(6, '0').slice(0, 6)}`); + return ( + Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])) + + frac * 1000 + ); +} + +function createFixtureExecutor(dataset: readonly FixtureBar[]): { + readonly executor: DuckDbExecutor; + readonly queries: Array<{ sql: string; params: readonly DuckDbParam[] }>; +} { + const queries: Array<{ sql: string; params: readonly DuckDbParam[] }> = []; + const executor: DuckDbExecutor = { + async run(): Promise {}, + async query(sql: string, params: readonly DuckDbParam[]) { + queries.push({ sql, params: [...params] }); + const listingIds = new Set(params.slice(0, -3) as number[]); + const [fromIso, toIso, asOfIso] = params.slice(-3) as [string, string, string]; + const fromMs = isoToMs(fromIso); + const toMs = isoToMs(toIso); + const asOfMs = isoToMs(asOfIso); + return dataset + .filter( + (b) => + listingIds.has(b.listingId) && b.ts >= fromMs && b.ts <= toMs && b.knownAt <= asOfMs + ) + .sort((a, b) => a.listingId - b.listingId || a.ts - b.ts) + .map((b) => ({ + listing_id: b.listingId, + ts: b.ts, + open: 10, + high: 11, + low: 9, + close: 10.5, + volume: 1000, + vwap: null, + known_at: b.knownAt, + })); + }, + }; + return { executor, queries }; +} + +const DATASET: readonly FixtureBar[] = [ + // XNYS reference listings 11 and 12 (overlapping + one-sided dates). + edtBar(11, '2026-05-21'), + edtBar(12, '2026-05-22'), + edtBar(11, '2026-05-26'), + edtBar(12, '2026-05-26'), + edtBar(12, '2026-05-27'), + // Held-out Vault sessions at and after the cutoff date. + edtBar(11, '2026-05-28'), + edtBar(12, '2026-05-29'), + edtBar(11, '2026-06-01'), + // XTSE reference listing 21. + edtBar(21, '2026-05-25'), // Victoria Day: XTSE closed in reality, but present here to prove per-calendar isolation. + edtBar(21, '2026-05-26'), + // Pre-cutoff session whose bar only became known after the cutoff: must stay hidden. + edtBar(21, '2026-05-27', CUTOFF_MS + 3_600_000), + edtBar(21, '2026-05-28'), +]; + +function makeStore(barBatchSize?: number) { + const fake = createFixtureExecutor(DATASET); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + ...(barBatchSize !== undefined ? { barBatchSize } : {}), + }); + return { store, queries: fake.queries }; +} + +describe('bar-session-dates QA — DuckDB store planner at the Vault cutoff', () => { + test('window straddling the cutoff returns only pre-cutoff sessions with a raw bars_1d plan clamped to cutoff - 1µs', async () => { + const { store, queries } = makeStore(); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [12, 11], XTSE: [21] }, + }); + + const dates = await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2026-05-22', + toDate: '2026-06-02', + }); + + expect(dates).toEqual(['2026-05-22', '2026-05-26', '2026-05-27']); + expect(queries).toHaveLength(1); + const q = queries[0]!; + expect(q.sql).toContain(`read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet'`); + expect(q.sql).not.toContain('adj_factors'); + expect(q.params).toEqual([ + 12, + 11, + '2026-05-22T00:00:00.000Z', + MAX_ALLOWED_ISO_MICROS, + MAX_ALLOWED_ISO_MICROS, + ]); + }); + + test('pre-cutoff bar first known after the cutoff is excluded via the default known_at fence', async () => { + const { store } = makeStore(); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [11, 12], XTSE: [21] }, + }); + + expect( + await port.listSessionDates({ + calendarCode: 'XTSE', + fromDate: '2026-05-25', + toDate: '2026-05-31', + }) + ).toEqual(['2026-05-25', '2026-05-26']); + }); + + test('fromDate on or after the cutoff date rejects with VaultHoldoutFenceError before any executor query', async () => { + const { store, queries } = makeStore(); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [11, 12] }, + }); + + for (const fromDate of ['2026-05-28', '2026-06-01']) { + let caught: unknown; + try { + await port.listSessionDates({ calendarCode: 'XNYS', fromDate, toDate: '2026-06-02' }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(VaultHoldoutFenceError); + } + expect(queries).toHaveLength(0); + }); + + test('last pre-cutoff day as a single-day window is included, and output is identical across barBatchSize settings', async () => { + const results: string[][] = []; + for (const batchSize of [undefined, 1, 2]) { + const { store } = makeStore(batchSize); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [11, 12] }, + }); + results.push([ + ...(await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2026-05-21', + toDate: '2026-05-27', + })), + ]); + expect( + await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2026-05-27', + toDate: '2026-05-27', + }) + ).toEqual(['2026-05-27']); + } + const expected = ['2026-05-21', '2026-05-22', '2026-05-26', '2026-05-27']; + expect(results).toEqual([expected, expected, expected]); + }); + + test('resolver composed over the DuckDB-backed port yields no post-cutoff session closes', async () => { + const { store, queries } = makeStore(); + const sessionDates = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [11, 12], XTSE: [21] }, + }); + const listingCalendars: ListingCalendarPort = { + getListingCalendars(listingIds) { + return listingIds.map((listingId) => ({ + listingId, + calendarCode: listingId === 901 ? 'XNYS' : 'XTSE', + })); + }, + }; + const resolve = createExchangeCalendarResolver({ listingCalendars, sessionDates }); + + const resolved = await resolve({ + listingIds: [901, 902], + fromDate: '2026-05-26', + toDate: '2026-06-02', + }); + + expect(resolved.listingCalendarId).toEqual({ 901: 'XNYS', 902: 'XTSE' }); + expect(resolved.calendars).toEqual({ + XNYS: [ + { date: '2026-05-26', closeTs: utcMs('2026-05-26', 20) }, + { date: '2026-05-27', closeTs: utcMs('2026-05-27', 20) }, + ], + XTSE: [{ date: '2026-05-26', closeTs: utcMs('2026-05-26', 20) }], + }); + for (const closes of Object.values(resolved.calendars)) { + for (const c of closes) { + expect(c.closeTs).toBeLessThan(CUTOFF_MS); + } + } + expect(queries).toHaveLength(2); + }); +}); diff --git a/libs/research/test/mcp-bar-session-dates.test.ts b/libs/research/test/mcp-bar-session-dates.test.ts new file mode 100644 index 00000000..f5a1ebca --- /dev/null +++ b/libs/research/test/mcp-bar-session-dates.test.ts @@ -0,0 +1,527 @@ +import { describe, expect, test } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + type MarketDataStore, + VaultHoldoutFenceError, +} from '../src/market-data-store'; +import { + BarSessionDatesError, + type BarSessionDatesPortOptions, + type ListingCalendarPort, + type PostgresResearchCopilotServerOptions, + type SessionDatesPort, + createBarSessionDatesPort, + createExchangeCalendarResolver, +} from '@stock-bot/research/mcp'; + +type BarsQueryArg = Parameters[0]; + +function utcMs( + year: number, + month: number, + day: number, + hour = 0, + minute = 0, + second = 0 +): number { + return Date.UTC(year, month - 1, day, hour, minute, second, 0); +} + +function makeBar(listingId: number, dateStr: string, closeHourUtc = 21): BarRecord { + const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number]; + const ts = utcMs(y, m, d, closeHourUtc, 0, 0); + return { + listingId, + ts, + open: 100, + high: 101, + low: 99, + close: 100.5, + volume: 100_000, + knownAt: ts, + }; +} + +function makeRecordingStore( + handler: (q: BarsQueryArg) => AsyncIterable +): { + readonly store: Pick; + readonly calls: BarsQueryArg[]; +} { + const calls: BarsQueryArg[] = []; + const store: Pick = { + bars(q: BarsQueryArg): AsyncIterable { + calls.push(q); + return handler(q); + }, + }; + return { store, calls }; +} + +async function* yieldBatches(batches: readonly BarBatch[]): AsyncGenerator { + for (const batch of batches) { + yield batch; + } +} + +describe('createBarSessionDatesPort — exports, types, and query contract', () => { + test('returned port is assignable to SessionDatesPort and PostgresResearchCopilotServerOptions["sessionDates"] without casts', async () => { + const { store } = makeRecordingStore(() => yieldBatches([])); + const options: BarSessionDatesPortOptions = { + store, + referenceListingIds: { + XNYS: [101], + }, + }; + + const port = createBarSessionDatesPort(options); + const asSessionDatesPort: SessionDatesPort = port; + const asCopilotSessionDates: PostgresResearchCopilotServerOptions['sessionDates'] = port; + + expect(asSessionDatesPort).toBe(port); + expect(asCopilotSessionDates).toBe(port); + expect( + await asCopilotSessionDates.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-29', + }) + ).toEqual([]); + }); + + test('calls store.bars once per query with exact Vault-default keys and configured ID order', async () => { + const { store, calls } = makeRecordingStore(() => + yieldBatches([{ rows: [makeBar(202, '2024-11-26', 21)] }]) + ); + + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { + XNYS: [202, 101], + XTSE: [303], + }, + }); + + const dates = await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-29', + }); + + expect(dates).toEqual(['2024-11-26']); + expect(calls).toHaveLength(1); + + const req = calls[0] as BarsQueryArg; + expect(req.listingIds).toEqual([202, 101]); + expect(req.timeframe).toBe('1d'); + expect(req.adjustment).toBe('raw'); + expect(req.from).toBe('2024-11-25'); + expect(req.to).toBe('2024-11-29'); + expect(Object.keys(req).sort()).toEqual(['adjustment', 'from', 'listingIds', 'timeframe', 'to']); + expect('scope' in req).toBe(false); + expect('asOf' in req).toBe(false); + }); +}); + +describe('createBarSessionDatesPort — union, bounds, determinism, and empty streams', () => { + test('returns strictly ascending de-duplicated union across multiple out-of-order batches inside [fromDate, toDate]', async () => { + const batches: readonly BarBatch[] = [ + { + rows: [ + // Valid bars outside the requested window must be excluded. + makeBar(101, '2024-11-22', 21), + makeBar(102, '2024-12-02', 21), + // Out-of-order bars inside window, including upper inclusive bound. + makeBar(102, '2024-11-29', 21), + makeBar(101, '2024-11-27', 21), + ], + }, + { + rows: [ + // Overlapping date (2024-11-27), single-listing date (2024-11-26), lower inclusive bound (2024-11-25). + makeBar(102, '2024-11-27', 21), + makeBar(101, '2024-11-25', 21), + makeBar(102, '2024-11-26', 21), + ], + }, + ]; + + const { store, calls } = makeRecordingStore(() => yieldBatches(batches)); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { + XNYS: [101, 102], + }, + }); + + const first = await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-29', + }); + const second = await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-29', + }); + + const expected = ['2024-11-25', '2024-11-26', '2024-11-27', '2024-11-29']; + expect(first).toEqual(expected); + expect(second).toEqual(expected); + expect(calls).toHaveLength(2); + }); + + test('supports single-day inclusive window and returns [] for empty streams or empty batches', async () => { + const { store: singleDayStore } = makeRecordingStore(() => + yieldBatches([ + { + rows: [ + makeBar(101, '2024-07-01', 20), + makeBar(101, '2024-07-02', 20), + makeBar(101, '2024-07-03', 20), + ], + }, + ]) + ); + + const singleDayPort = createBarSessionDatesPort({ + store: singleDayStore, + referenceListingIds: { XNYS: [101] }, + }); + + expect( + await singleDayPort.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-07-02', + toDate: '2024-07-02', + }) + ).toEqual(['2024-07-02']); + + const { store: emptyBatchStore } = makeRecordingStore(() => + yieldBatches([{ rows: [] }, { rows: [] }]) + ); + const emptyPort = createBarSessionDatesPort({ + store: emptyBatchStore, + referenceListingIds: { XNYS: [101] }, + }); + + expect( + await emptyPort.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-07-02', + toDate: '2024-07-02', + }) + ).toEqual([]); + }); +}); + +describe('createBarSessionDatesPort — fail-closed query, store error, and bar validation', () => { + test('throws unknown_calendar and invalid_query with zero store calls', async () => { + const { store, calls } = makeRecordingStore(() => yieldBatches([])); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { + XNYS: [101], + }, + }); + + const expectError = async ( + query: unknown, + expectedCode: BarSessionDatesError['code'] + ): Promise => { + let caught: unknown; + try { + await port.listSessionDates(query as never); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(BarSessionDatesError); + expect((caught as BarSessionDatesError).code).toBe(expectedCode); + }; + + await expectError( + { calendarCode: 'XTSE', fromDate: '2024-11-25', toDate: '2024-11-29' }, + 'unknown_calendar' + ); + await expectError( + { calendarCode: '', fromDate: '2024-11-25', toDate: '2024-11-29' }, + 'unknown_calendar' + ); + await expectError( + { calendarCode: 'XNYS', fromDate: '2024/11/25', toDate: '2024-11-29' }, + 'invalid_query' + ); + await expectError( + { calendarCode: 'XNYS', fromDate: '2024-11-25T00:00:00Z', toDate: '2024-11-29' }, + 'invalid_query' + ); + await expectError( + { calendarCode: 'XNYS', fromDate: '2024-02-30', toDate: '2024-03-01' }, + 'invalid_query' + ); + await expectError( + { calendarCode: 'XNYS', fromDate: '2024-11-25', toDate: '2023-02-29' }, + 'invalid_query' + ); + await expectError( + { calendarCode: 'XNYS', fromDate: '2024-11-29', toDate: '2024-11-25' }, + 'invalid_query' + ); + await expectError(null, 'invalid_query'); + + expect(calls).toHaveLength(0); + }); + + test('propagates VaultHoldoutFenceError from the async iterator unchanged with no partial result', async () => { + const vaultError = new VaultHoldoutFenceError( + '2025-01-02', + utcMs(2025, 1, 2, 0, 0, 0), + utcMs(2025, 1, 1, 0, 0, 0) + ); + + const { store } = makeRecordingStore(() => + (async function* (): AsyncGenerator { + yield { rows: [makeBar(101, '2024-12-31', 21)] }; + throw vaultError; + })() + ); + + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [101] }, + }); + + let caught: unknown; + try { + await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-12-30', + toDate: '2025-01-02', + }); + } catch (err) { + caught = err; + } + + expect(caught).toBe(vaultError); + }); + + test('throws invalid_bar for NaN, Infinity, fractional ts, or unconfigured listingId', async () => { + const badBars: readonly BarRecord[] = [ + { ...makeBar(101, '2024-11-25', 21), ts: Number.NaN }, + { ...makeBar(101, '2024-11-25', 21), ts: Number.POSITIVE_INFINITY }, + { ...makeBar(101, '2024-11-25', 21), ts: Number.NEGATIVE_INFINITY }, + { ...makeBar(101, '2024-11-25', 21), ts: utcMs(2024, 11, 25, 21, 0, 0) + 0.5 }, + // Listing ID configured only on XTSE, not XNYS. + makeBar(202, '2024-11-25', 21), + // Listing ID not configured on any calendar, even when outside the date window. + makeBar(999, '2024-01-02', 21), + ]; + + for (const badBar of badBars) { + const { store } = makeRecordingStore(() => yieldBatches([{ rows: [badBar] }])); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { + XNYS: [101], + XTSE: [202], + }, + }); + + let caught: unknown; + try { + await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-29', + }); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(BarSessionDatesError); + expect((caught as BarSessionDatesError).code).toBe('invalid_bar'); + } + }); +}); + +describe('createBarSessionDatesPort — options validation and defensive copy', () => { + test('rejects malformed options, empty keys, non-positive/non-INT32 IDs, and duplicates with invalid_options', () => { + const { store } = makeRecordingStore(() => yieldBatches([])); + + const invalidInputs: readonly unknown[] = [ + null, + undefined, + {}, + { store: null, referenceListingIds: { XNYS: [1] } }, + { store: {}, referenceListingIds: { XNYS: [1] } }, + { store: { bars: 'nope' }, referenceListingIds: { XNYS: [1] } }, + { store, referenceListingIds: null }, + { store, referenceListingIds: [] }, + { store, referenceListingIds: { '': [1] } }, + { store, referenceListingIds: { ' ': [1] } }, + { store, referenceListingIds: { ' XNYS': [1] } }, + { store, referenceListingIds: { XNYS: null } }, + { store, referenceListingIds: { XNYS: [] } }, + { store, referenceListingIds: { XNYS: [0] } }, + { store, referenceListingIds: { XNYS: [-5] } }, + { store, referenceListingIds: { XNYS: [1.5] } }, + { store, referenceListingIds: { XNYS: [2_147_483_648] } }, + { store, referenceListingIds: { XNYS: [Number.NaN] } }, + { store, referenceListingIds: { XNYS: [101, 202, 101] } }, + ]; + + for (const input of invalidInputs) { + let caught: unknown; + try { + createBarSessionDatesPort(input as never); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(BarSessionDatesError); + expect((caught as BarSessionDatesError).code).toBe('invalid_options'); + } + }); + + test('defensively copies caller config and isolates per-call listingIds arrays', async () => { + const xnysIds = [101, 102]; + const referenceListingIds: Record = { + XNYS: xnysIds, + }; + + const observedIds: number[][] = []; + const store: Pick = { + bars(q: BarsQueryArg): AsyncIterable { + observedIds.push([...q.listingIds]); + // Mutate caller-passed query array to confirm port passes a fresh copy each time. + q.listingIds.push(999); + return yieldBatches([{ rows: [makeBar(101, '2024-11-25', 21)] }]); + }, + }; + + const port = createBarSessionDatesPort({ store, referenceListingIds }); + + // Mutate caller config after construction. + xnysIds.push(303); + xnysIds[0] = 404; + referenceListingIds.XNYS = [505]; + referenceListingIds.XTSE = [606]; + + expect( + await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-25', + }) + ).toEqual(['2024-11-25']); + expect( + await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-25', + }) + ).toEqual(['2024-11-25']); + + expect(observedIds).toEqual([ + [101, 102], + [101, 102], + ]); + + let caught: unknown; + try { + await port.listSessionDates({ + calendarCode: 'XTSE', + fromDate: '2024-11-25', + toDate: '2024-11-25', + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(BarSessionDatesError); + expect((caught as BarSessionDatesError).code).toBe('unknown_calendar'); + }); +}); + +describe('createBarSessionDatesPort — composition with createExchangeCalendarResolver', () => { + test('resolves XNYS and XTSE session closes including summer EDT, Thanksgiving divergence, and early-close override', async () => { + const xnysBars: readonly BarRecord[] = [ + // Summer EDT session (16:00 ET = 20:00Z) + makeBar(1001, '2024-07-02', 20), + // Winter EST sessions (US closed 2024-11-28 Thanksgiving; open 2024-11-29) + makeBar(1001, '2024-11-27', 21), + makeBar(1002, '2024-11-29', 21), + ]; + + const xtseBars: readonly BarRecord[] = [ + // Summer EDT session (16:00 ET = 20:00Z) + makeBar(2001, '2024-07-02', 20), + // Winter EST sessions (TSX open on US Thanksgiving 2024-11-28 and regular close on 2024-11-29) + makeBar(2001, '2024-11-27', 21), + makeBar(2001, '2024-11-28', 21), + makeBar(2002, '2024-11-29', 21), + ]; + + const { store, calls } = makeRecordingStore((q) => { + const requested = new Set(q.listingIds); + const rows = [...xnysBars, ...xtseBars].filter((bar) => requested.has(bar.listingId)); + return yieldBatches([{ rows }]); + }); + + const sessionDates = createBarSessionDatesPort({ + store, + referenceListingIds: { + XNYS: [1001, 1002], + XTSE: [2001, 2002], + }, + }); + + const listingCalendars: ListingCalendarPort = { + getListingCalendars(listingIds) { + return listingIds.map((listingId) => ({ + listingId, + calendarCode: listingId === 501 ? 'XNYS' : 'XTSE', + })); + }, + }; + + const resolveExchangeCalendars = createExchangeCalendarResolver({ + listingCalendars, + sessionDates, + earlyCloses: { + XNYS: { + '2024-11-29': 13 * 60, // 13:00 ET -> 18:00Z (EST) + }, + }, + }); + + const resolved = await resolveExchangeCalendars({ + listingIds: [501, 602], + fromDate: '2024-07-02', + toDate: '2024-11-29', + }); + + expect(resolved.listingCalendarId).toEqual({ + 501: 'XNYS', + 602: 'XTSE', + }); + + expect(resolved.calendars).toEqual({ + XNYS: [ + { date: '2024-07-02', closeTs: utcMs(2024, 7, 2, 20, 0, 0) }, + { date: '2024-11-27', closeTs: utcMs(2024, 11, 27, 21, 0, 0) }, + { date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 18, 0, 0) }, + ], + XTSE: [ + { date: '2024-07-02', closeTs: utcMs(2024, 7, 2, 20, 0, 0) }, + { date: '2024-11-27', closeTs: utcMs(2024, 11, 27, 21, 0, 0) }, + { date: '2024-11-28', closeTs: utcMs(2024, 11, 28, 21, 0, 0) }, + { date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 21, 0, 0) }, + ], + }); + + // One store.bars call per distinct calendar code (XNYS, XTSE). + expect(calls).toHaveLength(2); + expect(calls[0]?.listingIds).toEqual([1001, 1002]); + expect(calls[1]?.listingIds).toEqual([2001, 2002]); + }); +}); diff --git a/libs/research/test/mcp-postgres-copilot.test.ts b/libs/research/test/mcp-postgres-copilot.test.ts new file mode 100644 index 00000000..cdb0d3d8 --- /dev/null +++ b/libs/research/test/mcp-postgres-copilot.test.ts @@ -0,0 +1,1139 @@ +import { describe, expect, test } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + type EventKind, + type MarketDataStore, + type Table, + type TableRow, +} from '../src/market-data-store'; +import { + EVENTS_COLUMNS, + MarketDataStoreNotImplementedError, +} from '../src/market-data-store-duckdb'; +import { + type EventStudyResultPayload, + type FileFindingResultPayload, + type KnowledgePort, + type LibraryCardQuery, + type LibraryCardRecord, + type ListingCalendarExecutor, + type McpServer, + type PostgresFindingsExecutor, + type PostgresResearchCopilotExecutor, + type PostgresResearchCopilotServerOptions, + RESEARCH_COPILOT_TOOL_NAMES, + type ReadKnowledgeResultPayload, + type SearchSymbolsResultPayload, + type SessionDatesPort, + type SessionDatesQuery, + type SymbolSearchExecutor, + type TrialRefExecutor, + createPostgresResearchCopilotServer, +} from '../src/mcp/index'; +import type { TrialLedgerExecutor } from '../src/trial-ledger'; + +// Synthetic PostgreSQL copilot composition fixture metadata (pinned for reproducibility): +// - Dataset ID: `synthetic:mcp-postgres-copilot:seed-20261202:v1` +// - Seed: `20261202` (Mulberry32 PRNG) +// - Universe: 8 synthetic US equity listings (`60001..60008`, XNYS, USD, 21:00 UTC close) +// - Sessions: 40 pre-cutoff + 5 post-cutoff business sessions starting `2023-01-03` +// - Cutoff: `vaultCutoffDate` = `allDates[40]` (`vaultCutoffTs = Date.UTC(..., 0, 0, 0)`) +// - Economic assumptions: daily raw close-to-close returns, equal-weight benchmark over +// eligible listing returns, zero modeled execution/transaction costs. +// - Ownership: Quant research role owns the study assumptions; `AGENT_PRINCIPAL` owns +// recorded `trial_ledger` rows. +const FIXTURE_DATASET_ID = 'synthetic:mcp-postgres-copilot:seed-20261202:v1'; +const SEED = 20261202; +const SERVER_NAME = 'stock-bot-pg-copilot'; +const SERVER_VERSION = '0.1.0'; +const AGENT_PRINCIPAL = 'agent:22222222-3333-4444-8555-666666666666'; +const FIXED_FINDING_ID = 'finding-pg-copilot-001'; +const FIXED_NOW_ISO = '2024-06-15T12:00:00.000Z'; +const FIXED_NOW_MS = Date.parse(FIXED_NOW_ISO); + +// Compile-time assertions: +// 1) PostgresResearchCopilotExecutor is assignable to all five existing executor interfaces without casts. +function _assertExecutorAssignability(executor: PostgresResearchCopilotExecutor) { + const asSymbolSearch: SymbolSearchExecutor = executor; + const asTrialRef: TrialRefExecutor = executor; + const asFindings: PostgresFindingsExecutor = executor; + const asListingCalendar: ListingCalendarExecutor = executor; + const asTrialLedger: TrialLedgerExecutor = executor; + return [asSymbolSearch, asTrialRef, asFindings, asListingCalendar, asTrialLedger] as const; +} +void _assertExecutorAssignability; + +// 2) PostgresResearchCopilotServerOptions has no separate `vaultCutoffTs` key. +type HasSeparateVaultCutoffTs = 'vaultCutoffTs' extends keyof PostgresResearchCopilotServerOptions + ? true + : false; +const _noSeparateVaultCutoffTs: HasSeparateVaultCutoffTs = false; +void _noSeparateVaultCutoffTs; + +interface RecordedSqlCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +interface StoredTrialRow { + readonly trial_id: string; + readonly created_at: Date; + readonly principal_id: string; + readonly campaign_id: string | null; + readonly stage: string; + readonly universe_market: string; + readonly horizon_bucket: string; + readonly hypothesis_id: string | null; + readonly expression_hash: string; + readonly sample_start: string; + readonly sample_end: string; + readonly n_obs: number; + readonly sharpe_unann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly daily_series: readonly number[]; +} + +interface JsonRpcResponseEnvelope { + readonly jsonrpc: '2.0'; + readonly id: number | string | null; + readonly result?: unknown; + readonly error?: { + readonly code: number; + readonly message: string; + }; +} + +interface ToolCallEnvelope { + readonly content: readonly { readonly type: 'text'; readonly text: string }[]; + readonly isError?: boolean; +} + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = new Array(count); + const current = new Date(`${startDate}T00:00:00.000Z`); + let written = 0; + while (written < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out[written] = current.toISOString().slice(0, 10); + written += 1; + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0): number { + const [y, m, d] = date.split('-').map(Number); + return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, 0); +} + +function parseBoundMs(raw: string, endOfDay: boolean): number { + if (raw.length === 10) { + return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); + } + return Date.parse(raw); +} + +interface EventStudyFixture { + readonly listingIds: readonly number[]; + readonly allDates: readonly string[]; + readonly preCutoffDates: readonly string[]; + readonly firstDate: string; + readonly lastPreCutoffDate: string; + readonly vaultCutoffDate: string; + readonly vaultCutoffTs: number; + readonly bars: readonly BarRecord[]; + readonly eventsTable: Table; +} + +function buildEventStudyFixture(): EventStudyFixture { + const rand = createSeededRng(SEED); + const listingCount = 8; + const preCutoffSessions = 40; + const postCutoffSessions = 5; + + const allDates = makeBusinessDates('2023-01-03', preCutoffSessions + postCutoffSessions); + const preCutoffDates = allDates.slice(0, preCutoffSessions); + const firstDate = allDates[0]!; + const lastPreCutoffDate = allDates[preCutoffSessions - 1]!; + const vaultCutoffDate = allDates[preCutoffSessions]!; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const listingIds = Array.from({ length: listingCount }, (_, i) => 60_001 + i); + const bars: BarRecord[] = []; + const eventRows: TableRow[] = []; + + const eventDayIndices = [8, 14, 20, 26, 32]; + const eventSet = new Set(); + for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { + const t = eventDayIndices[eIdx]!; + const date = allDates[t]!; + const ts = makeUtcMs(date, 14); // 09:00 ET intraday filing + for (let k = 0; k < 2; k += 1) { + const l = (eIdx * 2 + k) % listingCount; + eventSet.add(`${t}:${l}`); + const kind: EventKind = 'filing'; + eventRows.push({ + listing_id: listingIds[l]!, + ts, + known_at: ts, + known_at_source: 'exact', + kind, + subtype: '8-K', + payload_json: '{}', + }); + } + } + + const prices = new Float64Array(listingCount); + for (let l = 0; l < listingCount; l += 1) { + prices[l] = 20 + l * 3; + } + + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); // 16:00 ET close + for (let l = 0; l < listingCount; l += 1) { + let drift = 0; + for (let offset = 0; offset <= 2; offset += 1) { + if (eventSet.has(`${t - offset}:${l}`)) { + drift += 0.008 * (1 + ((l + t) % 3) * 0.2); + } + } + const ret = drift + (rand() * 2 - 1) * 0.01; + prices[l] = Math.max(1.0, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(4)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: Number((close * 0.995).toFixed(4)), + high: Number((close * 1.01).toFixed(4)), + low: Number((close * 0.99).toFixed(4)), + close, + volume: 100_000 + l * 1_000 + t * 50, + vwap: close, + knownAt: closeTs, + }); + } + } + + return { + listingIds, + allDates, + preCutoffDates, + firstDate, + lastPreCutoffDate, + vaultCutoffDate, + vaultCutoffTs, + bars, + eventsTable: { + columns: [...EVENTS_COLUMNS], + rows: eventRows, + }, + }; +} + +function createFakeMarketDataStore(fixture: EventStudyFixture): MarketDataStore { + return { + bars(q): AsyncIterable { + const idSet = new Set(q.listingIds); + const fromMs = parseBoundMs(q.from, false); + const toMs = parseBoundMs(q.to, true); + const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; + const filtered = fixture.bars.filter( + row => + idSet.has(row.listingId) && + row.ts >= fromMs && + row.ts <= toMs && + row.knownAt <= asOfMs + ); + return { + async *[Symbol.asyncIterator]() { + yield { rows: filtered }; + }, + }; + }, + async universe() { + return [...fixture.listingIds]; + }, + async events(q): Promise { + const idSet = q.listingIds !== undefined ? new Set(q.listingIds) : null; + const kindSet = new Set(q.kinds); + const fromMs = parseBoundMs(q.from, false); + const toMs = parseBoundMs(q.to, true); + const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; + const filtered = fixture.eventsTable.rows.filter(row => { + const listingId = row.listing_id as number; + const kind = row.kind as EventKind; + const ts = row.ts as number; + const knownAt = row.known_at as number; + if (idSet !== null && !idSet.has(listingId)) { + return false; + } + return kindSet.has(kind) && ts >= fromMs && ts <= toMs && knownAt <= asOfMs; + }); + return { + columns: fixture.eventsTable.columns, + rows: filtered, + }; + }, + async shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + async crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + async fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + async macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + async fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; +} + +class RecordingPostgresExecutor implements PostgresResearchCopilotExecutor { + readonly calls: RecordedSqlCall[] = []; + readonly ledgerRows: StoredTrialRow[] = []; + readonly visibleTrialsById: Map; + private nextTrialId = 100; + + constructor(options?: { readonly trials?: readonly { readonly id: string; readonly sampleEnd: string }[] }) { + this.visibleTrialsById = new Map(); + for (const trial of options?.trials ?? [{ id: '42', sampleEnd: '2024-05-01' }]) { + this.visibleTrialsById.set(trial.id, { sampleEnd: trial.sampleEnd }); + } + } + + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + // Use `this` explicitly so receiver loss would immediately fail tests. + this.calls.push({ text, params }); + const normalized = text.trim(); + + // 1. Symbol search (`listing` + `instrument` + `exchange` + `listing_symbol_history`) + if (normalized.includes('listing_symbol_history') && normalized.includes('canonical_name')) { + return { + rows: [ + { + listing_id: 60_001, + instrument_id: 90_001, + ticker: 'ACME', + class_suffix: null, + name: 'Acme Holdings Inc', + mic: 'XNYS', + currency: 'USD', + isin: 'US0000000001', + first_bar_date: '2020-01-02', + last_bar_date: '2024-05-31', + delisted_at: null, + } as unknown as Row, + ], + }; + } + + // 2. Trial-ref visibility lookup (`SELECT 1 AS visible FROM ...trial_ledger`) + if (normalized.startsWith('SELECT 1 AS visible FROM')) { + const trialId = String(params?.[0] ?? ''); + const cutoffDate = String(params?.[1] ?? ''); + const trial = this.visibleTrialsById.get(trialId); + if (trial !== undefined && trial.sampleEnd < cutoffDate) { + return { rows: [{ visible: 1 } as unknown as Row] }; + } + return { rows: [] }; + } + + // 3. Findings insert (`INSERT INTO ...findings`) + if (normalized.startsWith('INSERT INTO') && normalized.includes('findings (')) { + const id = String(params?.[0] ?? ''); + const createdAt = String(params?.[5] ?? FIXED_NOW_ISO); + return { + rows: [{ id, created_at: createdAt } as unknown as Row], + }; + } + + // 4. Findings reader (`SELECT ... FROM ...findings`) + if (normalized.startsWith('SELECT') && normalized.includes('trial_refs') && normalized.includes('evidence_refs')) { + return { + rows: [ + { + id: 'finding-existing-01', + title: 'Short-interest drift finding', + status: 'approved', + created_at: '2024-05-10T10:00:00.000Z', + summary: 'Pre-Vault empirical finding on filing drift.', + trial_refs: ['42'], + evidence_refs: ['snap-01'], + } as unknown as Row, + ], + }; + } + + // 5. Provider caveats reader (`SELECT ... FROM ...provider_caveats`) + if (normalized.startsWith('SELECT') && normalized.includes('caveat') && normalized.includes('provider_caveats')) { + return { + rows: [ + { + id: 'caveat-eodhd-01', + provider: 'eodhd', + dataset: 'bars_1d', + caveat: 'Splits require un-adjustment before raw close storage.', + created_at: '2024-03-01T00:00:00.000Z', + } as unknown as Row, + ], + }; + } + + // 6. Listing calendar lookup (`SELECT ... e.calendar_code AS calendar_code`) + if (normalized.startsWith('SELECT') && normalized.includes('e.calendar_code AS calendar_code')) { + const requested = (params?.[0] as readonly number[] | undefined) ?? []; + return { + rows: requested.map( + listingId => + ({ + listing_id: listingId, + calendar_code: 'XNYS', + }) as unknown as Row + ), + }; + } + + // 7. Trial ledger insert (`INSERT INTO trial_ledger`) + if (normalized.startsWith('INSERT INTO trial_ledger')) { + const p = params ?? []; + const trialId = this.nextTrialId++; + const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId % 60)); + const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); + const stored: StoredTrialRow = { + trial_id: String(trialId), + created_at: createdAt, + principal_id: p[0] as string, + campaign_id: (p[1] as string | null) ?? null, + stage: p[2] as string, + universe_market: p[3] as string, + horizon_bucket: p[4] as string, + hypothesis_id: (p[5] as string | null) ?? null, + expression_hash: p[6] as string, + sample_start: p[7] as string, + sample_end: p[8] as string, + n_obs: p[9] as number, + sharpe_unann: p[10] as number, + skewness: p[11] as number, + kurtosis: p[12] as number, + daily_series: dailySeries, + }; + this.ledgerRows.push(stored); + return { + rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], + }; + } + + // 8. Trial ledger cluster/target reads (`SELECT ... FROM trial_ledger`) + if (normalized.startsWith('SELECT') && normalized.includes('FROM trial_ledger')) { + if (normalized.includes('WHERE trial_id = $1::bigint')) { + const targetId = String(params?.[0]); + const matched = this.ledgerRows.filter(r => r.trial_id === targetId); + return { rows: matched as unknown as Row[] }; + } + if (normalized.includes('WHERE universe_market = $1')) { + const market = params?.[0] as string; + const bucket = params?.[1] as string; + const matched = this.ledgerRows.filter( + r => r.universe_market === market && r.horizon_bucket === bucket + ); + return { rows: matched as unknown as Row[] }; + } + } + + throw new Error(`Unexpected SQL statement in RecordingPostgresExecutor:\n${text}`); + } +} + +async function callMcpTool( + server: McpServer, + id: number, + name: string, + args: Record +): Promise<{ readonly envelope: ToolCallEnvelope; readonly parsed: T | null }> { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'tools/call', + params: { name, arguments: args }, + }) + ); + if (raw === null) { + throw new Error(`Expected JSON-RPC response for tool "${name}", got null.`); + } + const rpc = JSON.parse(raw) as JsonRpcResponseEnvelope; + expect(rpc.error).toBeUndefined(); + const envelope = rpc.result as ToolCallEnvelope; + const text = envelope.content[0]?.text ?? ''; + if (envelope.isError === true) { + return { envelope, parsed: null }; + } + return { envelope, parsed: JSON.parse(text) as T }; +} + +function makeDefaultLibraryCards(): readonly LibraryCardRecord[] { + return [ + { + id: 'card-dsr-01', + title: 'Deflated Sharpe Ratio', + tags: ['dsr', 'rigor'], + summary: 'Adjust Sharpe ratios for multiple testing.', + body: 'Always record trials before reading results.', + }, + ]; +} + +function buildValidOptions(overrides?: { + readonly executor?: RecordingPostgresExecutor; + readonly schema?: string; + readonly vaultCutoffTs?: number; + readonly fixture?: EventStudyFixture; + readonly listLibraryCards?: KnowledgePort['listLibraryCards']; + readonly sessionDates?: SessionDatesPort; +}): { + readonly options: PostgresResearchCopilotServerOptions; + readonly executor: RecordingPostgresExecutor; + readonly fixture: EventStudyFixture; + readonly sessionDateCalls: SessionDatesQuery[]; + readonly libraryCardCalls: LibraryCardQuery[]; +} { + const fixture = overrides?.fixture ?? buildEventStudyFixture(); + const executor = overrides?.executor ?? new RecordingPostgresExecutor(); + const sessionDateCalls: SessionDatesQuery[] = []; + const libraryCardCalls: LibraryCardQuery[] = []; + + const defaultSessionDates: SessionDatesPort = { + listSessionDates(query: SessionDatesQuery) { + sessionDateCalls.push(query); + return fixture.allDates.filter(d => d >= query.fromDate && d <= query.toDate); + }, + }; + + const defaultListLibraryCards: KnowledgePort['listLibraryCards'] = async ( + q: LibraryCardQuery + ) => { + libraryCardCalls.push(q); + return makeDefaultLibraryCards(); + }; + + const base: PostgresResearchCopilotServerOptions = { + name: SERVER_NAME, + version: SERVER_VERSION, + executor, + ...(overrides?.schema !== undefined ? { schema: overrides.schema } : {}), + store: createFakeMarketDataStore(fixture), + vaultContext: { vaultCutoffTs: overrides?.vaultCutoffTs ?? fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + listLibraryCards: overrides?.listLibraryCards ?? defaultListLibraryCards, + sessionDates: overrides?.sessionDates ?? defaultSessionDates, + newId: () => FIXED_FINDING_ID, + now: () => FIXED_NOW_MS, + }; + + return { + options: base, + executor, + fixture, + sessionDateCalls, + libraryCardCalls, + }; +} + +describe('createPostgresResearchCopilotServer', () => { + test('registers all six MCP tools in RESEARCH_COPILOT_TOOL_NAMES order with zero queries at construction', () => { + const { options, executor } = buildValidOptions(); + const server = createPostgresResearchCopilotServer(options); + + expect(server.listTools().map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); + expect(executor.calls).toHaveLength(0); + }); + + test('routes search_symbols, file_finding, and read_knowledge (findings + provider_caveats) through the same executor', async () => { + const cutoffTs = Date.UTC(2024, 6, 1, 0, 0, 0, 0); // 2024-07-01 + const { options, executor } = buildValidOptions({ vaultCutoffTs: cutoffTs }); + const server = createPostgresResearchCopilotServer(options); + + // 1) search_symbols + const beforeSearch = executor.calls.length; + const searchRes = await callMcpTool(server, 1, 'search_symbols', { + query: 'ACME', + country: 'US', + includeDelisted: false, + limit: 5, + }); + expect(searchRes.envelope.isError).toBeUndefined(); + expect(searchRes.parsed?.rows).toHaveLength(1); + expect(searchRes.parsed?.rows[0]?.ticker).toBe('ACME'); + const searchCalls = executor.calls.slice(beforeSearch); + expect(searchCalls).toHaveLength(1); + // createSearchSymbolsTool always queries the port with includeDelisted: true so + // post-cutoff delistings cannot hide listings that were active as of the cutoff. + expect(searchCalls[0]?.params).toEqual(['2024-07-01', '%ACME%', 'ACME', 'US', true]); + + // 2) file_finding with trial_ledger ref '42' + const beforeFile = executor.calls.length; + const fileRes = await callMcpTool(server, 2, 'file_finding', { + kind: 'finding', + title: 'Filing drift effect', + summary: 'Pre-Vault event study shows positive post-filing drift.', + trialRefs: ['42'], + evidenceRefs: [FIXTURE_DATASET_ID], + }); + expect(fileRes.envelope.isError).toBeUndefined(); + expect(fileRes.parsed).toEqual({ + id: FIXED_FINDING_ID, + createdAt: FIXED_NOW_ISO, + created: true, + }); + const fileCalls = executor.calls.slice(beforeFile); + expect(fileCalls).toHaveLength(2); + // Visibility lookup must run before finding insert + expect(fileCalls[0]?.text).toContain('SELECT 1 AS visible FROM trial_ledger'); + expect(fileCalls[0]?.params).toEqual(['42', '2024-07-01']); + expect(fileCalls[1]?.text).toContain('INSERT INTO findings'); + expect(fileCalls[1]?.params?.[0]).toBe(FIXED_FINDING_ID); + expect(fileCalls[1]?.params?.[5]).toBe(FIXED_NOW_ISO); + + // 3) read_knowledge (findings) + const beforeFindings = executor.calls.length; + const findingsRes = await callMcpTool(server, 3, 'read_knowledge', { + source: 'findings', + query: 'drift', + }); + expect(findingsRes.envelope.isError).toBeUndefined(); + expect(findingsRes.parsed?.rows).toHaveLength(1); + expect(findingsRes.parsed?.rows[0]?.id).toBe('finding-existing-01'); + const findingsCalls = executor.calls.slice(beforeFindings); + expect(findingsCalls).toHaveLength(1); + expect(findingsCalls[0]?.text).toContain('FROM findings'); + expect(findingsCalls[0]?.params).toEqual(['%drift%']); + + // 4) read_knowledge (provider_caveats) + const beforeCaveats = executor.calls.length; + const caveatsRes = await callMcpTool(server, 4, 'read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + query: 'split', + }); + expect(caveatsRes.envelope.isError).toBeUndefined(); + expect(caveatsRes.parsed?.rows).toHaveLength(1); + expect(caveatsRes.parsed?.rows[0]?.id).toBe('caveat-eodhd-01'); + const caveatsCalls = executor.calls.slice(beforeCaveats); + expect(caveatsCalls).toHaveLength(1); + expect(caveatsCalls[0]?.text).toContain('FROM provider_caveats'); + expect(caveatsCalls[0]?.params).toEqual(['eodhd', '%split%']); + }); + + test('qualifies every schema-aware adapter table when schema is provided and leaves them unqualified when omitted', async () => { + const runAllSqlTools = async (schema?: string) => { + const fixture = buildEventStudyFixture(); + const executor = new RecordingPostgresExecutor({ + trials: [{ id: '42', sampleEnd: '2023-01-10' }], + }); + const { options } = buildValidOptions({ + executor, + fixture, + schema, + }); + const server = createPostgresResearchCopilotServer(options); + + const s1 = await callMcpTool(server, 1, 'search_symbols', { + query: 'ACME', + }); + expect(s1.envelope.isError).toBeUndefined(); + + const s2 = await callMcpTool(server, 2, 'file_finding', { + kind: 'finding', + title: 'Schema test finding', + summary: 'Verifies schema qualification across adapters.', + trialRefs: ['42'], + }); + expect(s2.envelope.isError).toBeUndefined(); + + const s3 = await callMcpTool(server, 3, 'read_knowledge', { + source: 'findings', + id: 'finding-existing-01', + }); + expect(s3.envelope.isError).toBeUndefined(); + + const s4 = await callMcpTool(server, 4, 'read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + }); + expect(s4.envelope.isError).toBeUndefined(); + + const s5 = await callMcpTool(server, 5, 'event_study', { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: fixture.lastPreCutoffDate, + event: { kinds: ['filing'], subtypes: ['8-K'] }, + preDays: 2, + postDays: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + benchmark: 'equal_weight', + }); + expect(s5.envelope.isError).toBeUndefined(); + + return executor.calls; + }; + + // With schema: 'research_x' + const qualifiedCalls = await runAllSqlTools('research_x'); + const symbolSql = qualifiedCalls.find(c => c.text.includes('listing_symbol_history'))?.text ?? ''; + expect(symbolSql).toContain('FROM "research_x".listing l'); + expect(symbolSql).toContain('INNER JOIN "research_x".instrument i'); + expect(symbolSql).toContain('INNER JOIN "research_x".exchange e'); + expect(symbolSql).toContain('FROM "research_x".listing_symbol_history h_any'); + expect(symbolSql).toContain('FROM "research_x".listing_symbol_history h_past'); + expect(symbolSql).toContain('FROM "research_x".listing_symbol_history h'); + + const trialLookupSql = + qualifiedCalls.find(c => c.text.startsWith('SELECT 1 AS visible'))?.text ?? ''; + expect(trialLookupSql).toContain('FROM "research_x".trial_ledger'); + + const findingInsertSql = + qualifiedCalls.find(c => c.text.startsWith('INSERT INTO') && c.text.includes('findings (')) + ?.text ?? ''; + expect(findingInsertSql).toContain('INSERT INTO "research_x".findings'); + + const findingsReadSql = + qualifiedCalls.find(c => c.text.startsWith('SELECT') && c.text.includes('trial_refs'))?.text ?? + ''; + expect(findingsReadSql).toContain('FROM "research_x".findings'); + + const caveatsReadSql = + qualifiedCalls.find(c => c.text.startsWith('SELECT') && c.text.includes('provider_caveats')) + ?.text ?? ''; + expect(caveatsReadSql).toContain('FROM "research_x".provider_caveats'); + + const calendarSql = + qualifiedCalls.find(c => c.text.includes('e.calendar_code AS calendar_code'))?.text ?? ''; + expect(calendarSql).toContain('FROM "research_x".listing l'); + expect(calendarSql).toContain('INNER JOIN "research_x".exchange e'); + + // Ledger SQL resolves via executor's search_path (unqualified even when schema is set) + const ledgerInsertSql = + qualifiedCalls.find(c => c.text.trim().startsWith('INSERT INTO trial_ledger'))?.text ?? ''; + expect(ledgerInsertSql).toContain('INSERT INTO trial_ledger'); + expect(ledgerInsertSql).not.toContain('"research_x".'); + + // With schema omitted + const unqualifiedCalls = await runAllSqlTools(undefined); + expect(unqualifiedCalls.length).toBeGreaterThanOrEqual(7); + for (const call of unqualifiedCalls) { + expect(call.text).not.toMatch(/"[a-z_][a-z0-9_]*"\./); + } + }); + + test('derives trial-ref visibility cutoff exclusively from vaultContext.vaultCutoffTs', async () => { + // Trial '42' ends on 2024-06-01: + // - Under cutoff 2024-06-01: sample_end < '2024-06-01' is false -> rejected with zero inserts. + // - Under cutoff 2024-07-01: sample_end < '2024-07-01' is true -> accepted and inserted. + const trialFixture = [{ id: '42', sampleEnd: '2024-06-01' }] as const; + + const blockedExecutor = new RecordingPostgresExecutor({ trials: trialFixture }); + const blockedSetup = buildValidOptions({ + executor: blockedExecutor, + vaultCutoffTs: Date.UTC(2024, 5, 1, 0, 0, 0, 0), // 2024-06-01 + }); + const blockedServer = createPostgresResearchCopilotServer(blockedSetup.options); + + const blockedRes = await callMcpTool(blockedServer, 1, 'file_finding', { + kind: 'finding', + title: 'Holdout-boundary trial', + summary: 'Must be rejected when sample_end equals cutoff.', + trialRefs: ['42'], + }); + expect(blockedRes.envelope.isError).toBe(true); + expect(blockedExecutor.calls).toHaveLength(1); + expect(blockedExecutor.calls[0]?.text).toContain('sample_end < $2::date'); + expect(blockedExecutor.calls[0]?.params).toEqual(['42', '2024-06-01']); + + const allowedExecutor = new RecordingPostgresExecutor({ trials: trialFixture }); + const allowedSetup = buildValidOptions({ + executor: allowedExecutor, + vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0), // 2024-07-01 + }); + const allowedServer = createPostgresResearchCopilotServer(allowedSetup.options); + + const allowedRes = await callMcpTool(allowedServer, 2, 'file_finding', { + kind: 'finding', + title: 'Pre-cutoff trial', + summary: 'Allowed once cutoff moves past sample_end.', + trialRefs: ['42'], + }); + expect(allowedRes.envelope.isError).toBeUndefined(); + expect(allowedRes.parsed?.created).toBe(true); + expect(allowedExecutor.calls).toHaveLength(2); + expect(allowedExecutor.calls[0]?.text).toContain('sample_end < $2::date'); + expect(allowedExecutor.calls[0]?.params).toEqual(['42', '2024-07-01']); + expect(allowedExecutor.calls[1]?.text).toContain('INSERT INTO findings'); + }); + + test('isolates library reads from PostgreSQL and prevents smuggling listFindings or listProviderCaveats', async () => { + const libraryCalls: LibraryCardQuery[] = []; + let smuggledFindingsCalled = false; + let smuggledCaveatsCalled = false; + + const baseLibraryFn: KnowledgePort['listLibraryCards'] = async (q: LibraryCardQuery) => { + libraryCalls.push(q); + return makeDefaultLibraryCards(); + }; + + const smuggledFn = Object.assign(baseLibraryFn, { + listFindings: async () => { + smuggledFindingsCalled = true; + throw new Error('Smuggled listFindings must never be called'); + }, + listProviderCaveats: async () => { + smuggledCaveatsCalled = true; + throw new Error('Smuggled listProviderCaveats must never be called'); + }, + }); + + const { options, executor } = buildValidOptions({ listLibraryCards: smuggledFn }); + const server = createPostgresResearchCopilotServer(options); + + // source: 'library' -> calls injected listLibraryCards and issues zero executor queries + const libRes = await callMcpTool(server, 1, 'read_knowledge', { + source: 'library', + query: 'Sharpe', + }); + expect(libRes.envelope.isError).toBeUndefined(); + expect(libRes.parsed?.rows).toHaveLength(1); + expect(libRes.parsed?.rows[0]?.id).toBe('card-dsr-01'); + expect(libraryCalls).toHaveLength(1); + expect(executor.calls).toHaveLength(0); + + // source: 'findings' -> uses PostgreSQL reader, never calls smuggled property + const findingsRes = await callMcpTool(server, 2, 'read_knowledge', { + source: 'findings', + }); + expect(findingsRes.envelope.isError).toBeUndefined(); + expect(findingsRes.parsed?.rows[0]?.id).toBe('finding-existing-01'); + expect(smuggledFindingsCalled).toBe(false); + + // source: 'provider_caveats' -> uses PostgreSQL reader, never calls smuggled property + const caveatsRes = await callMcpTool(server, 3, 'read_knowledge', { + source: 'provider_caveats', + }); + expect(caveatsRes.envelope.isError).toBeUndefined(); + expect(caveatsRes.parsed?.rows[0]?.id).toBe('caveat-eodhd-01'); + expect(smuggledCaveatsCalled).toBe(false); + expect(executor.calls).toHaveLength(2); + }); + + test('wires event_study calendar resolution through shared executor and injected sessionDates and records trial under principalId', async () => { + const fixture = buildEventStudyFixture(); + const { options, executor, sessionDateCalls } = buildValidOptions({ fixture }); + const server = createPostgresResearchCopilotServer({ + ...options, + earlyCloses: { XNYS: { [fixture.firstDate]: 780 } }, + }); + + // Pass `to` past vaultCutoffDate to verify Vault clamping reaches sessionDates. + const postCutoffTo = fixture.allDates[fixture.allDates.length - 1]!; + const res = await callMcpTool(server, 1, 'event_study', { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: postCutoffTo, + event: { kinds: ['filing'], subtypes: ['8-K'] }, + preDays: 2, + postDays: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + benchmark: 'equal_weight', + }); + + expect(res.envelope.isError).toBeUndefined(); + expect(res.parsed?.status).toBe('ok'); + + // Listing-calendar query ran through the shared executor with bound listing IDs + const calendarCalls = executor.calls.filter(c => + c.text.includes('e.calendar_code AS calendar_code') + ); + expect(calendarCalls).toHaveLength(1); + expect(calendarCalls[0]?.params).toEqual([[...fixture.listingIds]]); + + // Injected sessionDates received XNYS and a Vault-clamped date range (< vaultCutoffDate) + expect(sessionDateCalls).toHaveLength(1); + expect(sessionDateCalls[0]?.calendarCode).toBe('XNYS'); + expect(sessionDateCalls[0]?.fromDate).toBe(fixture.firstDate); + expect(sessionDateCalls[0]!.toDate < fixture.vaultCutoffDate).toBe(true); + + // Trial ledger append ran through the same shared executor under AGENT_PRINCIPAL + expect(executor.ledgerRows).toHaveLength(1); + expect(executor.ledgerRows[0]?.principal_id).toBe(AGENT_PRINCIPAL); + expect(executor.ledgerRows[0]?.stage).toBe('event_study'); + expect(executor.ledgerRows[0]!.sample_end < fixture.vaultCutoffDate).toBe(true); + }); + + describe('fail-closed option validation', () => { + const invalidCases: readonly { + readonly label: string; + readonly field: string; + readonly mutate: (valid: PostgresResearchCopilotServerOptions) => unknown; + }[] = [ + { label: 'options is undefined', field: 'options', mutate: () => undefined }, + { label: 'options is null', field: 'options', mutate: () => null }, + { label: 'options is primitive', field: 'options', mutate: () => 'invalid' }, + { + label: 'executor is undefined', + field: 'executor', + mutate: valid => ({ ...valid, executor: undefined }), + }, + { + label: 'executor is null', + field: 'executor', + mutate: valid => ({ ...valid, executor: null }), + }, + { + label: 'executor missing query', + field: 'executor', + mutate: valid => ({ ...valid, executor: {} }), + }, + { + label: 'executor.query is not callable', + field: 'executor', + mutate: valid => ({ ...valid, executor: { query: 'not-a-function' } }), + }, + { + label: 'vaultContext is null', + field: 'vaultContext', + mutate: valid => ({ ...valid, vaultContext: null }), + }, + { + label: 'listLibraryCards is undefined', + field: 'listLibraryCards', + mutate: valid => ({ ...valid, listLibraryCards: undefined }), + }, + { + label: 'listLibraryCards is not callable', + field: 'listLibraryCards', + mutate: valid => ({ ...valid, listLibraryCards: {} }), + }, + { + label: 'sessionDates is undefined', + field: 'sessionDates', + mutate: valid => ({ ...valid, sessionDates: undefined }), + }, + { + label: 'sessionDates is null', + field: 'sessionDates', + mutate: valid => ({ ...valid, sessionDates: null }), + }, + { + label: 'sessionDates missing listSessionDates', + field: 'sessionDates', + mutate: valid => ({ ...valid, sessionDates: {} }), + }, + { + label: 'sessionDates.listSessionDates is not callable', + field: 'sessionDates', + mutate: valid => ({ ...valid, sessionDates: { listSessionDates: 123 } }), + }, + { + label: 'newId is undefined', + field: 'newId', + mutate: valid => ({ ...valid, newId: undefined }), + }, + { + label: 'newId is not callable', + field: 'newId', + mutate: valid => ({ ...valid, newId: 'id-1' }), + }, + { + label: 'now is undefined', + field: 'now', + mutate: valid => ({ ...valid, now: undefined }), + }, + { + label: 'now is not callable', + field: 'now', + mutate: valid => ({ ...valid, now: FIXED_NOW_MS }), + }, + ]; + + for (const testCase of invalidCases) { + test(`throws an Error naming "${testCase.field}" when ${testCase.label}`, () => { + const { options, executor } = buildValidOptions(); + const badInput = testCase.mutate(options) as PostgresResearchCopilotServerOptions; + + expect(() => createPostgresResearchCopilotServer(badInput)).toThrow( + new RegExp(testCase.field) + ); + expect(executor.calls).toHaveLength(0); + }); + } + }); +}); + +describe('createPostgresResearchCopilotServer (QA edge cases)', () => { + test('clamps event_study session-date request to exactly the last pre-cutoff session', async () => { + const fixture = buildEventStudyFixture(); + const { options, sessionDateCalls, executor } = buildValidOptions({ fixture }); + const server = createPostgresResearchCopilotServer(options); + + const res = await callMcpTool(server, 1, 'event_study', { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: fixture.allDates[fixture.allDates.length - 1]!, + event: { kinds: ['filing'], subtypes: ['8-K'] }, + preDays: 2, + postDays: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + benchmark: 'equal_weight', + }); + + expect(res.parsed?.status).toBe('ok'); + expect(sessionDateCalls).toHaveLength(1); + const requested = sessionDateCalls[0]!; + // Fixture pins lastPreCutoffDate (2023-02-27) as the calendar day before the cutoff + // (2023-02-28), so an off-by-one clamp that drops the final session fails here. + expect(fixture.lastPreCutoffDate).toBe('2023-02-27'); + expect(fixture.vaultCutoffDate).toBe('2023-02-28'); + expect(requested.toDate).toBe(fixture.lastPreCutoffDate); + const served = fixture.allDates.filter( + d => d >= requested.fromDate && d <= requested.toDate + ); + expect(served[served.length - 1]).toBe(fixture.lastPreCutoffDate); + expect(executor.ledgerRows[0]!.sample_end <= fixture.lastPreCutoffDate).toBe(true); + }); + + test('binds the UTC calendar date of an intraday vaultCutoffTs to trial-ref and symbol-search queries', async () => { + const intradayCutoff = Date.UTC(2024, 6, 1, 15, 30, 0, 0); // 2024-07-01T15:30Z + const executor = new RecordingPostgresExecutor({ trials: [{ id: '42', sampleEnd: '2024-06-30' }] }); + const { options } = buildValidOptions({ executor, vaultCutoffTs: intradayCutoff }); + const server = createPostgresResearchCopilotServer(options); + + await callMcpTool(server, 1, 'search_symbols', { query: 'ACME' }); + const fileRes = await callMcpTool(server, 2, 'file_finding', { + kind: 'finding', + title: 'Intraday cutoff', + summary: 'Cutoff date derivation check.', + trialRefs: ['42'], + }); + + expect(fileRes.parsed?.created).toBe(true); + expect(executor.calls[0]?.params?.[0]).toBe('2024-07-01'); + expect(executor.calls[1]?.params).toEqual(['42', '2024-07-01']); + }); + + test('rejects unknown and non-canonical trial refs without inserting a finding', async () => { + const executor = new RecordingPostgresExecutor(); + const { options } = buildValidOptions({ + executor, + vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0), + }); + const server = createPostgresResearchCopilotServer(options); + + for (const [i, ref] of ['999', '042', '-1', 'abc'].entries()) { + const res = await callMcpTool(server, i + 1, 'file_finding', { + kind: 'finding', + title: 'Bad ref', + summary: 'Must not be filed.', + trialRefs: [ref], + }); + expect(res.envelope.isError).toBe(true); + } + expect(executor.calls.some(c => c.text.includes('INSERT INTO'))).toBe(false); + }); + + test('ignores pre-built ports and a stray vaultCutoffTs smuggled onto the options object', async () => { + const executor = new RecordingPostgresExecutor({ trials: [{ id: '42', sampleEnd: '2024-06-01' }] }); + const { options } = buildValidOptions({ + executor, + vaultCutoffTs: Date.UTC(2024, 5, 1, 0, 0, 0, 0), // 2024-06-01: trial 42 is Vault-only + }); + let smuggledUsed = false; + const smuggled = { + ...options, + vaultCutoffTs: Date.UTC(2030, 0, 1), + ledger: { query: async () => { smuggledUsed = true; return { rows: [] }; } }, + fileFinding: { + trialLookup: { hasResearchVisibleTrial: async () => { smuggledUsed = true; return true; } }, + }, + } as unknown as PostgresResearchCopilotServerOptions; + const server = createPostgresResearchCopilotServer(smuggled); + + const res = await callMcpTool(server, 1, 'file_finding', { + kind: 'finding', + title: 'Smuggle attempt', + summary: 'Holdout-backed trial must stay invisible.', + trialRefs: ['42'], + }); + + expect(res.envelope.isError).toBe(true); + expect(smuggledUsed).toBe(false); + expect(executor.calls).toHaveLength(1); + expect(executor.calls[0]?.params).toEqual(['42', '2024-06-01']); + }); + + test('keeps two servers isolated to their own executors', async () => { + const a = buildValidOptions(); + const b = buildValidOptions(); + const serverA = createPostgresResearchCopilotServer(a.options); + createPostgresResearchCopilotServer(b.options); + + await callMcpTool(serverA, 1, 'search_symbols', { query: 'ACME' }); + + expect(a.executor.calls).toHaveLength(1); + expect(b.executor.calls).toHaveLength(0); + }); + + test('lists tools over JSON-RPC tools/list in RESEARCH_COPILOT_TOOL_NAMES order', async () => { + const { options, executor } = buildValidOptions(); + const server = createPostgresResearchCopilotServer(options); + + const raw = await server.handleMessage( + JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) + ); + const rpc = JSON.parse(raw!) as { result: { tools: { name: string }[] } }; + + expect(rpc.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); + expect(executor.calls).toHaveLength(0); + }); + + test.each([ + ['uppercase schema', { schema: 'Research_X' }], + ['quoted schema injection', { schema: 'x"; DROP TABLE findings; --' }], + ['NaN vault cutoff', { vaultCutoffTs: Number.NaN }], + ] as const)('fails closed at construction with zero queries for %s', (_label, override) => { + const { options, executor } = buildValidOptions(); + const bad = { + ...options, + ...('schema' in override ? { schema: override.schema } : {}), + ...('vaultCutoffTs' in override + ? { vaultContext: { vaultCutoffTs: override.vaultCutoffTs } } + : {}), + }; + + expect(() => createPostgresResearchCopilotServer(bad)).toThrow(); + expect(executor.calls).toHaveLength(0); + }); +}); diff --git a/libs/research/test/mcp-stdio-host-qa.test.ts b/libs/research/test/mcp-stdio-host-qa.test.ts new file mode 100644 index 00000000..5933b196 --- /dev/null +++ b/libs/research/test/mcp-stdio-host-qa.test.ts @@ -0,0 +1,496 @@ +import { describe, expect, test } from 'bun:test'; +import type { BarBatch, BarQuery, MarketDataStore, Table } from '../src/market-data-store'; +import { + EVENTS_COLUMNS, + MarketDataStoreNotImplementedError, +} from '../src/market-data-store-duckdb'; +import { + type PostgresResearchCopilotExecutor, + type ResearchCopilotStdioHostDeps, + ResearchCopilotHostConfigError, + type StdioInput, + type StdioOutput, + parseResearchCopilotHostConfig, + runResearchCopilotStdioHost, +} from '../src/mcp/index'; + +// QA fixtures: synthetic in-memory factories and stdio only. No Postgres, +// DuckDB, filesystem, or network. Protocol/wiring checks; no strategy claims. +const FAKE_DECODED_PASSWORD = 'qa+p@ss w0rd/=?'; +const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD); +const FAKE_POSTGRES_URL = `postgresql://qa_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`; +const CUTOFF_ISO = '2025-06-01T00:00:00Z'; +const CUTOFF_MS = Date.UTC(2025, 5, 1); +const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12); + +function buildEnv( + overrides: Readonly> = {} +): Record { + return { + RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL, + RESEARCH_MCP_CURATED_ROOT: '/qa/curated', + RESEARCH_MCP_VAULT_CUTOFF_TS: CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: 'operator', + RESEARCH_MCP_LIBRARY_ROOT: '/qa/library', + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101, 102] }), + ...overrides, + }; +} + +function memoryOutput(): { readonly output: StdioOutput; readonly chunks: string[] } { + const chunks: string[] = []; + return { + chunks, + output: { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }, + }; +} + +function trackingInput(messages: readonly unknown[]): { + readonly input: StdioInput; + readonly pulled: () => number; +} { + let count = 0; + return { + pulled: () => count, + input: { + async *[Symbol.asyncIterator]() { + for (const msg of messages) { + count += 1; + yield `${JSON.stringify(msg)}\n`; + } + }, + }, + }; +} + +function recordingStore(): { readonly store: MarketDataStore; readonly barQueries: BarQuery[] } { + const barQueries: BarQuery[] = []; + const emptyEvents: Table = { columns: [...EVENTS_COLUMNS], rows: [] }; + const store: MarketDataStore = { + async *bars(q: BarQuery): AsyncIterable { + barQueries.push(q); + yield { listingId: q.listingIds[0] ?? 0, timeframe: q.timeframe, rows: [] }; + }, + async events() { + return emptyEvents; + }, + async universe() { + return []; + }, + async crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + async fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + async shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + async macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + async fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; + return { store, barQueries }; +} + +function calendarExecutor(): { + readonly executor: PostgresResearchCopilotExecutor; + readonly sql: string[]; +} { + const sql: string[] = []; + const executor: PostgresResearchCopilotExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + sql.push(text); + if (text.includes('calendar_code AS calendar_code')) { + const ids = (params?.[0] as readonly number[] | undefined) ?? []; + return { + rows: ids.map(id => ({ listing_id: id, calendar_code: 'XNYS' }) as unknown as Row), + }; + } + return { rows: [] }; + }, + }; + return { executor, sql }; +} + +function baseDeps( + overrides: Partial = {} +): ResearchCopilotStdioHostDeps { + return { + config: parseResearchCopilotHostConfig(buildEnv()), + openExecutor: () => ({ executor: calendarExecutor().executor, close: () => {} }), + openStore: () => ({ store: recordingStore().store, close: () => {} }), + createLibraryCardReader: () => ({ listLibraryCards: async () => [] }), + newId: () => 'qa-id', + now: () => FIXED_NOW_MS, + stdio: { input: trackingInput([]).input, output: memoryOutput().output }, + ...overrides, + }; +} + +async function captureRejection(run: () => Promise): Promise { + try { + await run(); + } catch (err) { + return err; + } + throw new Error('expected rejection'); +} + +function expectNoSecret(error: unknown): void { + expect(error).toBeInstanceOf(Error); + const err = error as Error & { cause?: unknown }; + for (const text of [err.message, err.stack ?? '']) { + expect(text).not.toContain(FAKE_POSTGRES_URL); + expect(text).not.toContain(FAKE_ENCODED_PASSWORD); + expect(text).not.toContain(FAKE_DECODED_PASSWORD); + } + expect(err.cause).toBeUndefined(); +} + +describe('runResearchCopilotStdioHost QA: session-date wiring', () => { + test('event_study derives session dates from the configured reference listings on the opened store, clamped below the env cutoff', async () => { + const { store, barQueries } = recordingStore(); + const { executor } = calendarExecutor(); + const sink = memoryOutput(); + const { input } = trackingInput([ + { + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { + name: 'event_study', + arguments: { + listingIds: [555], + from: '2025-05-01', + to: '2025-06-20', + event: { kinds: ['filing'] }, + preDays: 2, + postDays: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + benchmark: 'none', + }, + }, + }, + ]); + + await runResearchCopilotStdioHost( + baseDeps({ + openExecutor: () => ({ executor, close: () => {} }), + openStore: () => ({ store, close: () => {} }), + stdio: { input, output: sink.output }, + }) + ); + + expect(sink.chunks).toHaveLength(1); + const studyQuery = barQueries.find(q => q.listingIds.includes(555)); + expect(studyQuery?.scope).toBe('vault_fenced'); + + const sessionQueries = barQueries.filter(q => !q.listingIds.includes(555)); + expect(sessionQueries).toHaveLength(1); + const sessionQuery = sessionQueries[0]!; + expect([...sessionQuery.listingIds]).toEqual([101, 102]); + expect(sessionQuery.timeframe).toBe('1d'); + expect(sessionQuery.scope).not.toBe('vault_evaluation_only'); + expect(sessionQuery.to < '2025-06-01').toBe(true); + }); +}); + +describe('runResearchCopilotStdioHost QA: lifecycle edge cases', () => { + test('supports synchronous factories and synchronously throwing close(), closing in reverse order once each', async () => { + const events: string[] = []; + const err = await captureRejection(() => + runResearchCopilotStdioHost( + baseDeps({ + openExecutor: () => { + events.push('open:executor'); + return { + executor: calendarExecutor().executor, + close: () => { + events.push('close:executor'); + }, + }; + }, + openStore: () => { + events.push('open:store'); + return { + store: recordingStore().store, + close: () => { + events.push('close:store'); + throw new Error('sync store close failure'); + }, + }; + }, + }) + ) + ); + + expect((err as Error).message).toBe('sync store close failure'); + expect(events).toEqual(['open:executor', 'open:store', 'close:store', 'close:executor']); + }); + + test('synchronous throw from openStore is the rethrown original and the executor is still closed', async () => { + const storeError = new Error('sync store open failure'); + let execCloses = 0; + const sink = memoryOutput(); + const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); + + const err = await captureRejection(() => + runResearchCopilotStdioHost( + baseDeps({ + openExecutor: () => ({ + executor: calendarExecutor().executor, + close: () => { + execCloses += 1; + }, + }), + openStore: () => { + throw storeError; + }, + stdio: { input: tracker.input, output: sink.output }, + }) + ) + ); + + expect(err).toBe(storeError); + expect(execCloses).toBe(1); + expect(sink.chunks).toEqual([]); + expect(tracker.pulled()).toBe(0); + }); + + test.each([ + ['null', null], + ['missing close()', { executor: {} }], + ] as const)('invalid executor handle (%s) fails closed with no store open and no stdio', async (_label, handle) => { + let storeOpened = false; + const sink = memoryOutput(); + const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); + + const err = await captureRejection(() => + runResearchCopilotStdioHost( + baseDeps({ + openExecutor: () => handle as never, + openStore: () => { + storeOpened = true; + return { store: recordingStore().store, close: () => {} }; + }, + stdio: { input: tracker.input, output: sink.output }, + }) + ) + ); + + expect(err).toBeInstanceOf(Error); + expect(storeOpened).toBe(false); + expect(sink.chunks).toEqual([]); + expect(tracker.pulled()).toBe(0); + }); + + test('invalid store handle closes the executor and serves nothing', async () => { + let execCloses = 0; + const sink = memoryOutput(); + const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); + + const err = await captureRejection(() => + runResearchCopilotStdioHost( + baseDeps({ + openExecutor: () => ({ + executor: calendarExecutor().executor, + close: () => { + execCloses += 1; + }, + }), + openStore: () => ({ store: recordingStore().store }) as never, + stdio: { input: tracker.input, output: sink.output }, + }) + ) + ); + + expect(err).toBeInstanceOf(Error); + expect(execCloses).toBe(1); + expect(sink.chunks).toEqual([]); + expect(tracker.pulled()).toBe(0); + }); + + test('library reader without listLibraryCards closes store then executor and serves nothing', async () => { + const closes: string[] = []; + const sink = memoryOutput(); + const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); + + const err = await captureRejection(() => + runResearchCopilotStdioHost( + baseDeps({ + openExecutor: () => ({ + executor: calendarExecutor().executor, + close: () => { + closes.push('executor'); + }, + }), + openStore: () => ({ + store: recordingStore().store, + close: () => { + closes.push('store'); + }, + }), + createLibraryCardReader: () => ({}) as never, + stdio: { input: tracker.input, output: sink.output }, + }) + ) + ); + + expect(err).toBeInstanceOf(Error); + expect(closes).toEqual(['store', 'executor']); + expect(sink.chunks).toEqual([]); + expect(tracker.pulled()).toBe(0); + }); +}); + +describe('runResearchCopilotStdioHost QA: credential redaction', () => { + test('replaces a safe-message error whose cause chain carries the DSN', async () => { + const err = await captureRejection(() => + runResearchCopilotStdioHost( + baseDeps({ + openExecutor: () => { + throw new Error('connect failed', { + cause: new Error('inner', { cause: new Error(`dsn=${FAKE_POSTGRES_URL}`) }), + }); + }, + }) + ) + ); + expectNoSecret(err); + expect((err as Error).message).toContain('PostgreSQL executor'); + }); + + test('replaces an error carrying only the URL-encoded password', async () => { + const err = await captureRejection(() => + runResearchCopilotStdioHost( + baseDeps({ + createLibraryCardReader: () => { + throw new Error(`bad token ${FAKE_ENCODED_PASSWORD}`); + }, + }) + ) + ); + expectNoSecret(err); + expect((err as Error).message).toContain('library card reader'); + }); + + test('replaces an error whose message getter throws (uninspectable)', async () => { + const hostile = new Error('placeholder'); + Object.defineProperty(hostile, 'message', { + get() { + throw new Error(FAKE_DECODED_PASSWORD); + }, + }); + const err = await captureRejection(() => + runResearchCopilotStdioHost( + baseDeps({ + openStore: () => { + throw hostile; + }, + }) + ) + ); + expect(err).not.toBe(hostile); + expectNoSecret(err); + expect((err as Error).message).toContain('market data store'); + }); + + test('redacts a query-parameter password containing "+" in both decoded forms', async () => { + const config = parseResearchCopilotHostConfig( + buildEnv({ + RESEARCH_MCP_POSTGRES_URL: 'postgresql://qa_ro@127.0.0.1:5433/db?password=a+b%2Bc', + }) + ); + for (const leaked of ['a b+c', 'a+b+c', 'a+b%2Bc']) { + const err = await captureRejection(() => + runResearchCopilotStdioHost( + baseDeps({ + config, + openExecutor: () => { + throw new Error(`auth failed: ${leaked}`); + }, + }) + ) + ); + expect((err as Error).message).not.toContain(leaked); + } + }); +}); + +describe('parseResearchCopilotHostConfig QA: edge cases', () => { + test('keeps a "__proto__" calendar code as an own data property without prototype pollution', () => { + const config = parseResearchCopilotHostConfig( + buildEnv({ + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: '{"__proto__":[7],"XNYS":[101]}', + }) + ); + + expect(Object.keys(config.referenceListingIds).sort()).toEqual(['XNYS', '__proto__']); + expect(Object.getOwnPropertyDescriptor(config.referenceListingIds, '__proto__')?.value).toEqual([7]); + expect(Object.getPrototypeOf(config.referenceListingIds)).toBe(Object.prototype); + }); + + test('ignores undefined prefixed keys and differently cased look-alike keys', () => { + const config = parseResearchCopilotHostConfig( + buildEnv({ + RESEARCH_MCP_NOT_SET: undefined, + research_mcp_extra: 'x', + Research_Mcp_Extra: 'y', + }) + ); + expect(config.principalId).toBe('operator'); + }); + + test('accepts boundary early-close values (minute 1/960, dates 1976-01-01 and 2030-12-31)', () => { + const config = parseResearchCopilotHostConfig( + buildEnv({ + RESEARCH_MCP_EARLY_CLOSES: JSON.stringify({ + XNYS: { '1976-01-01': 1, '2030-12-31': 960 }, + }), + }) + ); + expect(config.earlyCloses).toEqual({ XNYS: { '1976-01-01': 1, '2030-12-31': 960 } }); + }); + + test('accepts INT32 max listing id and rejects a two-digit-year cutoff that Date.UTC would remap', () => { + expect( + parseResearchCopilotHostConfig( + buildEnv({ RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: '{"XNYS":[2147483647]}' }) + ).referenceListingIds + ).toEqual({ XNYS: [2147483647] }); + + let caught: unknown; + try { + parseResearchCopilotHostConfig( + buildEnv({ RESEARCH_MCP_VAULT_CUTOFF_TS: '0050-01-01T00:00:00Z' }) + ); + } catch (err) { + caught = err; + } + // Must never silently become 1950-01-01 (a different, earlier cutoff). + expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); + expect((caught as ResearchCopilotHostConfigError).variable).toBe( + 'RESEARCH_MCP_VAULT_CUTOFF_TS' + ); + }); + + test('parses the cutoff once and repeated parses of the same env are deterministic', () => { + const a = parseResearchCopilotHostConfig(buildEnv()); + const b = parseResearchCopilotHostConfig(buildEnv()); + expect(a).toEqual(b); + expect(a.vaultCutoffTs).toBe(CUTOFF_MS); + }); +}); diff --git a/libs/research/test/mcp-stdio-host.test.ts b/libs/research/test/mcp-stdio-host.test.ts new file mode 100644 index 00000000..3dd7cdee --- /dev/null +++ b/libs/research/test/mcp-stdio-host.test.ts @@ -0,0 +1,1206 @@ +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import type { + BarBatch, + BarQuery, + BarRecord, + MarketDataStore, +} from '../src/market-data-store'; +import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; +import { + type LibraryCardQuery, + type LibraryCardRecord, + type PostgresResearchCopilotExecutor, + RESEARCH_COPILOT_HOST_NAME, + RESEARCH_COPILOT_HOST_VERSION, + RESEARCH_COPILOT_TOOL_NAMES, + type QueryDataResultPayload, + type ReadKnowledgeResultPayload, + type ResearchCopilotHostConfig, + ResearchCopilotHostConfigError, + type StdioInput, + type StdioOutput, + parseResearchCopilotHostConfig, + runResearchCopilotStdioHost, +} from '../src/mcp/index'; + +const FAKE_DECODED_PASSWORD = 's3cr@t pass#99!'; +const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD); +const FAKE_POSTGRES_URL = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev?sslmode=disable`; +const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z'; +const VALID_CUTOFF_MS = Date.UTC(2025, 5, 1, 0, 0, 0, 0); +const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0); + +function buildValidEnv( + overrides: Readonly> = {} +): Record { + return { + PATH: '/usr/local/bin:/usr/bin', + HOME: '/tmp/fake-home', + NODE_ENV: 'test', + RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL, + RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro', + RESEARCH_MCP_CURATED_ROOT: '/mnt/data/stockbot/curated', + RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: '/mnt/data/stockbot/library', + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ + XNYS: [101, 102], + XTSE: [201], + }), + RESEARCH_MCP_EARLY_CLOSES: JSON.stringify({ + XNYS: { + '2024-11-29': 780, + '2024-12-24': 780, + }, + }), + ...overrides, + }; +} + +function assertNoCredentialLeak(error: unknown, visited: Set = new Set()): void { + expect(error).toBeInstanceOf(Error); + if (visited.has(error)) { + return; + } + visited.add(error); + const err = error as Error & { cause?: unknown; errors?: unknown }; + expect(err.message).not.toContain(FAKE_POSTGRES_URL); + expect(err.message).not.toContain(FAKE_ENCODED_PASSWORD); + expect(err.message).not.toContain(FAKE_DECODED_PASSWORD); + if (err.cause !== undefined) { + assertNoCredentialLeak(err.cause, visited); + } + if (Array.isArray(err.errors)) { + for (const nested of err.errors) { + assertNoCredentialLeak(nested, visited); + } + } +} + +function createMemoryOutput(): { + readonly output: StdioOutput; + readonly chunks: string[]; + text(): string; + jsonLines(): unknown[]; +} { + const chunks: string[] = []; + const output: StdioOutput = { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }; + return { + output, + chunks, + text: () => chunks.join(''), + jsonLines: () => { + const raw = chunks.join(''); + if (raw.length === 0) { + return []; + } + return raw + .trimEnd() + .split('\n') + .map(line => JSON.parse(line) as unknown); + }, + }; +} + +function createTrackingInput(messages: readonly unknown[]): { + readonly input: StdioInput; + readonly getPulledCount: () => number; +} { + let pulled = 0; + const input: StdioInput = { + async *[Symbol.asyncIterator]() { + for (const msg of messages) { + pulled += 1; + yield `${JSON.stringify(msg)}\n`; + } + }, + }; + return { + input, + getPulledCount: () => pulled, + }; +} + +function createFakeExecutor(): { + readonly executor: PostgresResearchCopilotExecutor; + readonly calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }>; +} { + const calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }> = []; + const executor: PostgresResearchCopilotExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return { rows: [] }; + }, + }; + return { executor, calls }; +} + +function createFakeStore( + rows: readonly BarRecord[] = [] +): { + readonly store: MarketDataStore; + readonly barQueries: BarQuery[]; +} { + const barQueries: BarQuery[] = []; + const store: MarketDataStore = { + async *bars(q: BarQuery): AsyncIterable { + barQueries.push(q); + yield { + listingId: q.listingIds[0] ?? 0, + timeframe: q.timeframe, + rows: [...rows], + }; + }, + async crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + async fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + async events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + async shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + async macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + async fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + async universe() { + return []; + }, + }; + return { store, barQueries }; +} + +describe('parseResearchCopilotHostConfig', () => { + test('parses a complete valid env with optionals and ignores unrelated env keys', () => { + const config = parseResearchCopilotHostConfig(buildValidEnv()); + + expect(config).toEqual({ + postgresUrl: FAKE_POSTGRES_URL, + postgresSchema: 'research_ro', + curatedRoot: '/mnt/data/stockbot/curated', + vaultCutoffTs: VALID_CUTOFF_MS, + principalId: VALID_AGENT_PRINCIPAL, + libraryRoot: '/mnt/data/stockbot/library', + referenceListingIds: { + XNYS: [101, 102], + XTSE: [201], + }, + earlyCloses: { + XNYS: { + '2024-11-29': 780, + '2024-12-24': 780, + }, + }, + }); + }); + + test('supports omitted optional variables, operator principal, postgres:// scheme, and millisecond UTC instants', () => { + const env = buildValidEnv({ + RESEARCH_MCP_POSTGRES_URL: 'postgres://user:pass@localhost:5432/db', + RESEARCH_MCP_POSTGRES_SCHEMA: undefined, + RESEARCH_MCP_VAULT_CUTOFF_TS: '2025-06-01T13:30:45.250Z', + RESEARCH_MCP_PRINCIPAL_ID: 'operator', + RESEARCH_MCP_EARLY_CLOSES: undefined, + }); + + const config = parseResearchCopilotHostConfig(env); + + expect(config.postgresUrl).toBe('postgres://user:pass@localhost:5432/db'); + expect(config.postgresSchema).toBeUndefined(); + expect('postgresSchema' in config).toBe(false); + expect(config.earlyCloses).toBeUndefined(); + expect('earlyCloses' in config).toBe(false); + expect(config.principalId).toBe('operator'); + expect(config.vaultCutoffTs).toBe(Date.UTC(2025, 5, 1, 13, 30, 45, 250)); + }); + + test.each([ + 'RESEARCH_MCP_POSTGRES_URL', + 'RESEARCH_MCP_CURATED_ROOT', + 'RESEARCH_MCP_VAULT_CUTOFF_TS', + 'RESEARCH_MCP_PRINCIPAL_ID', + 'RESEARCH_MCP_LIBRARY_ROOT', + 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS', + ] as const)('rejects missing required variable %s', variable => { + const env = buildValidEnv({ [variable]: undefined }); + let caught: unknown; + try { + parseResearchCopilotHostConfig(env); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); + const err = caught as ResearchCopilotHostConfigError; + expect(err.variable).toBe(variable); + expect(err.message).toContain(variable); + assertNoCredentialLeak(err); + }); + + test.each([ + 'RESEARCH_MCP_POSTGRES_URL', + 'RESEARCH_MCP_POSTGRES_SCHEMA', + 'RESEARCH_MCP_CURATED_ROOT', + 'RESEARCH_MCP_VAULT_CUTOFF_TS', + 'RESEARCH_MCP_PRINCIPAL_ID', + 'RESEARCH_MCP_LIBRARY_ROOT', + 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS', + 'RESEARCH_MCP_EARLY_CLOSES', + ] as const)('rejects empty and whitespace-only values for %s', variable => { + for (const blank of ['', ' \t\n ']) { + const env = buildValidEnv({ [variable]: blank }); + let caught: unknown; + try { + parseResearchCopilotHostConfig(env); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); + const err = caught as ResearchCopilotHostConfigError; + expect(err.variable).toBe(variable); + expect(err.message).toContain(variable); + assertNoCredentialLeak(err); + } + }); + + test.each([ + ['unknown prefixed key with value', 'RESEARCH_MCP_EXTRA', 'enabled'], + ['unknown prefixed key with empty string', 'RESEARCH_MCP_UNKNOWN_FLAG', ''], + ] as const)('rejects %s', (_label, key, value) => { + const env = buildValidEnv({ [key]: value }); + let caught: unknown; + try { + parseResearchCopilotHostConfig(env); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); + const err = caught as ResearchCopilotHostConfigError; + expect(err.variable).toBe(key); + expect(err.message).toContain(key); + assertNoCredentialLeak(err); + }); + + test.each([ + ['non-postgres scheme', `http://user:${FAKE_ENCODED_PASSWORD}@localhost:5432/db`], + ['missing host', `postgresql://user:${FAKE_ENCODED_PASSWORD}@/db`], + ['malformed URL', `not-a-url-${FAKE_DECODED_PASSWORD}`], + ['surrounding whitespace', ` ${FAKE_POSTGRES_URL} `], + ['invalid percent-encoding in password', 'postgresql://research_ro:%FF@127.0.0.1:5433/db'], + ['invalid percent-encoding in username', 'postgresql://user%FF:pass@127.0.0.1:5433/db'], + ] as const)('rejects invalid POSTGRES_URL (%s) without leaking URL or password', (_label, badUrl) => { + const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: badUrl }); + let caught: unknown; + try { + parseResearchCopilotHostConfig(env); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); + const err = caught as ResearchCopilotHostConfigError; + expect(err.variable).toBe('RESEARCH_MCP_POSTGRES_URL'); + expect(err.message).toContain('RESEARCH_MCP_POSTGRES_URL'); + expect(err.message).not.toContain(badUrl); + assertNoCredentialLeak(err); + }); + + test.each([ + ['uppercase', 'Research_RO'], + ['leading digit', '1schema'], + ['hyphen', 'research-ro'], + ['SQL injection', 'public"; DROP TABLE findings; --'], + ] as const)('rejects invalid POSTGRES_SCHEMA (%s)', (_label, badSchema) => { + const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_SCHEMA: badSchema }); + let caught: unknown; + try { + parseResearchCopilotHostConfig(env); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); + const err = caught as ResearchCopilotHostConfigError; + expect(err.variable).toBe('RESEARCH_MCP_POSTGRES_SCHEMA'); + expect(err.message).toContain('RESEARCH_MCP_POSTGRES_SCHEMA'); + expect(err.message).not.toContain(badSchema); + assertNoCredentialLeak(err); + }); + + test.each([ + ['bare uuid', '11111111-2222-4333-8444-555555555555'], + ['uppercase agent uuid', 'agent:11111111-2222-4333-8444-55555555555A'], + ['invalid uuid version 0', 'agent:11111111-2222-0333-8444-555555555555'], + ['invalid uuid version 9', 'agent:11111111-2222-9333-8444-555555555555'], + ['invalid RFC variant', 'agent:11111111-2222-4333-0444-555555555555'], + ['unknown role', 'admin'], + ] as const)('rejects invalid PRINCIPAL_ID (%s)', (_label, badPrincipal) => { + const env = buildValidEnv({ RESEARCH_MCP_PRINCIPAL_ID: badPrincipal }); + let caught: unknown; + try { + parseResearchCopilotHostConfig(env); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); + const err = caught as ResearchCopilotHostConfigError; + expect(err.variable).toBe('RESEARCH_MCP_PRINCIPAL_ID'); + expect(err.message).toContain('RESEARCH_MCP_PRINCIPAL_ID'); + expect(err.message).not.toContain(badPrincipal); + assertNoCredentialLeak(err); + }); + + test.each([ + ['date-only string', '2025-06-01'], + ['missing seconds', '2025-06-01T00:00Z'], + ['non-UTC offset +00:00', '2025-06-01T00:00:00+00:00'], + ['non-UTC offset -05:00', '2025-06-01T00:00:00-05:00'], + ['lowercase z', '2025-06-01T00:00:00z'], + ['sub-millisecond precision', '2025-06-01T00:00:00.123456Z'], + ['impossible leap day', '2025-02-29T00:00:00Z'], + ['impossible April 31', '2025-04-31T00:00:00Z'], + ['hour 24', '2025-06-01T24:00:00Z'], + ['second 60', '2025-06-01T00:00:60Z'], + ] as const)('rejects invalid VAULT_CUTOFF_TS (%s)', (_label, badTs) => { + const env = buildValidEnv({ RESEARCH_MCP_VAULT_CUTOFF_TS: badTs }); + let caught: unknown; + try { + parseResearchCopilotHostConfig(env); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); + const err = caught as ResearchCopilotHostConfigError; + expect(err.variable).toBe('RESEARCH_MCP_VAULT_CUTOFF_TS'); + expect(err.message).toContain('RESEARCH_MCP_VAULT_CUTOFF_TS'); + expect(err.message).not.toContain(badTs); + assertNoCredentialLeak(err); + }); + + test.each([ + ['malformed JSON', '{bad-json'], + ['JSON array root', '[101, 102]'], + ['JSON null root', 'null'], + ['scalar listing ID', '{"XNYS": 101}'], + ['empty listing ID array', '{"XNYS": []}'], + ['duplicate listing IDs', '{"XNYS": [101, 101]}'], + ['zero listing ID', '{"XNYS": [0]}'], + ['negative listing ID', '{"XNYS": [-5]}'], + ['float listing ID', '{"XNYS": [10.5]}'], + ['INT32 overflow', '{"XNYS": [2147483648]}'], + ['string listing ID', '{"XNYS": ["101"]}'], + ['untrimmed calendar code', '{" XNYS ": [101]}'], + ['blank calendar code', '{"": [101]}'], + ] as const)('rejects invalid SESSION_REFERENCE_LISTINGS (%s)', (_label, badJson) => { + const env = buildValidEnv({ RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: badJson }); + let caught: unknown; + try { + parseResearchCopilotHostConfig(env); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); + const err = caught as ResearchCopilotHostConfigError; + expect(err.variable).toBe('RESEARCH_MCP_SESSION_REFERENCE_LISTINGS'); + expect(err.message).toContain('RESEARCH_MCP_SESSION_REFERENCE_LISTINGS'); + assertNoCredentialLeak(err); + }); + + test.each([ + ['malformed JSON', '{bad-json'], + ['JSON array root', '[]'], + ['JSON null root', 'null'], + ['non-object calendar entry', '{"XNYS": [780]}'], + ['untrimmed calendar code', '{" XNYS": {"2024-11-29": 780}}'], + ['impossible calendar date', '{"XNYS": {"2024-02-30": 780}}'], + ['date below supported range', '{"XNYS": {"1975-12-31": 780}}'], + ['date above supported range', '{"XNYS": {"2031-01-01": 780}}'], + ['minute 0 (below min 1)', '{"XNYS": {"2024-11-29": 0}}'], + ['negative minute', '{"XNYS": {"2024-11-29": -10}}'], + ['minute 961 (above max 960)', '{"XNYS": {"2024-11-29": 961}}'], + ['fractional minute', '{"XNYS": {"2024-11-29": 780.5}}'], + ['string minute', '{"XNYS": {"2024-11-29": "780"}}'], + ] as const)('rejects invalid EARLY_CLOSES (%s)', (_label, badJson) => { + const env = buildValidEnv({ RESEARCH_MCP_EARLY_CLOSES: badJson }); + let caught: unknown; + try { + parseResearchCopilotHostConfig(env); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); + const err = caught as ResearchCopilotHostConfigError; + expect(err.variable).toBe('RESEARCH_MCP_EARLY_CLOSES'); + expect(err.message).toContain('RESEARCH_MCP_EARLY_CLOSES'); + assertNoCredentialLeak(err); + }); +}); + +describe('runResearchCopilotStdioHost', () => { + test('serves initialize, tools/list (exact 6 tools in order), and read_knowledge (library) with zero SQL calls', async () => { + const config = parseResearchCopilotHostConfig(buildValidEnv()); + const fakeExec = createFakeExecutor(); + const fakeStore = createFakeStore(); + const expectedCard: LibraryCardRecord = { + id: 'card-short-squeeze-01', + title: 'Canadian Short Interest Spike', + summary: 'Synthetic fixture card for stdio host wiring verification.', + body: 'Full body text for the synthetic short interest library card.', + tags: ['shorts', 'ca'], + }; + + class StatefulLibraryCardReader { + readonly queries: LibraryCardQuery[] = []; + private readonly cards: readonly LibraryCardRecord[]; + + constructor(cards: readonly LibraryCardRecord[]) { + this.cards = cards; + } + + async listLibraryCards(q: LibraryCardQuery): Promise { + this.queries.push(q); + return [...this.cards]; + } + } + + const reader = new StatefulLibraryCardReader([expectedCard]); + const sink = createMemoryOutput(); + const { input } = createTrackingInput([ + { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2024-11-05', + capabilities: {}, + clientInfo: { name: 'test-client', version: '1.0.0' }, + }, + }, + { + jsonrpc: '2.0', + method: 'notifications/initialized', + }, + { + jsonrpc: '2.0', + id: 2, + method: 'tools/list', + }, + { + jsonrpc: '2.0', + id: 3, + method: 'tools/call', + params: { + name: 'read_knowledge', + arguments: { + source: 'library', + query: 'short interest', + }, + }, + }, + ]); + + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => ({ + executor: fakeExec.executor, + close: async () => {}, + }), + openStore: async () => ({ + store: fakeStore.store, + close: async () => {}, + }), + createLibraryCardReader: async () => reader, + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input, output: sink.output }, + }); + + const responses = sink.jsonLines() as Array<{ + readonly id: number; + readonly result: Record; + }>; + expect(responses).toHaveLength(3); + + const initResp = responses[0]!; + expect(initResp.id).toBe(1); + expect(initResp.result.serverInfo).toEqual({ + name: RESEARCH_COPILOT_HOST_NAME, + version: RESEARCH_COPILOT_HOST_VERSION, + }); + + const listResp = responses[1]!; + expect(listResp.id).toBe(2); + const listedTools = listResp.result.tools as Array<{ readonly name: string }>; + expect(listedTools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); + + const callResp = responses[2]!; + expect(callResp.id).toBe(3); + const toolEnvelope = callResp.result as { + readonly isError?: boolean; + readonly content: ReadonlyArray<{ readonly type: 'text'; readonly text: string }>; + }; + expect(toolEnvelope.isError).toBeUndefined(); + const payload = JSON.parse(toolEnvelope.content[0]!.text) as ReadKnowledgeResultPayload; + expect(payload.rows).toHaveLength(1); + expect(payload.rows[0]?.source).toBe('library'); + expect(payload.rows[0]?.id).toBe(expectedCard.id); + expect(payload.rows[0]?.source === 'library' ? payload.rows[0].title : undefined).toBe( + expectedCard.title + ); + + expect(reader.queries).toHaveLength(1); + expect(fakeExec.calls).toHaveLength(0); + }); + + test('enforces the single RESEARCH_MCP_VAULT_CUTOFF_TS across query_data rejection, clamping, and row defense-in-depth', async () => { + // Pinned synthetic bar fixture (protocol check only, no strategy or return claim): + // - Cutoff from env: 2025-06-01T00:00:00Z + // - Listing 101: + // 1) Pre-cutoff bar (2025-05-30 20:00Z, knownAt 2025-05-30 20:00Z) -> included + // 2) Cutoff-ts bar (2025-06-01 00:00Z, knownAt 2025-05-30 20:00Z) -> excluded + // 3) Post-cutoff knownAt bar (2025-05-29 20:00Z, knownAt 2025-06-01 00:00Z) -> excluded + const config = parseResearchCopilotHostConfig(buildValidEnv()); + const preCutoffBar: BarRecord = { + listingId: 101, + ts: Date.UTC(2025, 4, 30, 20, 0, 0, 0), + open: 10, + high: 11, + low: 9.5, + close: 10.5, + volume: 10_000, + vwap: 10.25, + knownAt: Date.UTC(2025, 4, 30, 20, 0, 0, 0), + }; + const atCutoffTsBar: BarRecord = { + listingId: 101, + ts: VALID_CUTOFF_MS, + open: 10.5, + high: 11.5, + low: 10, + close: 11, + volume: 12_000, + vwap: 10.75, + knownAt: Date.UTC(2025, 4, 30, 20, 0, 0, 0), + }; + const atCutoffKnownAtBar: BarRecord = { + listingId: 101, + ts: Date.UTC(2025, 4, 29, 20, 0, 0, 0), + open: 9.5, + high: 10, + low: 9, + close: 9.8, + volume: 8_000, + vwap: 9.6, + knownAt: VALID_CUTOFF_MS, + }; + + const fakeExec = createFakeExecutor(); + const fakeStore = createFakeStore([preCutoffBar, atCutoffTsBar, atCutoffKnownAtBar]); + let storeFactoryConfig: ResearchCopilotHostConfig | undefined; + + const sink = createMemoryOutput(); + const { input } = createTrackingInput([ + { + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [101], + from: '2025-06-01', + to: '2025-06-05', + }, + }, + }, + { + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [101], + from: '2025-05-29', + to: '2025-06-05', + asOf: '2025-06-05', + }, + }, + }, + ]); + + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => ({ + executor: fakeExec.executor, + close: async () => {}, + }), + openStore: async cfg => { + storeFactoryConfig = cfg; + return { + store: fakeStore.store, + close: async () => {}, + }; + }, + createLibraryCardReader: async () => ({ + listLibraryCards: async () => [], + }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input, output: sink.output }, + }); + + expect(storeFactoryConfig).toBe(config); + expect(storeFactoryConfig?.vaultCutoffTs).toBe(VALID_CUTOFF_MS); + + const responses = sink.jsonLines() as Array<{ + readonly id: number; + readonly result: { + readonly isError?: boolean; + readonly content: ReadonlyArray<{ readonly type: 'text'; readonly text: string }>; + }; + }>; + expect(responses).toHaveLength(2); + + // Call 1: at/beyond cutoff -> VaultHoldoutFenceError with zero store calls. + expect(responses[0]?.result.isError).toBe(true); + expect(responses[0]?.result.content[0]?.text).toContain('VaultHoldoutFenceError'); + + // Call 2: straddling range -> clamped strictly below cutoff and post-cutoff rows dropped. + expect(fakeStore.barQueries).toHaveLength(1); + const barQuery = fakeStore.barQueries[0]!; + expect(barQuery.scope).toBe('vault_fenced'); + expect(barQuery.to).toBe('2025-05-31T23:59:59.999999Z'); + expect(barQuery.asOf).toBe('2025-05-31T23:59:59.999999Z'); + + expect(responses[1]?.result.isError).toBeUndefined(); + const payload = JSON.parse(responses[1]!.result.content[0]!.text) as QueryDataResultPayload; + expect(payload.vaultCutoffTs).toBe(VALID_CUTOFF_MS); + expect(payload.toMs).toBe(VALID_CUTOFF_MS - 1); + expect(payload.asOfMs).toBe(VALID_CUTOFF_MS - 1); + expect(payload.clampedTo).toBe(true); + expect(payload.clampedAsOf).toBe(true); + expect(payload.rows).toEqual([preCutoffBar]); + }); + + test('closes acquired resources exactly once in reverse order on normal EOF', async () => { + const config = parseResearchCopilotHostConfig(buildValidEnv()); + const fakeExec = createFakeExecutor(); + const fakeStore = createFakeStore(); + const events: string[] = []; + let execCloses = 0; + let storeCloses = 0; + + const sink = createMemoryOutput(); + const { input } = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); + + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => { + events.push('open:executor'); + return { + executor: fakeExec.executor, + close: async () => { + execCloses += 1; + events.push('close:executor'); + }, + }; + }, + openStore: async () => { + events.push('open:store'); + return { + store: fakeStore.store, + close: async () => { + storeCloses += 1; + events.push('close:store'); + }, + }; + }, + createLibraryCardReader: async () => { + events.push('open:library'); + return { + listLibraryCards: async () => [], + }; + }, + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input, output: sink.output }, + }); + + expect(events).toEqual([ + 'open:executor', + 'open:store', + 'open:library', + 'close:store', + 'close:executor', + ]); + expect(storeCloses).toBe(1); + expect(execCloses).toBe(1); + expect(sink.jsonLines()).toHaveLength(1); + }); + + test('fails closed when openExecutor rejects with zero downstream calls, zero stdout, and zero input consumed', async () => { + const config = parseResearchCopilotHostConfig(buildValidEnv()); + const safeError = new Error('PostgreSQL host unreachable'); + let storeCalled = false; + let libraryCalled = false; + + const sink = createMemoryOutput(); + const tracker = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); + + let caught: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => { + throw safeError; + }, + openStore: async () => { + storeCalled = true; + return { store: createFakeStore().store, close: async () => {} }; + }, + createLibraryCardReader: async () => { + libraryCalled = true; + return { listLibraryCards: async () => [] }; + }, + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: tracker.input, output: sink.output }, + }); + } catch (err) { + caught = err; + } + + expect(caught).toBe(safeError); + expect(storeCalled).toBe(false); + expect(libraryCalled).toBe(false); + expect(sink.text()).toBe(''); + expect(tracker.getPulledCount()).toBe(0); + }); + + test('closes executor and preserves original error when openStore throws, even if executor.close throws', async () => { + const config = parseResearchCopilotHostConfig(buildValidEnv()); + const storeError = new Error('DuckDB catalog open failed'); + let execCloses = 0; + let libraryCalled = false; + + const sink = createMemoryOutput(); + const tracker = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); + + let caught: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => ({ + executor: createFakeExecutor().executor, + close: async () => { + execCloses += 1; + throw new Error('secondary executor close failure'); + }, + }), + openStore: async () => { + throw storeError; + }, + createLibraryCardReader: async () => { + libraryCalled = true; + return { listLibraryCards: async () => [] }; + }, + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: tracker.input, output: sink.output }, + }); + } catch (err) { + caught = err; + } + + expect(caught).toBe(storeError); + expect(execCloses).toBe(1); + expect(libraryCalled).toBe(false); + expect(sink.text()).toBe(''); + expect(tracker.getPulledCount()).toBe(0); + }); + + test('closes store then executor and preserves original error when createLibraryCardReader throws, even if both closes throw', async () => { + const config = parseResearchCopilotHostConfig(buildValidEnv()); + const libraryError = new Error('library.yml unreadable'); + const closeOrder: string[] = []; + + const sink = createMemoryOutput(); + const tracker = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); + + let caught: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => ({ + executor: createFakeExecutor().executor, + close: async () => { + closeOrder.push('executor'); + throw new Error('executor close failed'); + }, + }), + openStore: async () => ({ + store: createFakeStore().store, + close: async () => { + closeOrder.push('store'); + throw new Error('store close failed'); + }, + }), + createLibraryCardReader: async () => { + throw libraryError; + }, + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: tracker.input, output: sink.output }, + }); + } catch (err) { + caught = err; + } + + expect(caught).toBe(libraryError); + expect(closeOrder).toEqual(['store', 'executor']); + expect(sink.text()).toBe(''); + expect(tracker.getPulledCount()).toBe(0); + }); + + test('closes both resources in reverse order and preserves transport error when stdio input or output throws', async () => { + const config = parseResearchCopilotHostConfig(buildValidEnv()); + + // Case 1: throwing input stream + const inputError = new Error('stdin read reset'); + const inputCloseOrder: string[] = []; + const failingInput: StdioInput = { + async *[Symbol.asyncIterator]() { + yield `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\n`; + throw inputError; + }, + }; + + let caughtInput: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => ({ + executor: createFakeExecutor().executor, + close: async () => { + inputCloseOrder.push('executor'); + }, + }), + openStore: async () => ({ + store: createFakeStore().store, + close: async () => { + inputCloseOrder.push('store'); + throw new Error('close error masked by primary'); + }, + }), + createLibraryCardReader: async () => ({ + listLibraryCards: async () => [], + }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: failingInput, output: createMemoryOutput().output }, + }); + } catch (err) { + caughtInput = err; + } + expect(caughtInput).toBe(inputError); + expect(inputCloseOrder).toEqual(['store', 'executor']); + + // Case 2: throwing output stream + const outputError = new Error('stdout broken pipe'); + const outputCloseOrder: string[] = []; + const failingOutput: StdioOutput = { + write() { + throw outputError; + }, + }; + + let caughtOutput: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => ({ + executor: createFakeExecutor().executor, + close: async () => { + outputCloseOrder.push('executor'); + }, + }), + openStore: async () => ({ + store: createFakeStore().store, + close: async () => { + outputCloseOrder.push('store'); + }, + }), + createLibraryCardReader: async () => ({ + listLibraryCards: async () => [], + }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { + input: createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]).input, + output: failingOutput, + }, + }); + } catch (err) { + caughtOutput = err; + } + expect(caughtOutput).toBe(outputError); + expect(outputCloseOrder).toEqual(['store', 'executor']); + }); + + test('attempts both closes after EOF and reports the first close failure when both fail', async () => { + const config = parseResearchCopilotHostConfig(buildValidEnv()); + const storeCloseError = new Error('store flush failed'); + const execCloseError = new Error('pool drain failed'); + const closeOrder: string[] = []; + + let caught: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => ({ + executor: createFakeExecutor().executor, + close: async () => { + closeOrder.push('executor'); + throw execCloseError; + }, + }), + openStore: async () => ({ + store: createFakeStore().store, + close: async () => { + closeOrder.push('store'); + throw storeCloseError; + }, + }), + createLibraryCardReader: async () => ({ + listLibraryCards: async () => [], + }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { + input: createTrackingInput([]).input, + output: createMemoryOutput().output, + }, + }); + } catch (err) { + caught = err; + } + + expect(closeOrder).toEqual(['store', 'executor']); + expect(caught).toBe(storeCloseError); + }); + + test('replaces startup and cleanup errors containing the full URL, decoded password, or uninspectable values with fixed stage errors and no cause', async () => { + const config = parseResearchCopilotHostConfig(buildValidEnv()); + + // 1. Startup error containing full DSN + let caughtDsn: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => { + throw new Error(`connect failed for ${FAKE_POSTGRES_URL}`); + }, + openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, + }); + } catch (err) { + caughtDsn = err; + } + assertNoCredentialLeak(caughtDsn); + expect((caughtDsn as Error & { cause?: unknown }).cause).toBeUndefined(); + expect((caughtDsn as Error).message).toContain('executor'); + + // 2. Startup error containing decoded password by itself + let caughtPass: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => ({ + executor: createFakeExecutor().executor, + close: async () => {}, + }), + openStore: async () => { + throw new Error(`auth rejected password "${FAKE_DECODED_PASSWORD}"`); + }, + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, + }); + } catch (err) { + caughtPass = err; + } + assertNoCredentialLeak(caughtPass); + expect((caughtPass as Error & { cause?: unknown }).cause).toBeUndefined(); + expect((caughtPass as Error).message).toContain('market data store'); + + // 3. Cleanup error containing decoded password after EOF + let caughtClose: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => ({ + executor: createFakeExecutor().executor, + close: async () => { + throw new Error(`disconnect error for ${FAKE_DECODED_PASSWORD}`); + }, + }), + openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, + }); + } catch (err) { + caughtClose = err; + } + assertNoCredentialLeak(caughtClose); + expect((caughtClose as Error & { cause?: unknown }).cause).toBeUndefined(); + expect((caughtClose as Error).message).toContain('closing host resources'); + + // 4. Uninspectable non-Error rejection containing raw secret + let caughtRaw: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => { + throw `raw-string-${FAKE_DECODED_PASSWORD}`; + }, + openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, + }); + } catch (err) { + caughtRaw = err; + } + assertNoCredentialLeak(caughtRaw); + expect((caughtRaw as Error & { cause?: unknown }).cause).toBeUndefined(); + }); + + test('redacts decoded password supplied via DSN query parameter', async () => { + const queryPasswordDsn = `postgresql://research_ro@127.0.0.1:5433/trading_bot_dev?sslmode=disable&password=${FAKE_ENCODED_PASSWORD}`; + const config = parseResearchCopilotHostConfig( + buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: queryPasswordDsn }) + ); + + let caught: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => { + throw new Error(`password authentication failed for "${FAKE_DECODED_PASSWORD}"`); + }, + openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, + }); + } catch (err) { + caught = err; + } + + assertNoCredentialLeak(caught); + expect((caught as Error).message).not.toContain(queryPasswordDsn); + expect((caught as Error).message).toContain('executor'); + expect((caught as Error & { cause?: unknown }).cause).toBeUndefined(); + }); + + test('replaces AggregateError containing nested credentials while preserving safe AggregateError', async () => { + const config = parseResearchCopilotHostConfig(buildValidEnv()); + + // 1. Unsafe AggregateError with nested DSN + let caughtUnsafe: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => { + throw new AggregateError( + [ + new Error('primary host timed out'), + new Error(`replica connect failed for ${FAKE_POSTGRES_URL}`), + ], + 'All database endpoints failed' + ); + }, + openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, + }); + } catch (err) { + caughtUnsafe = err; + } + + assertNoCredentialLeak(caughtUnsafe); + expect(caughtUnsafe).not.toBeInstanceOf(AggregateError); + expect((caughtUnsafe as Error).message).toContain('executor'); + expect((caughtUnsafe as Error & { cause?: unknown }).cause).toBeUndefined(); + + // 2. Safe AggregateError is preserved by identity + const safeAggregate = new AggregateError( + [new Error('primary host timed out'), new Error('replica refused connection')], + 'All database endpoints failed' + ); + let caughtSafe: unknown; + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: async () => { + throw safeAggregate; + }, + openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, + }); + } catch (err) { + caughtSafe = err; + } + + expect(caughtSafe).toBe(safeAggregate); + }); +}); + +describe('stdio-host dependency-free source invariants', () => { + test('contains no bare process access and no pg, node:*, or DuckDB imports', () => { + const src = readFileSync(new URL('../src/mcp/host/stdio-host.ts', import.meta.url), 'utf8'); + expect(src).not.toMatch(/\bprocess\./); + expect(src).not.toMatch(/from\s+['"]node:/); + expect(src).not.toMatch(/require\s*\(\s*['"]node:/); + expect(src).not.toMatch(/from\s+['"]pg(?:\/|['"])/); + expect(src).not.toMatch(/require\s*\(\s*['"]pg(?:\/|['"])/); + expect(src).not.toMatch(/from\s+['"][^'"]*duckdb/i); + expect(src).not.toMatch(/require\s*\(\s*['"][^'"]*duckdb/i); + }); +}); diff --git a/libs/research/test/notebook-snapshot-qa.test.ts b/libs/research/test/notebook-snapshot-qa.test.ts new file mode 100644 index 00000000..e9f01e18 --- /dev/null +++ b/libs/research/test/notebook-snapshot-qa.test.ts @@ -0,0 +1,615 @@ +import { createHash } from 'node:crypto'; +import { describe, expect, test } from 'bun:test'; +import { + exportNotebookSnapshot, + NotebookSnapshotError, + type ExportNotebookSnapshotOptions, + type NotebookCommandResult, + type NotebookCommandRunner, + type NotebookSnapshotFileStat, + type NotebookSnapshotFs, +} from '../src/notebook-snapshot'; + +// QA coverage for T-177 beyond the programmer's unit tests: fail-at-call-N fault +// injection across every port call, realistic marimo 0.26.0 report payloads +// (shapes taken from marimo/_lint/formatters/json.py, _lint/linter.py and +// _cli/cli.py `check`, which echoes JSON with a trailing newline), temp-name +// collisions, path normalization, and option validation. Fakes only; no real +// marimo process is ever spawned. + +const NOTEBOOK = '/work/notebooks/study.py'; +const OUTPUT = '/work/out/study.html'; +const ORIGINAL_SNAPSHOT = 'original-snapshot'; +const NEW_SNAPSHOT = 'new-snapshot — €'; +const TEMP_MARKER = '.marimo-snapshot-'; + +type PortOp = + | 'fs.stat' + | 'fs.createExclusive' + | 'fs.readBytes' + | 'fs.rename' + | 'fs.remove' + | 'runner.check' + | 'runner.export'; + +function errWithCode(code: string, message = code): Error & { code: string } { + const err = new Error(message) as Error & { code: string }; + err.code = code; + return err; +} + +/** + * In-memory fs + runner pair sharing one ordered port-call log. `failAt` makes + * the Nth port call throw EIO; `failPersistently` makes every later call throw too. + */ +class FaultyPorts { + readonly files = new Map(); + readonly ops: PortOp[] = []; + readonly runnerArgs: string[][] = []; + failAt = 0; + failPersistently = false; + checkStdout = ''; + exportBytes: Uint8Array = new TextEncoder().encode(NEW_SNAPSHOT); + createExclusiveHook: ((path: string, attempt: number) => void) | null = null; + private createAttempts = 0; + + constructor() { + this.files.set(NOTEBOOK, { isFile: true, bytes: new TextEncoder().encode('import marimo\n') }); + this.files.set(OUTPUT, { isFile: true, bytes: new TextEncoder().encode(ORIGINAL_SNAPSHOT) }); + } + + private tick(op: PortOp): void { + this.ops.push(op); + const n = this.ops.length; + if (this.failAt > 0 && (n === this.failAt || (this.failPersistently && n > this.failAt))) { + throw errWithCode('EIO', `injected EIO at port call ${n} (${op})`); + } + } + + text(path: string): string | undefined { + const entry = this.files.get(path); + return entry ? new TextDecoder().decode(entry.bytes) : undefined; + } + + tempPaths(): string[] { + return [...this.files.keys()].filter(p => p.includes(TEMP_MARKER)); + } + + readonly fs: NotebookSnapshotFs = { + stat: async (path): Promise => { + this.tick('fs.stat'); + const entry = this.files.get(path); + return entry ? { isFile: entry.isFile, size: entry.bytes.byteLength } : null; + }, + createExclusive: async path => { + this.tick('fs.createExclusive'); + this.createAttempts += 1; + this.createExclusiveHook?.(path, this.createAttempts); + if (this.files.has(path)) { + throw errWithCode('EEXIST'); + } + this.files.set(path, { isFile: true, bytes: new Uint8Array(0) }); + }, + readBytes: async path => { + this.tick('fs.readBytes'); + const entry = this.files.get(path); + if (!entry) { + throw errWithCode('ENOENT'); + } + return new Uint8Array(entry.bytes); + }, + rename: async (from, to) => { + this.tick('fs.rename'); + const entry = this.files.get(from); + if (!entry) { + throw errWithCode('ENOENT'); + } + this.files.delete(from); + this.files.set(to, entry); + }, + remove: async path => { + this.tick('fs.remove'); + this.files.delete(path); + }, + }; + + readonly runner: NotebookCommandRunner = { + run: async (_command, args): Promise => { + this.runnerArgs.push([...args]); + if (args[0] === 'check') { + this.tick('runner.check'); + return { exitCode: 0, stdout: this.checkStdout, stderr: '' }; + } + this.tick('runner.export'); + const tempPath = args[args.indexOf('-o') + 1] as string; + this.files.set(tempPath, { isFile: true, bytes: this.exportBytes }); + return { exitCode: 0, stdout: '', stderr: '' }; + }, + }; + + options(extra: Partial = {}): ExportNotebookSnapshotOptions { + return { notebookPath: NOTEBOOK, outputPath: OUTPUT, runner: this.runner, fs: this.fs, ...extra }; + } +} + +async function captureSnapshotError(promise: Promise): Promise { + try { + await promise; + } catch (err) { + expect(err).toBeInstanceOf(NotebookSnapshotError); + return err as NotebookSnapshotError; + } + throw new Error('Expected NotebookSnapshotError, but the export resolved.'); +} + +function stubRunner(result: unknown): { runner: NotebookCommandRunner; calls: string[][] } { + const calls: string[][] = []; + return { + calls, + runner: { + run: async (_c, args) => { + calls.push([...args]); + return result as NotebookCommandResult; + }, + }, + }; +} + +// Realistic marimo 0.26.0 `check --format=json` stdout (click.echo appends '\n'). +function marimoCheckStdout( + issues: readonly Record[], + errored: boolean, + totalFiles = 1 +): string { + return `${JSON.stringify({ + issues, + summary: { + total_files: totalFiles, + files_with_issues: issues.length > 0 ? 1 : 0, + total_issues: issues.length, + fixed_issues: 0, + errored, + }, + })}\n`; +} + +describe('exportNotebookSnapshot QA: fail-at-call-N fault injection', () => { + const expectedByStep: ReadonlyArray<{ op: PortOp; code: NotebookSnapshotError['code'] }> = [ + { op: 'fs.stat', code: 'NOTEBOOK_NOT_FOUND' }, + { op: 'runner.check', code: 'CHECK_FAILED' }, + { op: 'fs.createExclusive', code: 'EXPORT_FAILED' }, + { op: 'runner.export', code: 'EXPORT_FAILED' }, + { op: 'fs.stat', code: 'EXPORT_FAILED' }, + { op: 'fs.readBytes', code: 'EXPORT_FAILED' }, + { op: 'fs.rename', code: 'EXPORT_FAILED' }, + ]; + + test('happy path issues exactly the expected ordered port calls', async () => { + const ports = new FaultyPorts(); + await exportNotebookSnapshot(ports.options()); + expect(ports.ops).toEqual(expectedByStep.map(s => s.op)); + }); + + for (const persistent of [false, true]) { + test(`failing port call N (${persistent ? 'and every later call' : 'only'}) fails closed with the mapped code, keeps the old snapshot, and a retry succeeds`, async () => { + for (let n = 1; n <= expectedByStep.length; n += 1) { + const ports = new FaultyPorts(); + ports.failAt = n; + ports.failPersistently = persistent; + + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); + const step = expectedByStep[n - 1]!; + + expect({ n, op: ports.ops[n - 1], code: err.code }).toEqual({ n, op: step.op, code: step.code }); + expect(err.cause).toBeDefined(); + expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); + // Export must never run once the check phase (or anything before it) failed. + if (n <= 2) { + expect(ports.runnerArgs.filter(a => a[0] === 'export')).toHaveLength(0); + expect(ports.ops).not.toContain('fs.createExclusive'); + } + if (!persistent) { + // Cleanup succeeded: no owned temp file survives any injected fault. + expect(ports.tempPaths()).toEqual([]); + if (n >= 4) { + expect(ports.ops.at(-1)).toBe('fs.remove'); + } + } + + // Retry once the fault clears publishes the new snapshot. + ports.failAt = 0; + const receipt = await exportNotebookSnapshot(ports.options()); + expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); + expect(receipt.bytes).toBe(ports.exportBytes.byteLength); + if (!persistent) { + expect(ports.tempPaths()).toEqual([]); + } + } + }); + } + + test('an extra fault index past the last port call means the export succeeds (no hidden fault points)', async () => { + const ports = new FaultyPorts(); + ports.failAt = expectedByStep.length + 1; + const receipt = await exportNotebookSnapshot(ports.options()); + expect(receipt.sha256).toBe(createHash('sha256').update(ports.exportBytes).digest('hex')); + expect(ports.tempPaths()).toEqual([]); + }); +}); + +describe('exportNotebookSnapshot QA: realistic marimo 0.26.0 check reports', () => { + test('accepts the real report shape with trailing newline and formatting/runtime diagnostics', async () => { + const ports = new FaultyPorts(); + const issues = [ + { + type: 'diagnostic', + message: 'Cell is not formatted', + filename: NOTEBOOK, + line: 3, + column: 1, + severity: 'formatting', + name: 'general-formatting', + code: 'MF001', + fixable: true, + cell_id: ['Hbol'], + }, + { + type: 'diagnostic', + message: 'Self import', + filename: NOTEBOOK, + line: 7, + column: 1, + severity: 'runtime', + name: 'self-import', + code: 'MR001', + fixable: false, + }, + ]; + ports.checkStdout = marimoCheckStdout(issues, false); + + const receipt = await exportNotebookSnapshot(ports.options()); + + expect(receipt.checkDiagnostics).toEqual(JSON.parse(ports.checkStdout)); + expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); + }); + + test('blocks export for a file-level error issue even when exit is 0 and summary.errored is false', async () => { + // marimo marks `status == "invalid"` notebooks failed without necessarily + // setting errored first; the gate must not rely on summary.errored alone. + const ports = new FaultyPorts(); + ports.checkStdout = marimoCheckStdout( + [{ type: 'error', filename: NOTEBOOK, error: `Failed to parse: ${NOTEBOOK} (not a valid notebook)` }], + false + ); + + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); + + expect(err.code).toBe('CHECK_FAILED'); + expect(ports.runnerArgs).toHaveLength(1); + expect(ports.ops).not.toContain('fs.createExclusive'); + expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); + }); + + test('blocks export for a breaking diagnostic (MB rule) on exit 0', async () => { + const ports = new FaultyPorts(); + ports.checkStdout = marimoCheckStdout( + [ + { + type: 'diagnostic', + message: "Variable 'x' is defined in multiple cells", + filename: NOTEBOOK, + line: 4, + column: 1, + severity: 'breaking', + name: 'multiple-definitions', + code: 'MB002', + fixable: false, + }, + ], + false + ); + + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); + expect(err.code).toBe('CHECK_FAILED'); + expect(ports.runnerArgs).toHaveLength(1); + }); + + test('rejects a report that checked zero files (e.g. notebook vanished before check) as CHECK_OUTPUT_INVALID', async () => { + const ports = new FaultyPorts(); + ports.checkStdout = marimoCheckStdout([], false, 0); + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); + expect(err.code).toBe('CHECK_OUTPUT_INVALID'); + expect(ports.runnerArgs).toHaveLength(1); + }); + + test('blocks a nested diagnostics entry with type "error"', async () => { + const ports = new FaultyPorts(); + ports.checkStdout = marimoCheckStdout( + [{ filename: NOTEBOOK, diagnostics: [{ type: 'error', message: 'boom' }] }], + false + ); + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); + expect(err.code).toBe('CHECK_FAILED'); + expect(ports.runnerArgs).toHaveLength(1); + }); + + test('rejects non-string severity in an issue as CHECK_OUTPUT_INVALID', async () => { + const ports = new FaultyPorts(); + ports.checkStdout = marimoCheckStdout([{ type: 'diagnostic', severity: 3 }], false); + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); + expect(err.code).toBe('CHECK_OUTPUT_INVALID'); + expect(ports.runnerArgs).toHaveLength(1); + }); + + test('receipt diagnostics are deeply frozen and detached from later mutation attempts', async () => { + const ports = new FaultyPorts(); + ports.checkStdout = marimoCheckStdout( + [{ type: 'diagnostic', severity: 'formatting', code: 'MF001', cell_id: ['a'] }], + false + ); + const receipt = await exportNotebookSnapshot(ports.options()); + const diagnostics = receipt.checkDiagnostics!; + + expect(() => { + (diagnostics.summary as { errored: boolean }).errored = true; + }).toThrow(TypeError); + expect(() => { + (diagnostics.issues as unknown[]).push({}); + }).toThrow(TypeError); + expect(() => { + (receipt as { sha256: string }).sha256 = 'x'; + }).toThrow(TypeError); + expect(diagnostics.summary.errored).toBe(false); + }); +}); + +describe('exportNotebookSnapshot QA: runner contract violations', () => { + test('non-timeout runner rejection in check maps to CHECK_FAILED with cause and never exports', async () => { + const spawnError = errWithCode('ENOENT', 'spawn marimo ENOENT'); + const calls: string[][] = []; + const ports = new FaultyPorts(); + const runner: NotebookCommandRunner = { + run: async (_c, args) => { + calls.push([...args]); + throw spawnError; + }, + }; + + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner }))); + + expect(err.code).toBe('CHECK_FAILED'); + expect(err.cause).toBe(spawnError); + expect(calls).toHaveLength(1); + expect(ports.tempPaths()).toEqual([]); + }); + + test('malformed runner results in check map to CHECK_FAILED and never export', async () => { + const malformed: unknown[] = [ + null, + 'exit 0', + { exitCode: '0', stdout: '', stderr: '' }, + { exitCode: Number.NaN, stdout: '', stderr: '' }, + { exitCode: 0.5, stdout: '', stderr: '' }, + { exitCode: 0, stderr: '' }, + { exitCode: 0, stdout: '', stderr: null }, + ]; + for (const result of malformed) { + const ports = new FaultyPorts(); + const { runner, calls } = stubRunner(result); + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner }))); + expect(err.code).toBe('CHECK_FAILED'); + expect(calls).toHaveLength(1); + expect(ports.tempPaths()).toEqual([]); + } + }); + + test('malformed runner result in export maps to EXPORT_FAILED, removes temp, and keeps destination', async () => { + const ports = new FaultyPorts(); + const runner: NotebookCommandRunner = { + run: async (_c, args) => + (args[0] === 'check' + ? { exitCode: 0, stdout: '', stderr: '' } + : { exitCode: 0, stdout: undefined, stderr: '' }) as unknown as NotebookCommandResult, + }; + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner }))); + expect(err.code).toBe('EXPORT_FAILED'); + expect(ports.tempPaths()).toEqual([]); + expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); + }); + + test('readBytes returning zero bytes despite a nonzero stat size is EXPORT_EMPTY and cleans up', async () => { + const ports = new FaultyPorts(); + const fs: NotebookSnapshotFs = { ...ports.fs, readBytes: async () => new Uint8Array(0) }; + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs }))); + expect(err.code).toBe('EXPORT_EMPTY'); + expect(ports.tempPaths()).toEqual([]); + expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); + }); + + test('temp file vanishing between stat and read (ENOENT) is EXPORT_EMPTY', async () => { + const ports = new FaultyPorts(); + const fs: NotebookSnapshotFs = { + ...ports.fs, + readBytes: async () => { + throw errWithCode('ENOENT'); + }, + }; + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs }))); + expect(err.code).toBe('EXPORT_EMPTY'); + expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); + }); + + test('notebook stat throwing ENOENT is NOTEBOOK_NOT_FOUND with zero runner calls', async () => { + const ports = new FaultyPorts(); + const fs: NotebookSnapshotFs = { + ...ports.fs, + stat: async () => { + throw errWithCode('ENOENT'); + }, + }; + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs }))); + expect(err.code).toBe('NOTEBOOK_NOT_FOUND'); + expect(ports.runnerArgs).toHaveLength(0); + }); +}); + +describe('exportNotebookSnapshot QA: temp reservation', () => { + test('retries on EEXIST collisions and exports to the first free sibling', async () => { + const ports = new FaultyPorts(); + ports.createExclusiveHook = (path, attempt) => { + if (attempt <= 3) { + ports.files.set(path, { isFile: true, bytes: new TextEncoder().encode('foreign') }); + } + }; + + await exportNotebookSnapshot(ports.options()); + + const exportArgs = ports.runnerArgs.find(a => a[0] === 'export')!; + const usedTemp = exportArgs[exportArgs.indexOf('-o') + 1]!; + expect(ports.ops.filter(op => op === 'fs.createExclusive')).toHaveLength(4); + expect(usedTemp.startsWith('/work/out/')).toBe(true); + // The three foreign colliding files are not owned and must be left alone. + expect(ports.tempPaths()).toHaveLength(3); + expect(ports.tempPaths()).not.toContain(usedTemp); + expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); + }); + + test('gives up with EXPORT_FAILED after bounded EEXIST collisions, never exports, and never removes foreign files', async () => { + const ports = new FaultyPorts(); + ports.createExclusiveHook = path => { + ports.files.set(path, { isFile: true, bytes: new TextEncoder().encode('foreign') }); + }; + + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); + + expect(err.code).toBe('EXPORT_FAILED'); + expect(ports.ops.filter(op => op === 'fs.createExclusive')).toHaveLength(16); + expect(ports.runnerArgs.filter(a => a[0] === 'export')).toHaveLength(0); + expect(ports.ops).not.toContain('fs.remove'); + expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); + }); + + test('a destination directly under / reserves its temp under / without a double slash', async () => { + const ports = new FaultyPorts(); + ports.files.set('/nb.py', { isFile: true, bytes: new TextEncoder().encode('x') }); + await exportNotebookSnapshot(ports.options({ notebookPath: '/nb.py', outputPath: '/snap.html' })); + const exportArgs = ports.runnerArgs.find(a => a[0] === 'export')!; + const temp = exportArgs[exportArgs.indexOf('-o') + 1]!; + expect(temp).toMatch(/^\/\.marimo-snapshot-[^/]+\.tmp\.html$/); + expect(ports.text('/snap.html')).toBe(NEW_SNAPSHOT); + }); +}); + +describe('exportNotebookSnapshot QA: path normalization and roots', () => { + test('passes and reports normalized paths (dot segments, duplicate slashes) to runner, fs, and receipt', async () => { + const ports = new FaultyPorts(); + const receipt = await exportNotebookSnapshot( + ports.options({ + notebookPath: '/work//notebooks/./sub/../study.py', + outputPath: '/work/out/./x/../study.html', + allowedNotebookRoot: '/work/notebooks/', + allowedOutputRoot: '/work/out', + }) + ); + expect(ports.runnerArgs[0]).toEqual(['check', '--format=json', NOTEBOOK]); + expect(ports.runnerArgs[1]?.[2]).toBe(NOTEBOOK); + expect(receipt.notebookPath).toBe(NOTEBOOK); + expect(receipt.outputPath).toBe(OUTPUT); + expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); + }); + + test('a basename starting with "-" inside an absolute path is passed as one argv element', async () => { + const ports = new FaultyPorts(); + ports.files.set('/work/notebooks/-rf.py', { isFile: true, bytes: new TextEncoder().encode('x') }); + await exportNotebookSnapshot(ports.options({ notebookPath: '/work/notebooks/-rf.py' })); + expect(ports.runnerArgs[0]).toEqual(['check', '--format=json', '/work/notebooks/-rf.py']); + }); + + test('root "/" accepts any absolute path; relative or NUL roots and relative cwd are rejected before any port call', async () => { + const ok = new FaultyPorts(); + await exportNotebookSnapshot(ok.options({ allowedNotebookRoot: '/', allowedOutputRoot: '/' })); + expect(ok.text(OUTPUT)).toBe(NEW_SNAPSHOT); + + const badExtras: Array> = [ + { allowedNotebookRoot: 'work/notebooks' }, + { allowedOutputRoot: './out' }, + { allowedOutputRoot: '/work/out\0' }, + { allowedNotebookRoot: '' }, + { cwd: 'work' }, + // Path equal to the root itself is not "inside" it. + { allowedNotebookRoot: NOTEBOOK }, + // `..` that climbs above the root after normalization. + { notebookPath: '/work/notebooks/../../work/notebooks/../x.py', allowedNotebookRoot: '/work/notebooks' }, + ]; + for (const extra of badExtras) { + const ports = new FaultyPorts(); + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options(extra))); + expect(err.code).toBe('INVALID_PATH'); + expect(ports.ops).toEqual([]); + expect(ports.runnerArgs).toEqual([]); + } + }); + + test('".." above filesystem root clamps to "/" and is still contained by roots', async () => { + const ports = new FaultyPorts(); + const err = await captureSnapshotError( + exportNotebookSnapshot( + ports.options({ notebookPath: '/../../etc/x.py', allowedNotebookRoot: '/work/notebooks' }) + ) + ); + expect(err.code).toBe('INVALID_PATH'); + expect(ports.runnerArgs).toEqual([]); + }); +}); + +describe('exportNotebookSnapshot QA: option validation', () => { + test('rejects malformed ports and options with INVALID_OPTION before any port call', async () => { + const ports = new FaultyPorts(); + const bad: Array | null> = [ + null, + { runner: undefined as unknown as NotebookCommandRunner }, + { runner: {} as NotebookCommandRunner }, + { fs: { ...ports.fs, rename: undefined } as unknown as NotebookSnapshotFs }, + { fs: { ...ports.fs, createExclusive: 'x' } as unknown as NotebookSnapshotFs }, + { timeoutMs: -1 }, + { timeoutMs: 1.5 }, + { timeoutMs: Number.NaN }, + { timeoutMs: Number.POSITIVE_INFINITY }, + { timeoutMs: '1000' as unknown as number }, + { marimoCommand: '' }, + { marimoCommand: ' ' }, + { marimoCommand: 'mar\0imo' }, + { marimoCommand: 42 as unknown as string }, + ]; + for (const extra of bad) { + const options = + extra === null ? (null as unknown as ExportNotebookSnapshotOptions) : ports.options(extra); + const err = await captureSnapshotError(exportNotebookSnapshot(options)); + expect(err.code).toBe('INVALID_OPTION'); + } + expect(ports.ops).toEqual([]); + expect(ports.runnerArgs).toEqual([]); + }); + + test('non-string notebookPath/outputPath are INVALID_PATH', async () => { + for (const extra of [ + { notebookPath: undefined as unknown as string }, + { outputPath: 7 as unknown as string }, + { notebookPath: '' }, + ]) { + const ports = new FaultyPorts(); + const err = await captureSnapshotError(exportNotebookSnapshot(ports.options(extra))); + expect(err.code).toBe('INVALID_PATH'); + expect(ports.ops).toEqual([]); + } + }); + + test('NotebookSnapshotError is a real Error subclass with stable name and code', () => { + const err = new NotebookSnapshotError('TIMEOUT', 'm', { details: { a: 1 } }); + expect(err).toBeInstanceOf(Error); + expect(err.name).toBe('NotebookSnapshotError'); + expect(err.code).toBe('TIMEOUT'); + expect(err.details).toEqual({ a: 1 }); + expect('cause' in err && err.cause !== undefined).toBe(false); + }); +}); diff --git a/libs/research/test/notebook-snapshot.test.ts b/libs/research/test/notebook-snapshot.test.ts new file mode 100644 index 00000000..3e5e31b0 --- /dev/null +++ b/libs/research/test/notebook-snapshot.test.ts @@ -0,0 +1,851 @@ +import { createHash } from 'node:crypto'; +import { describe, expect, test } from 'bun:test'; +import { exportNotebookSnapshot as barrelExportNotebookSnapshot } from '../src/index'; +import { + DEFAULT_MARIMO_COMMAND, + DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS, + exportNotebookSnapshot, + NotebookSnapshotError, + type NotebookCommandResult, + type NotebookCommandRunner, + type NotebookCommandRunOptions, + type NotebookSnapshotFileStat, + type NotebookSnapshotFs, +} from '../src/notebook-snapshot'; + +interface RecordedCall { + readonly command: string; + readonly args: readonly string[]; + readonly options: NotebookCommandRunOptions; +} + +interface FakeFsEntry { + readonly isFile: boolean; + bytes: Uint8Array; +} + +class InMemoryNotebookFs implements NotebookSnapshotFs { + readonly entries = new Map(); + readonly createdTempPaths: string[] = []; + readonly removedPaths: string[] = []; + readonly renames: Array<{ readonly from: string; readonly to: string }> = []; + failRenameError: Error | null = null; + failRemoveError: Error | null = null; + + putFile(path: string, content: string | Uint8Array): void { + const bytes = + typeof content === 'string' ? new TextEncoder().encode(content) : new Uint8Array(content); + this.entries.set(path, { isFile: true, bytes }); + } + + putDirectory(path: string): void { + this.entries.set(path, { isFile: false, bytes: new Uint8Array(0) }); + } + + getBytes(path: string): Uint8Array | undefined { + const entry = this.entries.get(path); + return entry?.isFile ? entry.bytes : undefined; + } + + getText(path: string): string | undefined { + const bytes = this.getBytes(path); + return bytes ? new TextDecoder().decode(bytes) : undefined; + } + + async stat(path: string): Promise { + const entry = this.entries.get(path); + if (!entry) { + return null; + } + return { isFile: entry.isFile, size: entry.bytes.byteLength }; + } + + async createExclusive(path: string): Promise { + if (this.entries.has(path)) { + const err = new Error(`EEXIST: file already exists '${path}'`) as Error & { code: string }; + err.code = 'EEXIST'; + throw err; + } + this.entries.set(path, { isFile: true, bytes: new Uint8Array(0) }); + this.createdTempPaths.push(path); + } + + async readBytes(path: string): Promise { + const entry = this.entries.get(path); + if (!entry || !entry.isFile) { + const err = new Error(`ENOENT: no such file '${path}'`) as Error & { code: string }; + err.code = 'ENOENT'; + throw err; + } + return new Uint8Array(entry.bytes); + } + + async rename(sourcePath: string, destinationPath: string): Promise { + if (this.failRenameError) { + throw this.failRenameError; + } + const entry = this.entries.get(sourcePath); + if (!entry) { + const err = new Error(`ENOENT: no such file '${sourcePath}'`) as Error & { code: string }; + err.code = 'ENOENT'; + throw err; + } + this.entries.delete(sourcePath); + this.entries.set(destinationPath, entry); + this.renames.push({ from: sourcePath, to: destinationPath }); + } + + async remove(path: string): Promise { + this.removedPaths.push(path); + if (this.failRemoveError) { + throw this.failRemoveError; + } + this.entries.delete(path); + } +} + +type RunnerHandler = ( + command: string, + args: readonly string[], + options: NotebookCommandRunOptions, + callIndex: number +) => Promise; + +function createRecordingRunner(handler: RunnerHandler): { + readonly runner: NotebookCommandRunner; + readonly calls: RecordedCall[]; +} { + const calls: RecordedCall[] = []; + const runner: NotebookCommandRunner = { + async run(command, args, options) { + const callIndex = calls.length; + calls.push({ command, args: [...args], options: { ...options } }); + return handler(command, args, options, callIndex); + }, + }; + return { runner, calls }; +} + +function makeTimeoutError(message = 'Command timed out'): Error & { code: string } { + const err = new Error(message) as Error & { code: string }; + err.code = 'ETIMEDOUT'; + return err; +} + +async function expectSnapshotError( + promise: Promise, + expectedCode: NotebookSnapshotError['code'] +): Promise { + try { + await promise; + } catch (err) { + expect(err).toBeInstanceOf(NotebookSnapshotError); + const snapshotErr = err as NotebookSnapshotError; + expect(snapshotErr.code).toBe(expectedCode); + return snapshotErr; + } + throw new Error(`Expected NotebookSnapshotError(${expectedCode}), but promise resolved.`); +} + +describe('exportNotebookSnapshot', () => { + test('is re-exported from the @stock-bot/research barrel', () => { + expect(barrelExportNotebookSnapshot).toBe(exportNotebookSnapshot); + }); + + test('happy path: runs check then export html with exact argv, publishes via sibling temp rename, and returns frozen receipt with exact non-ASCII bytes and sha256', async () => { + const fs = new InMemoryNotebookFs(); + const notebookPath = '/workspace/research/notebooks/study.py'; + const outputPath = '/workspace/artifacts/study.html'; + fs.putFile(notebookPath, 'import marimo\n'); + + const nonAsciiHtml = + '

CA Shorts — €100 / 日本語

'; + const expectedBytes = new TextEncoder().encode(nonAsciiHtml); + const expectedSha256 = createHash('sha256').update(expectedBytes).digest('hex'); + + const cleanReport = { + issues: [], + summary: { errored: false, total_files: 1 }, + }; + + const { runner, calls } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: JSON.stringify(cleanReport), stderr: '' }; + } + const outFlagIdx = args.indexOf('-o'); + const tempPath = args[outFlagIdx + 1] as string; + fs.putFile(tempPath, expectedBytes); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const receipt = await exportNotebookSnapshot({ + notebookPath, + outputPath, + runner, + fs, + allowedNotebookRoot: '/workspace/research/notebooks', + allowedOutputRoot: '/workspace/artifacts', + }); + + expect(calls).toHaveLength(2); + expect(calls[0]).toEqual({ + command: DEFAULT_MARIMO_COMMAND, + args: ['check', '--format=json', notebookPath], + options: { timeoutMs: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS }, + }); + + expect(fs.createdTempPaths).toHaveLength(1); + const tempPath = fs.createdTempPaths[0] as string; + expect(tempPath.startsWith('/workspace/artifacts/')).toBe(true); + expect(tempPath.endsWith('.html')).toBe(true); + expect(tempPath).not.toBe(outputPath); + + expect(calls[1]).toEqual({ + command: DEFAULT_MARIMO_COMMAND, + args: ['export', 'html', notebookPath, '-o', tempPath, '--force'], + options: { timeoutMs: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS }, + }); + + expect(fs.renames).toEqual([{ from: tempPath, to: outputPath }]); + expect(fs.getBytes(tempPath)).toBeUndefined(); + expect(fs.getBytes(outputPath)).toEqual(expectedBytes); + + expect(Object.isFrozen(receipt)).toBe(true); + expect(Object.isFrozen(receipt.checkDiagnostics)).toBe(true); + expect(receipt).toEqual({ + notebookPath, + outputPath, + bytes: expectedBytes.byteLength, + sha256: expectedSha256, + checkDiagnostics: cleanReport, + }); + }); + + test('passes custom marimoCommand, timeoutMs, cwd, and notebook paths with spaces and shell metacharacters as single unmodified argv elements', async () => { + const fs = new InMemoryNotebookFs(); + const trickyNotebook = "/work/my notebooks/study $(rm -rf) & 'quote'; echo hi | cat.py"; + const outputPath = '/work/out/report snapshot.html'; + fs.putFile(trickyNotebook, 'import marimo\n'); + + const { runner, calls } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'ok'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const receipt = await exportNotebookSnapshot({ + notebookPath: trickyNotebook, + outputPath, + runner, + fs, + marimoCommand: '/opt/uv/bin/marimo', + timeoutMs: 45_000, + cwd: '/work', + }); + + expect(calls).toHaveLength(2); + expect(calls[0]?.command).toBe('/opt/uv/bin/marimo'); + expect(calls[0]?.args).toEqual(['check', '--format=json', trickyNotebook]); + expect(calls[0]?.options).toEqual({ cwd: '/work', timeoutMs: 45_000 }); + expect(calls[1]?.command).toBe('/opt/uv/bin/marimo'); + expect(calls[1]?.args[2]).toBe(trickyNotebook); + expect(calls[1]?.options).toEqual({ cwd: '/work', timeoutMs: 45_000 }); + expect(receipt.checkDiagnostics).toBeNull(); + }); + + test('accepts formatting and runtime advisories on clean exit 0', async () => { + const fs = new InMemoryNotebookFs(); + const notebookPath = '/work/nb.py'; + const outputPath = '/work/out.html'; + fs.putFile(notebookPath, 'import marimo\n'); + + const advisoryReport = { + issues: [ + { code: 'MF001', severity: 'formatting', message: 'Formatting suggestion' }, + { code: 'MR001', severity: 'runtime', message: 'Runtime advisory' }, + ], + summary: { errored: false, total_files: 1 }, + }; + + const { runner, calls } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: JSON.stringify(advisoryReport), stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'advisory ok'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const receipt = await exportNotebookSnapshot({ notebookPath, outputPath, runner, fs }); + expect(calls).toHaveLength(2); + expect(receipt.checkDiagnostics).toEqual(advisoryReport); + expect(Object.isFrozen(receipt.checkDiagnostics?.issues)).toBe(true); + }); + + test('never invokes export when marimo check exits non-zero and preserves parsed diagnostics', async () => { + const fs = new InMemoryNotebookFs(); + const notebookPath = '/work/bad.py'; + const outputPath = '/work/out.html'; + fs.putFile(notebookPath, 'def broken(:\n'); + + const failureReport = { + issues: [{ code: 'MB001', severity: 'breaking', message: 'Syntax error' }], + summary: { errored: true, total_files: 1 }, + }; + + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 1, + stdout: JSON.stringify(failureReport), + stderr: 'check failed', + })); + + const err = await expectSnapshotError( + exportNotebookSnapshot({ notebookPath, outputPath, runner, fs }), + 'CHECK_FAILED' + ); + + expect(calls).toHaveLength(1); + expect(calls[0]?.args[0]).toBe('check'); + expect(fs.createdTempPaths).toHaveLength(0); + expect((err.details as { diagnostics?: unknown }).diagnostics).toEqual(failureReport); + }); + + test('nonzero check exit takes precedence as CHECK_FAILED even when stdout is non-JSON', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/bad.py', 'import marimo\n'); + + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 2, + stdout: 'not json at all', + stderr: 'fatal error', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/bad.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'CHECK_FAILED' + ); + expect(calls).toHaveLength(1); + }); + + test('never invokes export when check exits 0 with whitespace-only stdout', async () => { + for (const stdout of ['\n', ' \t\r\n']) { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'existing-snapshot'); + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout, + stderr: '', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'CHECK_OUTPUT_INVALID' + ); + expect(calls).toHaveLength(1); + expect(calls[0]?.args[0]).toBe('check'); + expect(fs.createdTempPaths).toHaveLength(0); + expect(fs.getText('/work/out.html')).toBe('existing-snapshot'); + } + }); + + test('never invokes export when check exits 0 with malformed JSON or invalid report shape', async () => { + const badOutputs = [ + '{not-valid-json', + '[]', + '{}', + JSON.stringify({ issues: 'not-an-array', summary: { errored: false, total_files: 1 } }), + JSON.stringify({ issues: [], summary: { errored: 'false', total_files: 1 } }), + JSON.stringify({ issues: [], summary: { errored: false, total_files: 0 } }), + JSON.stringify({ issues: [], summary: { errored: false, total_files: 2 } }), + JSON.stringify({ issues: [123], summary: { errored: false, total_files: 1 } }), + ]; + + for (const stdout of badOutputs) { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout, + stderr: '', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'CHECK_OUTPUT_INVALID' + ); + expect(calls).toHaveLength(1); + expect(fs.createdTempPaths).toHaveLength(0); + } + }); + + test('never invokes export when check exits 0 with summary.errored, file error, or breaking diagnostic', async () => { + const blockingReports = [ + { issues: [], summary: { errored: true, total_files: 1 } }, + { + issues: [{ type: 'error', message: 'Failed to parse notebook' }], + summary: { errored: false, total_files: 1 }, + }, + { + issues: [{ code: 'MB002', severity: 'breaking', message: 'Cycle detected' }], + summary: { errored: false, total_files: 1 }, + }, + { + issues: [ + { + file: '/work/nb.py', + diagnostics: [{ code: 'MB003', severity: 'breaking', message: 'Multiple definitions' }], + }, + ], + summary: { errored: false, total_files: 1 }, + }, + ]; + + for (const report of blockingReports) { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout: JSON.stringify(report), + stderr: '', + })); + + const err = await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'CHECK_FAILED' + ); + expect(calls).toHaveLength(1); + expect(fs.createdTempPaths).toHaveLength(0); + expect((err.details as { diagnostics?: unknown }).diagnostics).toEqual(report); + } + }); + + test('maps check timeout to TIMEOUT and never invokes export', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'original'); + + const { runner, calls } = createRecordingRunner(async () => { + throw makeTimeoutError('check timed out'); + }); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + timeoutMs: 5_000, + }), + 'TIMEOUT' + ); + + expect(calls).toHaveLength(1); + expect(fs.createdTempPaths).toHaveLength(0); + expect(fs.getText('/work/out.html')).toBe('original'); + }); + + test('fail-closed export: nonzero exit after partial HTML write removes temp and preserves existing destination', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'original-good-snapshot'); + + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'partial-broken-cell-output'); + return { exitCode: 1, stdout: '', stderr: 'ZeroDivisionError in cell 3' }; + }); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'EXPORT_FAILED' + ); + + expect(fs.createdTempPaths).toHaveLength(1); + const tempPath = fs.createdTempPaths[0] as string; + expect(fs.removedPaths).toContain(tempPath); + expect(fs.getBytes(tempPath)).toBeUndefined(); + expect(fs.getText('/work/out.html')).toBe('original-good-snapshot'); + }); + + test('fail-closed export: missing or zero-byte temp output throws EXPORT_EMPTY, cleans temp, and preserves destination', async () => { + for (const mode of ['zero-byte', 'missing'] as const) { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'keep-me'); + + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + if (mode === 'missing') { + fs.entries.delete(tempPath); + } + // In 'zero-byte' mode, tempPath stays at 0 bytes from createExclusive. + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'EXPORT_EMPTY' + ); + + const tempPath = fs.createdTempPaths[0] as string; + expect(fs.removedPaths).toContain(tempPath); + expect(fs.getBytes(tempPath)).toBeUndefined(); + expect(fs.getText('/work/out.html')).toBe('keep-me'); + } + }); + + test('fail-closed export: export timeout after partial write throws TIMEOUT, removes temp, and preserves destination', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'keep-original'); + + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'partial-before-timeout'); + throw makeTimeoutError('export timed out'); + }); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + timeoutMs: 1_000, + }), + 'TIMEOUT' + ); + + const tempPath = fs.createdTempPaths[0] as string; + expect(fs.removedPaths).toContain(tempPath); + expect(fs.getBytes(tempPath)).toBeUndefined(); + expect(fs.getText('/work/out.html')).toBe('keep-original'); + }); + + test('fail-closed export: rename failure throws EXPORT_FAILED, removes temp, and preserves destination', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'prior-snapshot'); + fs.failRenameError = new Error('EXDEV: cross-device link not permitted'); + + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'new-snapshot'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const err = await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'EXPORT_FAILED' + ); + + const tempPath = fs.createdTempPaths[0] as string; + expect(err.cause).toBe(fs.failRenameError); + expect(fs.removedPaths).toContain(tempPath); + expect(fs.getBytes(tempPath)).toBeUndefined(); + expect(fs.getText('/work/out.html')).toBe('prior-snapshot'); + }); + + test('fail-closed export: rename failure preserves primary error if temp cleanup also fails', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'prior-snapshot'); + fs.failRenameError = new Error('EXDEV: cross-device link not permitted'); + fs.failRemoveError = new Error('EIO: cleanup failed'); + + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'new-snapshot'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const err = await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'EXPORT_FAILED' + ); + + expect(err.cause).toBe(fs.failRenameError); + expect(fs.removedPaths).toContain(fs.createdTempPaths[0] as string); + expect(fs.getText('/work/out.html')).toBe('prior-snapshot'); + }); + + test('uses a short sibling temp filename even when output basename is near POSIX NAME_MAX', async () => { + const fs = new InMemoryNotebookFs(); + const notebookPath = '/work/nb.py'; + const longBasename = `${'a'.repeat(250)}.html`; + const outputPath = `/work/${longBasename}`; + fs.putFile(notebookPath, 'import marimo\n'); + + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'long-name-ok'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + await exportNotebookSnapshot({ notebookPath, outputPath, runner, fs }); + + expect(fs.createdTempPaths).toHaveLength(1); + const tempPath = fs.createdTempPaths[0] as string; + const tempBasename = tempPath.slice(tempPath.lastIndexOf('/') + 1); + expect(tempPath.startsWith('/work/')).toBe(true); + expect(tempBasename.endsWith('.html')).toBe(true); + expect(tempBasename.length).toBeLessThan(128); + expect(fs.getText(outputPath)).toBe('long-name-ok'); + }); + + test('overlapping exports to the same outputPath reserve separate temp files without partial publication', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'initial'); + + let releaseFirstExport: (() => void) | null = null; + const firstExportStarted = new Promise(resolve => { + releaseFirstExport = resolve; + }); + let unblockFirstExport: (() => void) | null = null; + const gateFirstExport = new Promise(resolve => { + unblockFirstExport = resolve; + }); + + let exportCount = 0; + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + exportCount += 1; + const myExport = exportCount; + const tempPath = args[args.indexOf('-o') + 1] as string; + if (myExport === 1) { + fs.putFile(tempPath, 'snapshot-A'); + releaseFirstExport?.(); + await gateFirstExport; + return { exitCode: 0, stdout: '', stderr: '' }; + } + fs.putFile(tempPath, 'snapshot-B'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const firstPromise = exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }); + await firstExportStarted; + + const secondReceipt = await exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }); + expect(fs.getText('/work/out.html')).toBe('snapshot-B'); + + unblockFirstExport?.(); + const firstReceipt = await firstPromise; + + expect(fs.createdTempPaths).toHaveLength(2); + expect(fs.createdTempPaths[0]).not.toBe(fs.createdTempPaths[1]); + expect(firstReceipt.bytes).toBe(new TextEncoder().encode('snapshot-A').byteLength); + expect(secondReceipt.bytes).toBe( + new TextEncoder().encode('snapshot-B').byteLength + ); + expect(fs.getText('/work/out.html')).toBe('snapshot-A'); + }); + + test('rejects invalid paths before any runner call', async () => { + const cases: Array<{ + readonly name: string; + readonly notebookPath: string; + readonly outputPath: string; + readonly allowedNotebookRoot?: string; + readonly allowedOutputRoot?: string; + }> = [ + { name: 'non-.py notebook', notebookPath: '/work/nb.txt', outputPath: '/work/out.html' }, + { name: 'bare .py filename', notebookPath: '/work/.py', outputPath: '/work/out.html' }, + { + name: 'trailing slash notebook', + notebookPath: '/work/nb.py/', + outputPath: '/work/out.html', + }, + { name: 'non-.html output', notebookPath: '/work/nb.py', outputPath: '/work/out.htm' }, + { name: 'bare .html filename', notebookPath: '/work/nb.py', outputPath: '/work/.html' }, + { name: 'relative notebook', notebookPath: 'research/nb.py', outputPath: '/work/out.html' }, + { name: 'relative output', notebookPath: '/work/nb.py', outputPath: './out.html' }, + { name: 'leading dash notebook', notebookPath: '-nb.py', outputPath: '/work/out.html' }, + { name: 'leading dash output', notebookPath: '/work/nb.py', outputPath: '--out.html' }, + { name: 'NUL in notebook', notebookPath: '/work/nb\0.py', outputPath: '/work/out.html' }, + { name: 'NUL in output', notebookPath: '/work/nb.py', outputPath: '/work/out\0.html' }, + { + name: '.. escape outside allowedNotebookRoot', + notebookPath: '/work/notebooks/../secret.py', + outputPath: '/work/out/report.html', + allowedNotebookRoot: '/work/notebooks', + }, + { + name: '.. escape outside allowedOutputRoot', + notebookPath: '/work/notebooks/nb.py', + outputPath: '/work/out/../evil.html', + allowedOutputRoot: '/work/out', + }, + { + name: 'same-prefix sibling notebook root', + notebookPath: '/work/notebooks-other/nb.py', + outputPath: '/work/out/report.html', + allowedNotebookRoot: '/work/notebooks', + }, + { + name: 'same-prefix sibling output root', + notebookPath: '/work/notebooks/nb.py', + outputPath: '/work/out-other/report.html', + allowedOutputRoot: '/work/out', + }, + ]; + + for (const tc of cases) { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout: '', + stderr: '', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: tc.notebookPath, + outputPath: tc.outputPath, + runner, + fs, + ...(tc.allowedNotebookRoot !== undefined + ? { allowedNotebookRoot: tc.allowedNotebookRoot } + : {}), + ...(tc.allowedOutputRoot !== undefined + ? { allowedOutputRoot: tc.allowedOutputRoot } + : {}), + }), + 'INVALID_PATH' + ); + expect(calls).toHaveLength(0); + } + }); + + test('rejects missing notebook or directory in place of notebook with NOTEBOOK_NOT_FOUND and zero runner calls', async () => { + for (const setup of ['missing', 'directory'] as const) { + const fs = new InMemoryNotebookFs(); + if (setup === 'directory') { + fs.putDirectory('/work/nb.py'); + } + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout: '', + stderr: '', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'NOTEBOOK_NOT_FOUND' + ); + expect(calls).toHaveLength(0); + } + }); + + test('rejects invalid timeoutMs or marimoCommand with INVALID_OPTION and zero runner calls', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout: '', + stderr: '', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + timeoutMs: 0, + }), + 'INVALID_OPTION' + ); + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + marimoCommand: '-evil', + }), + 'INVALID_OPTION' + ); + expect(calls).toHaveLength(0); + }); +}); diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 8c2221aa..ec632373 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -748,6 +748,7 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x6d48cd59 - `decode_eod_price_stream` / `decode_eod_price_chunks` → `Result` - `decode_qm_split_stream` / `decode_qm_split_chunks` → `Result` - `decode_qm_dividend_stream` / `decode_qm_dividend_chunks` → `Result` + - `decode_te_data_stream` / `decode_te_data_chunks` → `Result` (borrowed historical `TeDataPoint<'a>` points only — `forecast` unread — with absolute `u64` error offsets) - Because borrowed zero-copy views (`RawEodDailyBar<'a>`, `RawQmSplit<'a>`, `RawQmDividend<'a>`) borrow from the reused chunk buffer, callbacks are higher-ranked (`for<'a> FnMut(...)`). Per-document decode errors are skipped and reported with absolute `u64` stream offsets (rebasing embedded `offset` fields on `CorruptBson` errors), and chunk stats sum via `AddAssign` so `decoded + rejected_total() == docs_in` holds across the entire stream. ### `bench-bson-stream` @@ -1697,6 +1698,65 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m - **`listing_venues.tsv` format (`load_listing_venues_tsv`):** strict headerless 2-column tab-separated file `listing_idvenue`, where `listing_id` is a strictly positive ASCII base-10 integer and `venue` is exact `us_tsx` (`StatutoryLagVenue::UsTsx`) or `tsxv_cse` (`StatutoryLagVenue::TsxvCse`). Wrong column counts, non-integer/non-positive IDs, unknown venues, duplicate IDs, and interior blank lines fail closed with a single-line error naming the path and 1-based line number. - **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up. +## `run_curate_bars_1m` Bounded-Memory File-to-File Runner (`M2.3k`) + +`run_curate_bars_1m` / `run_curate_bars_1m_with_readers` (`src/run_curate_bars_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a headerless 5-column `provider_mapping.tsv` (reusing `load_provider_mapping_tsv` and the shared `qmSplits` loader from `src/run_curate_bars.rs`) into per-shard QuestDB ILP v2 files (`/bars_1m.shard-.ilp`): + +- **Bounded-memory chunking & listing-keyed splits:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_eod_intraday_buffer` directly (the same reader and decoder wrapped by `decode_eod_intraday_chunks`, which hides chunk boundaries), resolving each bar's `listing_id` on its Eastern Time `session_date` before applying `listing_id`-keyed `qmSplits` un-adjustment (preventing split leakage across reused tickers) into one shared `IlpShardedWriter` and calling `finish()` once after EOF. Peak memory is bounded by the reference tables, `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`), per-chunk curation buffers, and one ILP batch buffer per shard. +- **Cross-chunk semantics & reporting:** `mapping_source` must be `"eod"`. Collision collapse/drop and `(listing_id, ts)` ordering apply per chunk; the same `(listing_id, ts)` appearing in two chunks is emitted twice and relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. Aggregated `curate_stats.listings_out` and `curate_stats.builder.keys_out` are sums of per-chunk counts (not global distinct counts). `known_at_micros` is caller-supplied and supplies no evidence of earlier market availability. +- **Fail-closed publication:** Preflight scans `out_dir` for any pre-existing `bars_1m.shard-.ilp` file (regardless of `shard_count`) and rejects before staging, writes to exclusively created temp files in `out_dir`, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any publication error. File-mode CLI wiring is available via `curate-bars-1m` below; `--from-mongo` and live QuestDB ingestion remain follow-ups. + +### `curate-bars-1m` Command (`M2.3n`) + +File-mode CLI command wiring `run_curate_bars_1m` into the `curate-etl` binary: + +```bash +curate-etl curate-bars-1m \ + --eod-intraday eodIntraday1M.bson \ + --qm-splits qmSplits.bson \ + --provider-mapping provider_mapping.tsv \ + --out ./out \ + --shards 4 \ + --known-at-micros 1750000000000000 +``` + +- **Required flags:** `--eod-intraday `, `--qm-splits `, `--provider-mapping `, `--out `, `--shards ` (positive base-10 integer, no default), and `--known-at-micros ` (positive base-10 UTC microsecond timestamp, no default). +- **Optional flag:** `--mapping-source ` (defaults to `eod`; only `eod` is accepted by the runner). +- **Timestamp semantics:** `--known-at-micros` records the caller-supplied curation run timestamp verbatim in each ILP row's `known_at` column; it does not establish historical market availability. +- **Outputs & fail-closed publication:** writes `/bars_1m.shard-.ilp` (`00`..``) and prints the `format_curate_bars_1m_report` summary to stdout. Inherits the runner's fail-closed preflight and staging/rollback guarantees (refuses to overwrite existing `bars_1m.shard-*.ilp` files and leaves no partial shard or staging files on error). +- **File mode only:** MongoDB streaming flags (such as `--from-mongo` and `--mongo-uri`) are rejected; `--from-mongo` streaming and live QuestDB ingestion remain follow-ups. + +## `run_curate_fx_1m` File-to-File Runner (`M2.3l`) + +`run_curate_fx_1m` / `run_curate_fx_1m_with_readers` (`src/run_curate_fx_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files (`/fx_1m.shard-.ilp`) via `curate_and_write_fx_1m_from_bson` (`src/curate_fx_1m.rs`): + +- **Global sort & deduplication with bounded non-FX memory:** Calls `curate_and_write_fx_1m_from_bson` once over the entire input stream so `ts` sorting and deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop) are global across all BSON stream chunks, then calls `IlpShardedWriter::finish()` once after clean EOF. Because `Fx1mAccumulator::push` counts wrong-code rows and returns before appending, peak memory is bounded by accepted `CAD.FOREX` rows plus `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`) and bounded per-shard output buffers. +- **Single-pair sharding & empty runs:** Every curated row carries `pair = "USDCAD"`, `source = "eod"`, and EODHD's UTC microsecond bar-start `ts` (preserving CAD-per-USD OHLC bits without implying bar-close observability at bar start), routing all rows deterministically to `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files. Empty or wrong-code-only inputs succeed with `rows_written == 0` and publish the full set of empty shard files. +- **Fail-closed publication:** Reuses the shared `run_curate_bars_1m` staging and publication helpers parameterized by table name (`fx_1m`): preflight rejects any pre-existing `fx_1m.shard-.ilp` in `out_dir` regardless of `shard_count` (while allowing `bars_1m.shard-*.ilp` to coexist untouched), writes to exclusively created temp files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any error. File-mode CLI wiring is available via `curate-fx-1m` below; `--from-mongo` and live QuestDB load remain follow-ups. + +### `curate-fx-1m` Command (`M2.3o`) + +File-mode CLI command wiring `run_curate_fx_1m` into the `curate-etl` binary: + +```bash +curate-etl curate-fx-1m \ + --eod-intraday eodIntraday1M.bson \ + --out ./out \ + --shards 4 +``` + +- **Required flags:** `--eod-intraday ` (local concatenated raw BSON `eodIntraday1M` dump), `--out `, and `--shards ` (positive base-10 integer, no default). +- **Outputs & fail-closed publication:** writes `/fx_1m.shard-.ilp` (`00`..``) and prints the `format_curate_fx_1m_report` summary to stdout. Inherits the runner's fail-closed preflight and staging/rollback guarantees (refuses to overwrite existing `fx_1m.shard-*.ilp` files and leaves no partial shard or staging files on error). +- **File mode only:** MongoDB streaming flags (such as `--from-mongo` and `--mongo-uri`) are rejected; `--from-mongo` streaming and live QuestDB ingestion remain follow-ups. + +## `run_curate_qm_bars_1m` Bounded-Memory File-to-File Runner (`M2.3m`) + +`run_curate_qm_bars_1m` / `run_curate_qm_bars_1m_with_readers` (`src/run_curate_qm_bars_1m.rs`) streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) into per-shard QuestDB ILP v2 files (`/bars_1m_qm.shard-.ilp`) via `curate_and_write_qm_bars_1m` (`src/curate_qm_bars_1m.rs`): + +- **Bounded-memory chunking & raw OHLCV passthrough:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_qm_intraday_buffer` directly, borrowing `qmSearchCode` per chunk and curating without split un-adjustment (no splits input; raw `qmIntraday` OHLCV passes through bit-identical aside from `-0.0 -> +0.0` volume normalization) into one shared `IlpShardedWriter` with `finish()` called once after clean EOF. `mapping_source` rejects blank values and forwards any nonblank namespace verbatim (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`). +- **Cross-chunk semantics, table/file separation & reporting:** Sorting and collision collapse/drop apply per chunk; cross-chunk duplicates rely on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`, and `curate_stats.listings_out` / `curate_stats.builder.keys_out` sum per-chunk counts. Emitted ILP v2 rows target table `bars_1m` with `source=qm_raw` and caller-supplied `known_at_micros`, while output files use the `bars_1m_qm.shard-.ilp` prefix so QM and EOD (`bars_1m.shard-.ilp`) exports can share `out_dir` safely. +- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-.ilp` in `out_dir` regardless of `shard_count`, writes to exclusively created staging files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only this run's final and staging files on any error. CLI wiring, `--from-mongo`, and live QuestDB ingestion remain follow-ups. + ## Lagged Macro Regime Series Builder (`M2.2n`) `build_macro_rows` (`src/macro_series.rs`, tested in `src/macro_series_tests.rs`) is a pure, in-memory builder turning `MacroObservation` inputs and a caller-supplied `(country_iso, indicator) -> Option` lookup into sorted, unique `MacroRow` records matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` (§1 and §3A). diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs index f797bf80..564a70ae 100644 --- a/tools/curate-etl/src/bson_stream.rs +++ b/tools/curate-etl/src/bson_stream.rs @@ -54,6 +54,9 @@ use crate::bson_qm_intraday::{ use crate::bson_qm_prices::{ decode_qm_price_buffer, BsonQmPriceDecodeStats, BsonQmPriceError, RawQmPrice, }; +use crate::bson_te_data::{ + decode_te_data_buffer, BsonTeDataDecodeStats, BsonTeDataError, TeDataPoint, +}; use crate::bson_te_market_data::{ decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError, }; @@ -983,6 +986,92 @@ where decode_te_market_data_chunks(&mut chunk_reader, target_symbol, on_bar, on_error) } +#[inline] +fn rebase_te_data_error(base: u64, err: BsonTeDataError) -> BsonTeDataError { + match err { + BsonTeDataError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonTeDataError::TruncatedDocument { + offset: rebase_offset(base, offset), + remaining, + declared_len, + }, + BsonTeDataError::CorruptDocumentLength { + offset, + declared_len, + } => BsonTeDataError::CorruptDocumentLength { + offset: rebase_offset(base, offset), + declared_len, + }, + BsonTeDataError::CorruptBson { offset, detail } => BsonTeDataError::CorruptBson { + offset: rebase_offset(base, offset), + detail, + }, + BsonTeDataError::CorruptPointBson { + offset, + point_index, + detail, + } => BsonTeDataError::CorruptPointBson { + offset: rebase_offset(base, offset), + point_index, + detail, + }, + other => other, + } +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_te_data_buffer`], +/// accumulating [`BsonTeDataDecodeStats`] and rebasing per-document and per-point error offsets +/// to absolute stream byte offsets. +/// +/// Emits historical `data` observations as borrowed [`TeDataPoint<'a>`] values; `forecast` is +/// never read. Per-document and per-point data-quality errors are reported to `on_error` and do +/// not abort the stream; only stream-level framing or I/O errors return `Err(BsonStreamError)`. +pub fn decode_te_data_chunks( + reader: &mut RawBsonChunkReader, + mut on_point: F, + mut on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(TeDataPoint<'a>), + E: FnMut(u64, BsonTeDataError), +{ + let mut total = BsonTeDataDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_te_data_buffer( + chunk.bytes, + &mut on_point, + |local_offset, err| { + let abs_offset = base + local_offset as u64; + on_error(abs_offset, rebase_te_data_error(base, err)); + }, + ); + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `teData` [`std::io::Read`] source through +/// [`decode_te_data_buffer`] with bounded memory. +pub fn decode_te_data_stream( + reader: R, + options: BsonStreamOptions, + on_point: F, + on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(TeDataPoint<'a>), + E: FnMut(u64, BsonTeDataError), +{ + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_te_data_chunks(&mut chunk_reader, on_point, on_error) +} + /// Terminal error returned by [`decode_ceo_posts_chunks`] and [`decode_ceo_posts_stream`]. #[derive(Debug)] pub enum BsonCeoPostsStreamError { diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs index 12c563fa..a903b778 100644 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -1,7 +1,7 @@ use std::error::Error as _; use std::io::{self, Cursor, Read}; -use bson::raw::{cstr, RawDocumentBuf}; +use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; use bson::DateTime; use crate::bson_eod_intraday::{ @@ -25,9 +25,13 @@ use crate::bson_stream::{ decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_financials_chunks, decode_qm_financials_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_stream, - decode_qm_split_stream, BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, + decode_qm_split_stream, decode_te_data_chunks, decode_te_data_stream, + BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, }; +use crate::bson_te_data::{ + decode_te_data_buffer, BsonTeDataDecodeStats, BsonTeDataError, TeDataPoint, +}; use crate::fundamentals::FinancialObservation; #[derive(Debug, Clone, Copy)] @@ -3092,3 +3096,739 @@ fn qm_financials_stream_rejects_invalid_config_before_read() { BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) )); } + +#[derive(Debug, PartialEq, Eq)] +struct OwnedTeDataPoint { + te_symbol: String, + country: String, + category: String, + period_date: i32, + value_bits: u64, +} + +fn owned_te_data_point(p: TeDataPoint<'_>) -> OwnedTeDataPoint { + OwnedTeDataPoint { + te_symbol: p.te_symbol.to_owned(), + country: p.country.to_owned(), + category: p.category.to_owned(), + period_date: p.period_date, + value_bits: p.value.to_bits(), + } +} + +fn make_te_data_doc( + te_symbol: Option<&str>, + country: &str, + category: &str, + data_points: &[(&str, f64)], + forecast_points: &[(&str, f64)], +) -> Vec { + let mut doc = RawDocumentBuf::new(); + if let Some(sym) = te_symbol { + doc.append(cstr!("teSymbol"), sym); + } + doc.append(cstr!("country"), country); + doc.append(cstr!("category"), category); + + let mut data_arr = RawArrayBuf::new(); + for &(d, v) in data_points { + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), d); + pt.append(cstr!("v"), v); + data_arr.push(pt); + } + doc.append(cstr!("data"), data_arr); + + if !forecast_points.is_empty() { + let mut fc_arr = RawArrayBuf::new(); + for &(d, v) in forecast_points { + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), d); + pt.append(cstr!("v"), v); + fc_arr.push(pt); + } + doc.append(cstr!("forecast"), fc_arr); + } + + doc.into_bytes() +} + +#[test] +fn te_data_stream_and_chunks_match_buffer_across_tiny_chunks_and_short_reads() { + let mut fixture = Vec::new(); + fixture.extend_from_slice(&make_te_data_doc( + Some("USACPI"), + "United States", + "Inflation Rate", + &[("2024-01-31", 3.1), ("2024-02-29", 3.2)], + &[("2025-06-30", 2.4)], + )); + fixture.extend_from_slice(&make_te_data_doc( + Some("CACPI"), + "Canada", + "Inflation Rate", + &[("2024-01-31", 2.9), ("2024-02-29", 2.8), ("2024-03-31", 2.9)], + &[], + )); + // Include a rejected doc (missing teSymbol) and a doc with a bad point date + valid trailing point. + fixture.extend_from_slice(&make_te_data_doc( + None, + "United States", + "GDP", + &[("2024-03-31", 2.1)], + &[], + )); + fixture.extend_from_slice(&make_te_data_doc( + Some("USAGDP"), + "United States", + "GDP Growth Rate", + &[("2024-01-31", 1.6), ("2023-02-29", 9.9), ("2024-06-30", 3.0)], + &[("2025-12-31", 2.0)], + )); + fixture.extend_from_slice(&make_te_data_doc( + Some("CAPOLICY"), + "Canada", + "Interest Rate", + &[("2024-06-05", 4.75)], + &[], + )); + + let mut expected_points = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_te_data_buffer( + &fixture, + |p| expected_points.push(owned_te_data_point(p)), + |off, err| expected_errs.push((off as u64, err)), + ); + assert_eq!(expected_stats.docs_in, 5); + assert_eq!(expected_stats.docs_accepted, 4); + assert_eq!(expected_stats.docs_rejected_total(), 1); + assert_eq!(expected_stats.points_in, 9); + assert_eq!(expected_stats.points_decoded, 8); + assert_eq!(expected_stats.rejected_total(), 1); + assert_eq!( + expected_stats.docs_in, + expected_stats.docs_accepted + expected_stats.docs_rejected_total() + ); + assert_eq!( + expected_stats.points_in, + expected_stats.points_decoded + expected_stats.rejected_total() + ); + + // Tiny chunk capacities force multiple whole-document chunks; short FixedStepReader splits + // both 4-byte length prefixes and document bodies across reads. + let max_doc_bytes = 4096; + for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (128, 17)] { + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes, + }; + let mut got_points = Vec::new(); + let mut got_errs = Vec::new(); + let got_stats = decode_te_data_stream( + FixedStepReader::new(&fixture, step), + opts, + |p| got_points.push(owned_te_data_point(p)), + |off, err| got_errs.push((off, err)), + ) + .unwrap_or_else(|e| panic!("teData stream cap={cap} step={step} failed: {e}")); + + assert_eq!(got_stats, expected_stats, "stats mismatch cap={cap} step={step}"); + assert_eq!(got_points, expected_points, "points mismatch cap={cap} step={step}"); + assert_eq!(got_errs, expected_errs, "errors mismatch cap={cap} step={step}"); + } + + // Exercise decode_te_data_chunks directly with tiny buffer + FixedStepReader and verify + // buffer_capacity stays within max_doc_bytes. + let chunk_opts = BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes, + }; + let mut chunk_reader = RawBsonChunkReader::with_options( + RandomInterruptReader::new(&fixture, 0x7E_DA7A, true), + chunk_opts, + ) + .unwrap(); + let mut chunk_points = Vec::new(); + let mut chunk_errs = Vec::new(); + let chunk_stats = decode_te_data_chunks( + &mut chunk_reader, + |p| chunk_points.push(owned_te_data_point(p)), + |off, err| chunk_errs.push((off, err)), + ) + .unwrap(); + assert_eq!(chunk_stats, expected_stats); + assert_eq!(chunk_points, expected_points); + assert_eq!(chunk_errs, expected_errs); + assert!(chunk_reader.buffer_capacity() <= max_doc_bytes); + assert_eq!(chunk_reader.docs_framed(), 5); + assert_eq!(chunk_reader.bytes_read(), fixture.len() as u64); +} + +#[test] +fn te_data_stream_later_chunk_rejects_continue_with_absolute_offsets() { + let doc1 = make_te_data_doc( + Some("USACPI"), + "United States", + "Inflation Rate", + &[("2024-01-31", 3.1)], + &[], + ); + let doc2_missing_sym = make_te_data_doc( + None, + "United States", + "Unemployment Rate", + &[("2024-01-31", 3.7)], + &[], + ); + let doc3_bad_point = make_te_data_doc( + Some("CACPI"), + "Canada", + "Inflation Rate", + &[ + ("2024-01-31", 2.9), + ("not-a-date", 99.0), + ("2024-03-31", 2.8), + ], + &[], + ); + let doc4_trailing_valid = make_te_data_doc( + Some("USAGDP"), + "United States", + "GDP Growth Rate", + &[("2024-06-30", 3.0)], + &[], + ); + + let mut fixture = Vec::new(); + fixture.extend_from_slice(&doc1); + let missing_sym_offset = fixture.len() as u64; + assert!(missing_sym_offset > 0); + fixture.extend_from_slice(&doc2_missing_sym); + let bad_point_doc_offset = fixture.len() as u64; + assert!(bad_point_doc_offset > missing_sym_offset); + fixture.extend_from_slice(&doc3_bad_point); + fixture.extend_from_slice(&doc4_trailing_valid); + + // chunk_capacity_bytes == doc1.len() guarantees doc2 and doc3 start in non-first chunks. + let opts = BsonStreamOptions { + chunk_capacity_bytes: doc1.len(), + max_doc_bytes: 4096, + }; + let mut points = Vec::new(); + let mut errs = Vec::new(); + let stats = decode_te_data_stream( + FixedStepReader::new(&fixture, 9), + opts, + |p| points.push(owned_te_data_point(p)), + |off, err| errs.push((off, err)), + ) + .unwrap(); + + // Valid prefix, valid point before and after bad point, and trailing valid doc all emit. + assert_eq!(points.len(), 4); + assert_eq!(points[0].te_symbol, "USACPI"); + assert_eq!(points[1].te_symbol, "CACPI"); + assert_eq!(points[1].value_bits, 2.9_f64.to_bits()); + assert_eq!(points[2].te_symbol, "CACPI"); + assert_eq!(points[2].value_bits, 2.8_f64.to_bits()); + assert_eq!(points[3].te_symbol, "USAGDP"); + + assert_eq!( + errs, + vec![ + (missing_sym_offset, BsonTeDataError::MissingSymbol), + ( + bad_point_doc_offset, + BsonTeDataError::InvalidPointDate { point_index: 1 }, + ), + ] + ); + + assert_eq!(stats.docs_in, 4); + assert_eq!(stats.docs_accepted, 3); + assert_eq!(stats.rejected_missing_symbol, 1); + assert_eq!(stats.docs_rejected_total(), 1); + assert_eq!(stats.points_in, 5); + assert_eq!(stats.points_decoded, 4); + assert_eq!(stats.rejected_invalid_date, 1); + assert_eq!(stats.rejected_total(), 1); + assert_eq!( + stats.docs_in, + stats.docs_accepted + stats.docs_rejected_total() + ); + assert_eq!(stats.points_in, stats.points_decoded + stats.rejected_total()); +} + +#[test] +fn te_data_stream_rebases_corrupt_bson_and_corrupt_point_bson_in_later_chunks() { + let doc1 = make_te_data_doc( + Some("USACPI"), + "United States", + "Inflation Rate", + &[("2024-01-31", 3.1)], + &[], + ); + // Length-framed corrupt top-level BSON doc. + let doc2_corrupt_top = make_corrupt_bson_doc(37); + // Length-framed teData doc whose second point (point_index = 1) has a corrupt element type tag. + let mut doc3_corrupt_point = make_te_data_doc( + Some("CACPI"), + "Canada", + "Inflation Rate", + &[("2024-01-31", 2.9), ("2024-02-29", 2.8)], + &[], + ); + let second_d_pos = doc3_corrupt_point + .windows(3) + .enumerate() + .filter(|(_, w)| *w == b"\x02d\0") + .nth(1) + .map(|(idx, _)| idx) + .expect("locate second point's 'd' element"); + doc3_corrupt_point[second_d_pos] = 0x7E; + + let doc4_after = make_te_data_doc( + Some("USAGDP"), + "United States", + "GDP Growth Rate", + &[("2024-06-30", 3.0)], + &[], + ); + + let mut fixture = Vec::new(); + fixture.extend_from_slice(&doc1); + let corrupt_top_offset = fixture.len() as u64; + fixture.extend_from_slice(&doc2_corrupt_top); + let corrupt_point_offset = fixture.len() as u64; + fixture.extend_from_slice(&doc3_corrupt_point); + fixture.extend_from_slice(&doc4_after); + + let opts = BsonStreamOptions { + chunk_capacity_bytes: doc1.len(), + max_doc_bytes: 4096, + }; + let mut points = Vec::new(); + let mut errs = Vec::new(); + let stats = decode_te_data_stream( + FixedStepReader::new(&fixture, 11), + opts, + |p| points.push(owned_te_data_point(p)), + |off, err| errs.push((off, err)), + ) + .unwrap(); + + // doc1 point + doc3's valid first point + doc4 point all emit. + assert_eq!(points.len(), 3); + assert_eq!(points[0].te_symbol, "USACPI"); + assert_eq!(points[1].te_symbol, "CACPI"); + assert_eq!(points[2].te_symbol, "USAGDP"); + + assert_eq!(errs.len(), 2); + assert!( + matches!( + &errs[0], + (abs_off, BsonTeDataError::CorruptBson { offset, .. }) + if *abs_off == corrupt_top_offset && *offset as u64 == corrupt_top_offset + ), + "expected rebased CorruptBson at {corrupt_top_offset}, got {:?}", + errs[0] + ); + assert!( + matches!( + &errs[1], + ( + abs_off, + BsonTeDataError::CorruptPointBson { + offset, + point_index: 1, + .. + } + ) if *abs_off == corrupt_point_offset && *offset as u64 == corrupt_point_offset + ), + "expected rebased CorruptPointBson at {corrupt_point_offset}, got {:?}", + errs[1] + ); + + assert_eq!(stats.docs_in, 4); + assert_eq!(stats.docs_accepted, 3); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.points_in, 4); + assert_eq!(stats.points_decoded, 3); + assert_eq!(stats.rejected_corrupt_point, 1); + assert_eq!( + stats.docs_in, + stats.docs_accepted + stats.docs_rejected_total() + ); + assert_eq!(stats.points_in, stats.points_decoded + stats.rejected_total()); + + // Directly exercise rebase_te_data_error for the two framing-offset variants intercepted by + // RawBsonChunkReader, plus non-offset variants. + assert_eq!( + super::rebase_te_data_error( + 1_000, + BsonTeDataError::TruncatedDocument { + offset: 42, + remaining: 3, + declared_len: Some(64), + }, + ), + BsonTeDataError::TruncatedDocument { + offset: 1_042, + remaining: 3, + declared_len: Some(64), + } + ); + assert_eq!( + super::rebase_te_data_error( + 2_000, + BsonTeDataError::CorruptDocumentLength { + offset: 17, + declared_len: 3, + }, + ), + BsonTeDataError::CorruptDocumentLength { + offset: 2_017, + declared_len: 3, + } + ); + assert_eq!( + super::rebase_te_data_error(500, BsonTeDataError::InvalidPointDate { point_index: 4 }), + BsonTeDataError::InvalidPointDate { point_index: 4 } + ); + assert_eq!( + super::rebase_te_data_error(500, BsonTeDataError::MissingSymbol), + BsonTeDataError::MissingSymbol + ); +} + +#[test] +fn te_data_stream_ignores_forecast_and_handles_empty_input() { + // Empty input via both decode_te_data_stream and decode_te_data_chunks. + let opts = BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 1024, + }; + let empty_stats = decode_te_data_stream( + Cursor::new(&[][..]), + opts, + |_| panic!("unexpected point on empty input"), + |_, _| panic!("unexpected error on empty input"), + ) + .unwrap(); + assert_eq!(empty_stats, BsonTeDataDecodeStats::default()); + + let mut empty_reader = RawBsonChunkReader::with_options(Cursor::new(&[][..]), opts).unwrap(); + let empty_chunk_stats = decode_te_data_chunks( + &mut empty_reader, + |_| panic!("unexpected point on empty chunks"), + |_, _| panic!("unexpected error on empty chunks"), + ) + .unwrap(); + assert_eq!(empty_chunk_stats, BsonTeDataDecodeStats::default()); + + // Document with distinct historical `data` and forward-looking `forecast` arrays. + let doc = make_te_data_doc( + Some("USACPI"), + "United States", + "Inflation Rate", + &[("2024-01-31", 3.1), ("2024-02-29", 3.2)], + &[("2026-01-31", 99.1), ("2026-06-30", 99.2), ("2027-01-31", 99.3)], + ); + let mut points = Vec::new(); + let stats = decode_te_data_stream( + FixedStepReader::new(&doc, 7), + BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes: 4096, + }, + |p| points.push(owned_te_data_point(p)), + |off, err| panic!("unexpected error at {off}: {err}"), + ) + .unwrap(); + + assert_eq!(stats.docs_in, 1); + assert_eq!(stats.docs_accepted, 1); + assert_eq!(stats.points_in, 2); + assert_eq!(stats.points_decoded, 2); + assert_eq!(stats.rejected_total(), 0); + assert_eq!(points.len(), 2); + assert_eq!(points[0].value_bits, 3.1_f64.to_bits()); + assert_eq!(points[1].value_bits, 3.2_f64.to_bits()); +} + +#[test] +fn te_data_stream_returns_terminal_errors_for_truncated_and_oversized_docs() { + let prefix_doc = make_te_data_doc( + Some("USACPI"), + "United States", + "Inflation Rate", + &[("2024-01-31", 3.1)], + &[], + ); + + // 1. Truncated trailing document after valid prefix. + let mut truncated = prefix_doc.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 trunc_points = Vec::new(); + let trunc_err = decode_te_data_stream( + FixedStepReader::new(&truncated, 5), + BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes: 4096, + }, + |p| trunc_points.push(owned_te_data_point(p)), + |off, err| panic!("terminal stream error must not reach on_error ({off}: {err})"), + ) + .unwrap_err(); + + assert_eq!(trunc_points.len(), 1); + assert_eq!(trunc_points[0].te_symbol, "USACPI"); + assert!(matches!( + trunc_err, + BsonStreamError::TruncatedDocument { + offset, + remaining: 7, + declared_len: Some(120), + } if offset == trunc_offset + )); + + // 2. Oversized trailing document (declared length > max_doc_bytes) after valid prefix. + let mut oversized = prefix_doc; + let oversize_offset = oversized.len() as u64; + oversized.extend_from_slice(&1024_i32.to_le_bytes()); + oversized.extend_from_slice(&[0x00; 16]); + + let mut oversize_points = Vec::new(); + let oversize_err = decode_te_data_stream( + FixedStepReader::new(&oversized, 5), + BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes: 512, + }, + |p| oversize_points.push(owned_te_data_point(p)), + |off, err| panic!("terminal stream error must not reach on_error ({off}: {err})"), + ) + .unwrap_err(); + + assert_eq!(oversize_points.len(), 1); + assert_eq!(oversize_points[0].te_symbol, "USACPI"); + assert!(matches!( + oversize_err, + BsonStreamError::CorruptDocumentLength { + offset, + declared_len: 1024, + max_doc_bytes: 512, + } if offset == oversize_offset + )); +} + +/// Builds a two-point teData doc whose byte length depends only on the string lengths, so +/// fixtures can be made of equal-length documents and chunk layouts are exact. +fn make_fixed_len_te_data_doc(te_symbol: &str, v0: f64, v1: f64) -> Vec { + make_te_data_doc( + Some(te_symbol), + "Canada", + "Inflation Rate", + &[("2024-01-31", v0), ("2024-02-29", v1)], + &[], + ) +} + +#[test] +fn te_data_stream_rebases_errors_at_nonzero_local_offsets_inside_later_multi_doc_chunks() { + // Arrange: six equal-length docs, chunk capacity = 2 docs, so every chunk holds exactly two + // documents and each offending document sits at local offset L inside a chunk with base 2L/4L. + // This separates `chunk.start_offset` from the in-chunk local offset, which single-doc chunks + // (local offset 0) cannot do. + let doc_a = make_fixed_len_te_data_doc("TEDOCA", 1.0, 1.5); + let len = doc_a.len(); + let doc_b = make_fixed_len_te_data_doc("TEDOCB", 2.0, 2.5); + let doc_c = make_fixed_len_te_data_doc("TEDOCC", 3.0, 3.5); + let doc_d_corrupt_top = make_corrupt_bson_doc(len); + let doc_e = make_fixed_len_te_data_doc("TEDOCE", 5.0, 5.5); + let mut doc_f_corrupt_point = make_fixed_len_te_data_doc("TEDOCF", 6.0, 6.5); + let second_d_pos = doc_f_corrupt_point + .windows(3) + .enumerate() + .filter(|(_, w)| *w == b"\x02d\0") + .nth(1) + .map(|(idx, _)| idx) + .expect("locate second point's 'd' element"); + doc_f_corrupt_point[second_d_pos] = 0x7E; + + let docs = [ + &doc_a, + &doc_b, + &doc_c, + &doc_d_corrupt_top, + &doc_e, + &doc_f_corrupt_point, + ]; + for d in docs { + assert_eq!(d.len(), len, "fixture docs must be equal length"); + } + let fixture: Vec = docs.iter().flat_map(|d| d.iter().copied()).collect(); + let opts = BsonStreamOptions { + chunk_capacity_bytes: 2 * len, + max_doc_bytes: 4096, + }; + + // Pin the chunk layout the assertions below rely on. + let mut layout_reader = + RawBsonChunkReader::with_options(Cursor::new(fixture.as_slice()), opts).unwrap(); + let mut layout = Vec::new(); + while let Some(chunk) = layout_reader.next_chunk().unwrap() { + layout.push((chunk.start_offset, chunk.bytes.len())); + } + let l = len as u64; + assert_eq!( + layout, + vec![(0, 2 * len), (2 * l, 2 * len), (4 * l, 2 * len)] + ); + + // Act: both entry points. + let mut stream_points = Vec::new(); + let mut stream_errs = Vec::new(); + let stream_stats = decode_te_data_stream( + Cursor::new(fixture.as_slice()), + opts, + |p| stream_points.push(owned_te_data_point(p)), + |off, err| stream_errs.push((off, err)), + ) + .unwrap(); + + let mut chunk_reader = + RawBsonChunkReader::with_options(Cursor::new(fixture.as_slice()), opts).unwrap(); + let mut chunk_points = Vec::new(); + let mut chunk_errs = Vec::new(); + let chunk_stats = decode_te_data_chunks( + &mut chunk_reader, + |p| chunk_points.push(owned_te_data_point(p)), + |off, err| chunk_errs.push((off, err)), + ) + .unwrap(); + + // Assert: absolute offsets 3L and 5L both in the callback argument and the embedded error. + assert_eq!(stream_errs.len(), 2, "{stream_errs:?}"); + match &stream_errs[0] { + (abs, BsonTeDataError::CorruptBson { offset, .. }) => { + assert_eq!(*abs, 3 * l); + assert_eq!(*offset as u64, 3 * l); + } + other => panic!("expected CorruptBson at {}, got {other:?}", 3 * l), + } + match &stream_errs[1] { + ( + abs, + BsonTeDataError::CorruptPointBson { + offset, + point_index, + .. + }, + ) => { + assert_eq!(*abs, 5 * l); + assert_eq!(*offset as u64, 5 * l); + assert_eq!(*point_index, 1); + } + other => panic!("expected CorruptPointBson at {}, got {other:?}", 5 * l), + } + assert_eq!(chunk_errs, stream_errs); + + let symbols: Vec<(&str, u64)> = stream_points + .iter() + .map(|p| (p.te_symbol.as_str(), p.value_bits)) + .collect(); + assert_eq!( + symbols, + vec![ + ("TEDOCA", 1.0_f64.to_bits()), + ("TEDOCA", 1.5_f64.to_bits()), + ("TEDOCB", 2.0_f64.to_bits()), + ("TEDOCB", 2.5_f64.to_bits()), + ("TEDOCC", 3.0_f64.to_bits()), + ("TEDOCC", 3.5_f64.to_bits()), + ("TEDOCE", 5.0_f64.to_bits()), + ("TEDOCE", 5.5_f64.to_bits()), + ("TEDOCF", 6.0_f64.to_bits()), + ] + ); + assert_eq!(chunk_points, stream_points); + + assert_eq!(stream_stats, chunk_stats); + assert_eq!(stream_stats.docs_in, 6); + assert_eq!(stream_stats.docs_accepted, 5); + assert_eq!(stream_stats.rejected_corrupt_document, 1); + assert_eq!(stream_stats.points_in, 10); + assert_eq!(stream_stats.points_decoded, 9); + assert_eq!(stream_stats.rejected_corrupt_point, 1); + assert_eq!( + stream_stats.docs_in, + stream_stats.docs_accepted + stream_stats.docs_rejected_total() + ); + assert_eq!( + stream_stats.points_in, + stream_stats.points_decoded + stream_stats.rejected_total() + ); + assert_eq!(chunk_reader.docs_framed(), 6); +} + +#[test] +fn te_data_rebase_preserves_payload_fields_and_saturates_offsets() { + // CorruptBson keeps its detail; CorruptPointBson keeps point_index and detail. + assert_eq!( + super::rebase_te_data_error( + 4_096, + BsonTeDataError::CorruptBson { + offset: 10, + detail: "bad top".to_owned(), + }, + ), + BsonTeDataError::CorruptBson { + offset: 4_106, + detail: "bad top".to_owned(), + } + ); + assert_eq!( + super::rebase_te_data_error( + 4_096, + BsonTeDataError::CorruptPointBson { + offset: 0, + point_index: 7, + detail: "bad point".to_owned(), + }, + ), + BsonTeDataError::CorruptPointBson { + offset: 4_096, + point_index: 7, + detail: "bad point".to_owned(), + } + ); + // Overflowing absolute offsets saturate instead of wrapping (shared `rebase_offset` policy). + assert_eq!( + super::rebase_te_data_error( + u64::MAX, + BsonTeDataError::CorruptBson { + offset: 1, + detail: String::new(), + }, + ), + BsonTeDataError::CorruptBson { + offset: usize::MAX, + detail: String::new(), + } + ); + // Point-level variants without an offset pass through unchanged. + let passthrough = BsonTeDataError::WrongPointFieldType { + point_index: 2, + field: "v", + actual: bson::spec::ElementType::String, + }; + assert_eq!( + super::rebase_te_data_error(9_999, passthrough.clone()), + passthrough + ); +} diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 3483d0ed..f59c8445 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -41,7 +41,9 @@ use crate::bson_qm_events::{ DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, DEFAULT_EARNINGS_KEY_FIELD, DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD, }; +use crate::bson_stream::BsonStreamOptions; use crate::curate_adj::AdjPointInTimeFence; +use crate::ilp::IlpWriterOptions; use crate::mongo_stream::{ MongoCliOptions, MongoUriSource, DEFAULT_MONGO_BATCH_SIZE, DEFAULT_MONGO_URI_ENV, MAX_MONGO_BATCH_SIZE, @@ -50,9 +52,11 @@ use crate::run_curate_adj::CurateAdjFactorsArgs; use crate::run_curate_bars::{ default_curate_bars_threads, CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE, }; +use crate::run_curate_bars_1m::{CurateBars1mArgs, DEFAULT_BARS_1M_MAPPING_SOURCE}; use crate::run_curate_corporate_actions::CurateCorporateActionsArgs; use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE}; use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; +use crate::run_curate_fx_1m::CurateFx1mArgs; use crate::run_curate_posts::{ CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE, }; @@ -80,6 +84,8 @@ pub enum CliAction { CurateShortsMongo(CurateShortsMongoArgs), CurateEvents(CurateEventsArgs), CurateEventsMongo(CurateEventsMongoArgs), + CurateBars1m(CurateBars1mArgs), + CurateFx1m(CurateFx1mArgs), CuratePosts(CuratePostsArgs), BenchSplit(usize), BenchAdj(usize), @@ -140,9 +146,12 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} curate-shorts --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ Curate shorts from ceoShorts BSON or read-only MongoDB + provider_mapping TSV into shorts/part.parquet (defaults: --key-field {DEFAULT_KEY_FIELD}, --report-date-field {DEFAULT_REPORT_DATE_FIELD}, --mapping-source {DEFAULT_MAPPING_SOURCE})\n\ {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ - {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ {name} curate-events --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ Curate events from qmFilings + qmEarnings BSON or read-only MongoDB + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\ + {name} curate-bars-1m --eod-intraday --qm-splits --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ + Curate split-unadjusted 1-minute bars from eodIntraday1M + qmSplits BSON + provider_mapping TSV into bars_1m.shard-.ilp (default --mapping-source: {DEFAULT_BARS_1M_MAPPING_SOURCE})\n\ + {name} curate-fx-1m --eod-intraday --out --shards \n\ + Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-.ilp\n\ {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ Curate ceoPosts from BSON + provider_mapping TSV into /events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\ {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ @@ -193,6 +202,8 @@ pub fn format_usage_stderr(name: &str) -> String { {name} curate-fx-1d --eod-prices --te-market-data [--te-symbol ] --out \n\ {name} curate-shorts --ceo-shorts --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ + {name} curate-bars-1m --eod-intraday --qm-splits --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ + {name} curate-fx-1m --eod-intraday --out --shards \n\ {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ {name} bench-split [rows]\n\ {name} bench-adj [events]\n\ @@ -1552,6 +1563,261 @@ fn parse_curate_events_args(args: &[&str]) -> Result { Ok(CliAction::CurateEvents(parsed)) } +fn parse_curate_bars_1m_args(args: &[&str]) -> Result { + let mut intraday_path: Option = None; + let mut splits_path: Option = None; + let mut provider_mapping_path: Option = None; + let mut out_dir: Option = None; + let mut shard_count: Option = None; + let mut known_at_micros: Option = None; + let mut mapping_source: Option = None; + + let mut i = 0usize; + while i < args.len() { + let token = args[i]; + if !token.starts_with("--") { + return Err(format!( + "unexpected positional argument '{token}' for curate-bars-1m" + )); + } + + let flag_name = token.split_once('=').map_or(token, |(k, _)| k); + if matches!( + flag_name, + "--from-mongo" + | "--mongo-uri" + | "--mongo-uri-env" + | "--batch-size" + | "--limit" + | "--date-gte" + | "--date-lt" + | "--with-qm-prices" + ) { + return Err(format!( + "MongoDB streaming flag '{flag_name}' is not supported by curate-bars-1m (file mode only)" + )); + } + + let (flag, value) = if let Some((k, v)) = token.split_once('=') { + i += 1; + (k, v) + } else { + let Some(&v) = args.get(i + 1) else { + return Err(format!("missing value for flag '{token}'")); + }; + if v.starts_with("--") { + return Err(format!("missing value for flag '{token}'")); + } + i += 2; + (token, v) + }; + + let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(PathBuf::from(raw)); + Ok(()) + }; + + let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.trim().is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(raw.to_string()); + Ok(()) + }; + + match flag { + "--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?, + "--qm-splits" => set_path(&mut splits_path, "--qm-splits", value)?, + "--provider-mapping" => { + set_path(&mut provider_mapping_path, "--provider-mapping", value)?; + } + "--out" => set_path(&mut out_dir, "--out", value)?, + "--shards" => { + if shard_count.is_some() { + return Err("duplicate flag '--shards'".to_string()); + } + if value.is_empty() { + return Err("empty value for flag '--shards'".to_string()); + } + if !value.bytes().all(|b| b.is_ascii_digit()) { + return Err(format!( + "invalid --shards '{value}' (expected a positive integer >= 1)" + )); + } + let parsed = value.parse::().map_err(|_| { + format!("invalid --shards '{value}' (expected a positive integer >= 1)") + })?; + if parsed == 0 { + return Err(format!( + "invalid --shards '{value}' (expected a positive integer >= 1)" + )); + } + shard_count = Some(parsed); + } + "--known-at-micros" => { + if known_at_micros.is_some() { + return Err("duplicate flag '--known-at-micros'".to_string()); + } + if value.is_empty() { + return Err("empty value for flag '--known-at-micros'".to_string()); + } + if !value.bytes().all(|b| b.is_ascii_digit()) { + return Err(format!( + "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" + )); + } + let parsed = value.parse::().map_err(|_| { + format!( + "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" + ) + })?; + if parsed <= 0 { + return Err(format!( + "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" + )); + } + known_at_micros = Some(parsed); + } + "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, + other => return Err(format!("unknown flag '{other}' for curate-bars-1m")), + } + } + + let intraday_path = + intraday_path.ok_or_else(|| "missing required flag '--eod-intraday'".to_string())?; + let splits_path = + splits_path.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?; + let provider_mapping_path = provider_mapping_path + .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let shard_count = + shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; + let known_at_micros = + known_at_micros.ok_or_else(|| "missing required flag '--known-at-micros'".to_string())?; + + Ok(CliAction::CurateBars1m(CurateBars1mArgs { + intraday_path, + splits_path, + provider_mapping_path, + out_dir, + mapping_source: mapping_source + .unwrap_or_else(|| DEFAULT_BARS_1M_MAPPING_SOURCE.to_string()), + shard_count, + known_at_micros, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + })) +} + +fn parse_curate_fx_1m_args(args: &[&str]) -> Result { + let mut intraday_path: Option = None; + let mut out_dir: Option = None; + let mut shard_count: Option = None; + + let mut i = 0usize; + while i < args.len() { + let token = args[i]; + if !token.starts_with("--") { + return Err(format!( + "unexpected positional argument '{token}' for curate-fx-1m" + )); + } + + let flag_name = token.split_once('=').map_or(token, |(k, _)| k); + if matches!( + flag_name, + "--from-mongo" + | "--mongo-uri" + | "--mongo-uri-env" + | "--batch-size" + | "--limit" + | "--date-gte" + | "--date-lt" + | "--with-qm-prices" + ) { + return Err(format!( + "MongoDB streaming flag '{flag_name}' is not supported by curate-fx-1m (file mode only)" + )); + } + + let (flag, value) = if let Some((k, v)) = token.split_once('=') { + i += 1; + (k, v) + } else { + let Some(&v) = args.get(i + 1) else { + return Err(format!("missing value for flag '{token}'")); + }; + if v.starts_with("--") { + return Err(format!("missing value for flag '{token}'")); + } + i += 2; + (token, v) + }; + + let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(PathBuf::from(raw)); + Ok(()) + }; + + match flag { + "--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?, + "--out" => set_path(&mut out_dir, "--out", value)?, + "--shards" => { + if shard_count.is_some() { + return Err("duplicate flag '--shards'".to_string()); + } + if value.is_empty() { + return Err("empty value for flag '--shards'".to_string()); + } + if !value.bytes().all(|b| b.is_ascii_digit()) { + return Err(format!( + "invalid --shards '{value}' (expected a positive integer >= 1)" + )); + } + let parsed = value.parse::().map_err(|_| { + format!("invalid --shards '{value}' (expected a positive integer >= 1)") + })?; + if parsed == 0 { + return Err(format!( + "invalid --shards '{value}' (expected a positive integer >= 1)" + )); + } + shard_count = Some(parsed); + } + other => return Err(format!("unknown flag '{other}' for curate-fx-1m")), + } + } + + let intraday_path = + intraday_path.ok_or_else(|| "missing required flag '--eod-intraday'".to_string())?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let shard_count = + shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; + + Ok(CliAction::CurateFx1m(CurateFx1mArgs { + intraday_path, + out_dir, + shard_count, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + })) +} + /// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`]. pub fn parse_args(args: &[String]) -> Result { let slices: Vec<&str> = args.iter().map(String::as_str).collect(); @@ -1567,6 +1833,8 @@ pub fn parse_args(args: &[String]) -> Result { ["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest), ["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest), ["curate-events", rest @ ..] => parse_curate_events_args(rest), + ["curate-bars-1m", rest @ ..] => parse_curate_bars_1m_args(rest), + ["curate-fx-1m", rest @ ..] => parse_curate_fx_1m_args(rest), ["curate-posts", rest @ ..] => parse_curate_posts_args(rest), ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), ["bench-split", raw] => match raw.parse::() { @@ -3591,6 +3859,576 @@ mod tests { assert!(parse_args(&to_args(&["bench-fundamentals", "1", "2"])).is_err()); } + #[test] + fn parse_curate_bars_1m_valid_default_and_explicit_mapping_source() { + let parsed = parse_args(&to_args(&[ + "curate-bars-1m", + "--eod-intraday", + "intraday.bson", + "--qm-splits", + "splits.bson", + "--provider-mapping", + "mapping.tsv", + "--out", + "out_dir", + "--shards", + "4", + "--known-at-micros", + "1735689600000000", + ])) + .expect("valid curate-bars-1m args with default mapping source"); + + assert_eq!( + parsed, + CliAction::CurateBars1m(CurateBars1mArgs { + intraday_path: PathBuf::from("intraday.bson"), + splits_path: PathBuf::from("splits.bson"), + provider_mapping_path: PathBuf::from("mapping.tsv"), + out_dir: PathBuf::from("out_dir"), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 4, + known_at_micros: 1_735_689_600_000_000, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + ); + + let parsed_eq = parse_args(&to_args(&[ + "curate-bars-1m", + "--eod-intraday=i2.bson", + "--qm-splits=s2.bson", + "--provider-mapping=m2.tsv", + "--out=o2", + "--shards=2", + "--known-at-micros=9223372036854775807", + "--mapping-source=eod_alt", + ])) + .expect("valid curate-bars-1m args with equals form and explicit mapping source"); + + assert_eq!( + parsed_eq, + CliAction::CurateBars1m(CurateBars1mArgs { + intraday_path: PathBuf::from("i2.bson"), + splits_path: PathBuf::from("s2.bson"), + provider_mapping_path: PathBuf::from("m2.tsv"), + out_dir: PathBuf::from("o2"), + mapping_source: "eod_alt".to_string(), + shard_count: 2, + known_at_micros: i64::MAX, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + ); + } + + #[test] + fn curate_bars_1m_usage_mentions_command_and_all_flags() { + let expected_flags = [ + "--eod-intraday", + "--qm-splits", + "--provider-mapping", + "--out", + "--shards", + "--known-at-micros", + "--mapping-source", + ]; + let usage = format_usage("curate-etl", "0.1.0"); + let usage_stderr = format_usage_stderr("curate-etl"); + let usage_line = usage + .lines() + .find(|line| line.trim_start().starts_with("curate-etl curate-bars-1m ")) + .expect("format_usage missing curate-bars-1m command line"); + let stderr_line = usage_stderr + .lines() + .find(|line| line.trim_start().starts_with("curate-etl curate-bars-1m ")) + .expect("format_usage_stderr missing curate-bars-1m command line"); + for flag in expected_flags { + assert!( + usage_line.contains(flag), + "format_usage curate-bars-1m line missing {flag}: {usage_line}" + ); + assert!( + stderr_line.contains(flag), + "format_usage_stderr curate-bars-1m line missing {flag}: {stderr_line}" + ); + } + } + + #[test] + fn parse_curate_bars_1m_rejects_missing_required_flags() { + let required: [(&str, &str); 6] = [ + ("--eod-intraday", "intraday.bson"), + ("--qm-splits", "splits.bson"), + ("--provider-mapping", "mapping.tsv"), + ("--out", "out_dir"), + ("--shards", "2"), + ("--known-at-micros", "1735689600000000"), + ]; + + for omit in 0..required.len() { + let mut argv: Vec<&str> = vec!["curate-bars-1m"]; + for (idx, &(flag, val)) in required.iter().enumerate() { + if idx != omit { + argv.push(flag); + argv.push(val); + } + } + let err = parse_args(&to_args(&argv)).unwrap_err(); + let missing_flag = required[omit].0; + assert!( + err.contains(&format!("missing required flag '{missing_flag}'")), + "expected missing required flag '{missing_flag}', got: {err}" + ); + } + } + + #[test] + fn parse_curate_bars_1m_rejects_duplicates_empty_missing_value_unknown_and_positional() { + let base = [ + "curate-bars-1m", + "--eod-intraday", + "i.bson", + "--qm-splits", + "s.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + "--mapping-source", + "eod", + ]; + + // Duplicate flags (path, numeric, and name). + for (flag, extra_val) in [ + ("--eod-intraday", "i2.bson"), + ("--qm-splits", "s2.bson"), + ("--provider-mapping", "m2.tsv"), + ("--out", "o2"), + ("--shards", "3"), + ("--known-at-micros", "2000"), + ("--mapping-source", "eod"), + ] { + let mut argv = base.to_vec(); + argv.push(flag); + argv.push(extra_val); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains(&format!("duplicate flag '{flag}'")), + "expected duplicate error for {flag}, got: {err}" + ); + } + + // Empty values via --flag= and whitespace-only --mapping-source. + for flag in [ + "--eod-intraday", + "--qm-splits", + "--provider-mapping", + "--out", + "--shards", + "--known-at-micros", + "--mapping-source", + ] { + let empty_token = format!("{flag}="); + let err = parse_args(&to_args(&["curate-bars-1m", &empty_token])).unwrap_err(); + assert!( + err.contains(&format!("empty value for flag '{flag}'")), + "expected empty value error for {flag}, got: {err}" + ); + } + let err = parse_args(&to_args(&["curate-bars-1m", "--mapping-source", " "])).unwrap_err(); + assert!( + err.contains("empty value for flag '--mapping-source'"), + "{err}" + ); + + // Flag at end of input or followed by another flag. + let err = parse_args(&to_args(&["curate-bars-1m", "--eod-intraday"])).unwrap_err(); + assert!( + err.contains("missing value for flag '--eod-intraday'"), + "{err}" + ); + let err = parse_args(&to_args(&[ + "curate-bars-1m", + "--shards", + "--out", + "o", + ])) + .unwrap_err(); + assert!(err.contains("missing value for flag '--shards'"), "{err}"); + + // Unknown flag. + let mut unknown = base.to_vec(); + unknown.push("--nope"); + unknown.push("1"); + let err = parse_args(&to_args(&unknown)).unwrap_err(); + assert!( + err.contains("unknown flag '--nope' for curate-bars-1m"), + "{err}" + ); + + // Positional argument. + let err = parse_args(&to_args(&["curate-bars-1m", "positional"])).unwrap_err(); + assert!( + err.contains("unexpected positional argument 'positional' for curate-bars-1m"), + "{err}" + ); + } + + #[test] + fn parse_curate_bars_1m_rejects_invalid_numeric_flags() { + let base_without_shards = [ + "curate-bars-1m", + "--eod-intraday", + "i.bson", + "--qm-splits", + "s.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--known-at-micros", + "1000", + ]; + + for bad_shards in [ + "0", + "-1", + "+1", + "abc", + "1.5", + "999999999999999999999999999999999999999", + ] { + let mut argv = base_without_shards.to_vec(); + argv.push("--shards"); + argv.push(bad_shards); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains("invalid --shards"), + "expected invalid --shards for '{bad_shards}', got: {err}" + ); + } + + let base_without_known_at = [ + "curate-bars-1m", + "--eod-intraday", + "i.bson", + "--qm-splits", + "s.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + ]; + + for bad_known_at in [ + "0", + "-1", + "-9223372036854775808", + "+1000", + "abc", + "1.5", + "9223372036854775808", + "999999999999999999999999999999", + ] { + let mut argv = base_without_known_at.to_vec(); + argv.push("--known-at-micros"); + argv.push(bad_known_at); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains("invalid --known-at-micros"), + "expected invalid --known-at-micros for '{bad_known_at}', got: {err}" + ); + } + } + + #[test] + fn parse_curate_bars_1m_rejects_all_mongo_streaming_flags_without_echoing_values() { + let mongo_flags = [ + "--from-mongo", + "--mongo-uri", + "--mongo-uri-env", + "--batch-size", + "--limit", + "--date-gte", + "--date-lt", + "--with-qm-prices", + ]; + + let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; + for flag in mongo_flags { + // Bare form (at end of argv). + let err_bare = parse_args(&to_args(&["curate-bars-1m", flag])).unwrap_err(); + assert!( + err_bare.contains(flag) && err_bare.contains("file mode only"), + "bare {flag} should fail with file-mode error, got: {err_bare}" + ); + + // Separated value form. + let err_sep = parse_args(&to_args(&["curate-bars-1m", flag, secret])).unwrap_err(); + assert!( + err_sep.contains(flag) && err_sep.contains("file mode only"), + "separated {flag} should fail with file-mode error, got: {err_sep}" + ); + assert!( + !err_sep.contains("s3cr3t_pw"), + "separated {flag} error leaked value: {err_sep}" + ); + + // Equals form. + let eq_token = format!("{flag}={secret}"); + let err_eq = parse_args(&to_args(&["curate-bars-1m", &eq_token])).unwrap_err(); + assert!( + err_eq.contains(flag) && err_eq.contains("file mode only"), + "equals {flag} should fail with file-mode error, got: {err_eq}" + ); + assert!( + !err_eq.contains("s3cr3t_pw"), + "equals {flag} error leaked value: {err_eq}" + ); + } + } + + #[test] + fn parse_curate_fx_1m_valid_space_and_equals_forms() { + let expected = CliAction::CurateFx1m(CurateFx1mArgs { + intraday_path: PathBuf::from("A"), + out_dir: PathBuf::from("B"), + shard_count: 4, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }); + + let parsed_space = parse_args(&to_args(&[ + "curate-fx-1m", + "--eod-intraday", + "A", + "--out", + "B", + "--shards", + "4", + ])) + .expect("valid curate-fx-1m args in space form"); + assert_eq!(parsed_space, expected); + + let parsed_eq = parse_args(&to_args(&[ + "curate-fx-1m", + "--eod-intraday=A", + "--out=B", + "--shards=4", + ])) + .expect("valid curate-fx-1m args in equals form"); + assert_eq!(parsed_eq, expected); + } + + #[test] + fn curate_fx_1m_usage_mentions_command_and_all_flags() { + let expected_flags = ["--eod-intraday", "--out", "--shards"]; + let usage = format_usage("curate-etl", "0.1.0"); + let usage_stderr = format_usage_stderr("curate-etl"); + let usage_line = usage + .lines() + .find(|line| line.trim_start().starts_with("curate-etl curate-fx-1m ")) + .expect("format_usage missing curate-fx-1m command line"); + let stderr_line = usage_stderr + .lines() + .find(|line| line.trim_start().starts_with("curate-etl curate-fx-1m ")) + .expect("format_usage_stderr missing curate-fx-1m command line"); + for flag in expected_flags { + assert!( + usage_line.contains(flag), + "format_usage curate-fx-1m line missing {flag}: {usage_line}" + ); + assert!( + stderr_line.contains(flag), + "format_usage_stderr curate-fx-1m line missing {flag}: {stderr_line}" + ); + } + } + + #[test] + fn parse_curate_fx_1m_rejects_missing_required_flags() { + let required: [(&str, &str); 3] = [ + ("--eod-intraday", "intraday.bson"), + ("--out", "out_dir"), + ("--shards", "4"), + ]; + + for omit in 0..required.len() { + let mut argv: Vec<&str> = vec!["curate-fx-1m"]; + for (idx, &(flag, val)) in required.iter().enumerate() { + if idx != omit { + argv.push(flag); + argv.push(val); + } + } + let err = parse_args(&to_args(&argv)).unwrap_err(); + let missing_flag = required[omit].0; + assert!( + err.contains(&format!("missing required flag '{missing_flag}'")), + "expected missing required flag '{missing_flag}', got: {err}" + ); + } + } + + #[test] + fn parse_curate_fx_1m_rejects_duplicates_empty_missing_value_unknown_and_positional() { + let base = [ + "curate-fx-1m", + "--eod-intraday", + "i.bson", + "--out", + "o", + "--shards", + "4", + ]; + + // Duplicate flags (path and numeric). + for (flag, extra_val) in [ + ("--eod-intraday", "i2.bson"), + ("--out", "o2"), + ("--shards", "2"), + ] { + let mut argv = base.to_vec(); + argv.push(flag); + argv.push(extra_val); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains(&format!("duplicate flag '{flag}'")), + "expected duplicate error for {flag}, got: {err}" + ); + } + + // Empty values via --flag=. + for flag in ["--eod-intraday", "--out", "--shards"] { + let empty_token = format!("{flag}="); + let err = parse_args(&to_args(&["curate-fx-1m", &empty_token])).unwrap_err(); + assert!( + err.contains(&format!("empty value for flag '{flag}'")), + "expected empty value error for {flag}, got: {err}" + ); + } + + // Flag at end of input or followed by another flag. + let err = parse_args(&to_args(&["curate-fx-1m", "--eod-intraday"])).unwrap_err(); + assert!( + err.contains("missing value for flag '--eod-intraday'"), + "{err}" + ); + let err = parse_args(&to_args(&["curate-fx-1m", "--shards", "--out", "o"])).unwrap_err(); + assert!(err.contains("missing value for flag '--shards'"), "{err}"); + + // Unknown flag. + let mut unknown = base.to_vec(); + unknown.push("--nope"); + unknown.push("1"); + let err = parse_args(&to_args(&unknown)).unwrap_err(); + assert!( + err.contains("unknown flag '--nope' for curate-fx-1m"), + "{err}" + ); + + // Bars-only flags must be rejected as unknown flags. + for (flag, val) in [ + ("--qm-splits", "splits.bson"), + ("--provider-mapping", "mapping.tsv"), + ("--known-at-micros", "1735689600000000"), + ("--mapping-source", "eod"), + ] { + let mut argv = base.to_vec(); + argv.push(flag); + argv.push(val); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains(&format!("unknown flag '{flag}' for curate-fx-1m")), + "expected unknown flag error for {flag}, got: {err}" + ); + } + + // Positional argument. + let err = parse_args(&to_args(&["curate-fx-1m", "positional"])).unwrap_err(); + assert!( + err.contains("unexpected positional argument 'positional' for curate-fx-1m"), + "{err}" + ); + } + + #[test] + fn parse_curate_fx_1m_rejects_invalid_shards() { + let base_without_shards = [ + "curate-fx-1m", + "--eod-intraday", + "i.bson", + "--out", + "o", + ]; + + for bad_shards in [ + "0", + "-1", + "+1", + "1.5", + "abc", + "999999999999999999999999999999999999999", + ] { + let mut argv = base_without_shards.to_vec(); + argv.push("--shards"); + argv.push(bad_shards); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains("invalid --shards"), + "expected invalid --shards for '{bad_shards}', got: {err}" + ); + } + } + + #[test] + fn parse_curate_fx_1m_rejects_all_mongo_streaming_flags_without_echoing_values() { + let mongo_flags = [ + "--from-mongo", + "--mongo-uri", + "--mongo-uri-env", + "--batch-size", + "--limit", + "--date-gte", + "--date-lt", + "--with-qm-prices", + ]; + + let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; + for flag in mongo_flags { + let expected = format!( + "MongoDB streaming flag '{flag}' is not supported by curate-fx-1m (file mode only)" + ); + + // Bare form (at end of argv). + let err_bare = parse_args(&to_args(&["curate-fx-1m", flag])).unwrap_err(); + assert_eq!(err_bare, expected, "bare {flag} error mismatch"); + + // Separated value form. + let err_sep = parse_args(&to_args(&["curate-fx-1m", flag, secret])).unwrap_err(); + assert_eq!(err_sep, expected, "separated {flag} error mismatch"); + assert!( + !err_sep.contains("s3cr3t_pw"), + "separated {flag} error leaked value: {err_sep}" + ); + + // Equals form. + let eq_token = format!("{flag}={secret}"); + let err_eq = parse_args(&to_args(&["curate-fx-1m", &eq_token])).unwrap_err(); + assert_eq!(err_eq, expected, "equals {flag} error mismatch"); + assert!( + !err_eq.contains("s3cr3t_pw"), + "equals {flag} error leaked value: {err_eq}" + ); + } + } + #[test] fn curate_posts_parsing_validation_and_usage() { let usage = format_usage("curate-etl", "0.1.0"); diff --git a/tools/curate-etl/src/curate_bars_1m.rs b/tools/curate-etl/src/curate_bars_1m.rs index 849ebbc7..f8c7689f 100644 --- a/tools/curate-etl/src/curate_bars_1m.rs +++ b/tools/curate-etl/src/curate_bars_1m.rs @@ -33,7 +33,7 @@ use crate::bson_eod_intraday::BsonEodIntradayDecodeStats; use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; use crate::ilp::{IlpShardedWriter, IlpWriterError}; use crate::provider_mapping::ProviderMappingTable; -use crate::split::SplitTable; +use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable}; /// Accounting summary produced alongside [`CurateBars1mOutput::rows`]. /// @@ -185,14 +185,36 @@ fn bar_1m_values_bit_eq(a: &Bar1mRow, b: &Bar1mRow) -> bool { && a.session == b.session } +#[inline] +fn is_valid_price(price: f64) -> bool { + price.is_finite() && price > 0.0 +} + +#[inline] +fn is_consistent_ohlc(open: f64, high: f64, low: f64, close: f64) -> bool { + high >= low && open >= low && open <= high && close >= low && close <= high +} + +#[inline] +fn decrement_builder_session_count(stats: &mut Bars1mStats, session: IntradaySession) { + match session { + IntradaySession::Pre => stats.pre_rows_out -= 1, + IntradaySession::Rth => stats.rth_rows_out -= 1, + IntradaySession::Post => stats.post_rows_out -= 1, + } +} + /// Maps source-keyed [`Bars1mBuild`] rows to permanent `listing_id: i32` keys via -/// `provider_mapping` on each bar's Eastern Time `session_date`, stamps `source`, re-sorts in -/// place by `(listing_id, ts)`, and compacts cross-`source_id` collisions. -pub(crate) fn map_bars_1m( +/// `provider_mapping` on each bar's Eastern Time `session_date`, optionally un-adjusts OHLCV via +/// `listing_splits` (keyed by permanent `listing_id`, preventing split leakage across reused +/// tickers), stamps `source`, re-sorts in place by `(listing_id, ts)`, and compacts +/// cross-`source_id` collisions. +fn map_bars_1m_impl( built: Bars1mBuild, provider_mapping: &ProviderMappingTable, mapping_source: &str, source: &'static str, + listing_splits: Option<&SplitTable>, ) -> CurateBars1mOutput where K: Eq + AsRef, @@ -222,25 +244,84 @@ where continue; } + let mut key_kept_or_unmapped = false; for bar in &built.rows[run_start..run_end] { let Some(listing_id) = cursor.resolve(bar.session_date) else { stats.dropped_unmapped += 1; + key_kept_or_unmapped = true; continue; }; + let (open, high, low, close, volume) = if let Some(splits) = listing_splits { + let factor = splits.cum_factor_after(&listing_id, bar.session_date); + if factor != 1.0 { + let mut unadj = unadjust_ohlcv( + OhlcvBar { + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + }, + factor, + ); + if !is_valid_price(unadj.open) + || !is_valid_price(unadj.high) + || !is_valid_price(unadj.low) + || !is_valid_price(unadj.close) + { + stats.builder.dropped_invalid_ohlc += 1; + stats.builder.rows_out -= 1; + decrement_builder_session_count(&mut stats.builder, bar.session); + stats.rows_in -= 1; + continue; + } + if !is_consistent_ohlc(unadj.open, unadj.high, unadj.low, unadj.close) { + stats.builder.dropped_inconsistent_ohlc += 1; + stats.builder.rows_out -= 1; + decrement_builder_session_count(&mut stats.builder, bar.session); + stats.rows_in -= 1; + continue; + } + if !unadj.volume.is_finite() + || unadj.volume < 0.0 + || (bar.volume > 0.0 && unadj.volume == 0.0) + { + stats.builder.dropped_invalid_volume += 1; + stats.builder.rows_out -= 1; + decrement_builder_session_count(&mut stats.builder, bar.session); + stats.rows_in -= 1; + continue; + } + if unadj.volume == 0.0 { + unadj.volume = 0.0; + } + (unadj.open, unadj.high, unadj.low, unadj.close, unadj.volume) + } else { + (bar.open, bar.high, bar.low, bar.close, bar.volume) + } + } else { + (bar.open, bar.high, bar.low, bar.close, bar.volume) + }; + + key_kept_or_unmapped = true; rows.push(Bar1mRow { key: listing_id, ts: bar.ts, session_date: bar.session_date, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, + open, + high, + low, + close, + volume, session: bar.session, source, }); } + + if !key_kept_or_unmapped { + stats.builder.keys_out -= 1; + } } // Free builder rows before sorting/compacting mapped rows to cut peak RAM. @@ -306,6 +387,21 @@ where CurateBars1mOutput { rows, stats } } +/// Maps source-keyed [`Bars1mBuild`] rows to permanent `listing_id: i32` keys via +/// `provider_mapping` on each bar's Eastern Time `session_date`, stamps `source`, re-sorts in +/// place by `(listing_id, ts)`, and compacts cross-`source_id` collisions. +pub(crate) fn map_bars_1m( + built: Bars1mBuild, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, + source: &'static str, +) -> CurateBars1mOutput +where + K: Eq + AsRef, +{ + map_bars_1m_impl(built, provider_mapping, mapping_source, source, None) +} + /// Pure `bars_1m` curation stage: un-adjusts source-keyed `eodIntraday1M` bars via /// [`build_bars_1m`], resolves `(mapping_source, source_id, session_date) -> listing_id` through /// `provider_mapping` using each bar's Eastern Time `session_date`, and emits [`Bar1mRow`] @@ -389,6 +485,51 @@ where }) } +/// Variant of [`curate_and_write_bars_1m`] that takes a [`SplitTable`] keyed by permanent +/// `listing_id` and resolves `(mapping_source, source_id, session_date) -> listing_id` on each +/// bar's Eastern Time `session_date` **before** applying split un-adjustment. +/// +/// This prevents split leakage across reused tickers (e.g., `FB.US` listing 10 through June 2022 +/// vs. listing 20 starting in 2025) while preserving all [`CurateBars1mStats`] conservation +/// invariants and cross-`source_id` collision handling. +pub(crate) fn curate_and_write_bars_1m_by_listing( + bars: B, + listing_splits: &SplitTable, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, + writer: &mut IlpShardedWriter, + known_at_micros: i64, +) -> Result +where + W: Write + Send, + K: Ord + Eq + Hash + Clone + AsRef, + B: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CurateBars1mError::EmptyMappingSource.into()); + } + + let empty_splits: SplitTable = SplitTable::default(); + let built = build_bars_1m(bars, &empty_splits); + let curated = map_bars_1m_impl( + built, + provider_mapping, + mapping_source, + BARS_1M_SOURCE_EOD, + Some(listing_splits), + ); + let mut rows_written = 0usize; + for row in &curated.rows { + writer.write_bar_1m(row, known_at_micros)?; + rows_written += 1; + } + + Ok(CurateBars1mWriteReport { + curate_stats: curated.stats, + rows_written, + }) +} + /// Decodes a concatenated raw BSON `eodIntraday1M` stream via [`decode_eod_intraday_stream`], /// converts each valid document via [`crate::bson_eod_intraday::RawEodIntradayBar::into_eod_intraday_bar`], /// and runs [`curate_and_write_bars_1m`] against the caller-owned [`IlpShardedWriter`]. diff --git a/tools/curate-etl/src/ilp.rs b/tools/curate-etl/src/ilp.rs index 54a5691e..6130adfa 100644 --- a/tools/curate-etl/src/ilp.rs +++ b/tools/curate-etl/src/ilp.rs @@ -458,6 +458,13 @@ impl IlpShardedWriter { self.shards.len() } + /// Returns `(flushed_rows, pending_rows)` across all shards. + #[inline] + pub(crate) fn row_counts(&self) -> (usize, usize) { + let pending = self.shards.iter().map(|s| s.pending_rows).sum(); + (self.rows_written, pending) + } + /// Encodes and buffers one `bars_1m` row on the shard determined by `row.key`. pub fn write_bar_1m( &mut self, diff --git a/tools/curate-etl/src/ilp_send.rs b/tools/curate-etl/src/ilp_send.rs new file mode 100644 index 00000000..0685b1de --- /dev/null +++ b/tools/curate-etl/src/ilp_send.rs @@ -0,0 +1,851 @@ +//! Multi-socket QuestDB ILP v2 shard-file sender (`M2.3p`). +//! +//! Streams published `.shard-.ilp` files (produced by [`crate::run_curate_bars_1m`], +//! [`crate::run_curate_qm_bars_1m`], or [`crate::run_curate_fx_1m`]) verbatim over one dedicated +//! sink/socket per shard using `std::thread::scope`. +//! +//! # Transport & Acknowledgement Semantics +//! +//! - **No server acknowledgement over TCP:** QuestDB's TCP ILP listener sends no per-row or +//! per-batch acknowledgement. A server-side parse error or schema rejection surfaces only as a +//! dropped connection or missing rows. A successful [`send_ilp_shard_files`] return therefore +//! means **"all bytes were accepted by the local socket and write-half shutdown succeeded"**, +//! not **"all rows were committed in QuestDB"**. Verify row counts and representative values +//! separately via PGWire after loading. +//! - **Protocol Version 2 binary doubles over TCP (unverified for QuestDB `10.2.0`):** QuestDB's +//! ILP transport documentation () +//! documents explicit client-side protocol-version-2 selection for TCP without autodetection. +//! Exact QuestDB `10.2.0` acceptance of this crate's ILP v2 binary `DOUBLE` payloads (`0x10` + +//! 8-byte LE IEEE-754) on the TCP ILP port (default `9009`) without a handshake is +//! **unverified** — confirm it in the manual `quant` load check using PGWire row counts and +//! spot-checked OHLCV/FX values before bulk ingestion. +//! +//! # Data Ownership, Discovery & Replay Semantics +//! +//! - **Completed publisher output required:** [`discover_ilp_shard_files`] consumes a completed, +//! immutable publisher output directory. Filenames alone cannot detect an in-progress +//! publication or a missing trailing shard. +//! - **Byte-for-byte streaming:** Bytes are streamed verbatim in fixed-size chunks +//! (`IlpSendOptions::buffer_bytes`) without loading whole files into RAM and without splitting, +//! re-framing, or re-encoding lines (binary `f64` fields may legitimately contain `0x0A`). +//! - **Per-key ordering & idempotent resend:** Quant data curation owns the curated shard files +//! as the durable replay baseline for OHLCV, FX values, timestamps, `known_at`, and per-key +//! ordering (`design/DATA-CONTRACTS.md` §3.B, `design/MILESTONES.md` M2). Because each shard +//! streams over a single dedicated sink in file order, per-key ordering is preserved. On any +//! shard failure, [`IlpSendError::ShardIo`] includes a partial [`IlpSendReport`] with per-shard +//! `bytes_sent` so operators can re-send the full, identical shard set against QuestDB's +//! configured `DEDUP UPSERT KEYS(ts, listing_id)` (`bars_1m`) or `DEDUP UPSERT KEYS(ts, pair)` +//! (`fx_1m`). Avoid replaying stale shard files after newer data sharing the same upsert keys +//! has been ingested. +//! - **Resource scaling:** Threads, open sockets, and read-buffer memory scale linearly with +//! shard count (`shard_count * buffer_bytes`). + +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, Read, Write}; +use std::net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::thread; +use std::time::Duration; + +use crate::run_curate_bars_1m::is_final_shard_file_name_for_table; + +/// Default per-shard streaming read buffer size (64 KiB). +pub const DEFAULT_ILP_SEND_BUFFER_BYTES: usize = 64 * 1024; + +/// Default TCP connect timeout per shard socket (10 seconds). +pub const DEFAULT_ILP_TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10); + +/// Default TCP write timeout per shard socket (30 seconds). +pub const DEFAULT_ILP_TCP_WRITE_TIMEOUT: Duration = Duration::from_secs(30); + +/// A discovered, validated published ILP shard file (`.shard-.ilp`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IlpShardFile { + pub shard: usize, + pub path: PathBuf, +} + +/// Streaming options for [`send_ilp_shard_files`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct IlpSendOptions { + /// Fixed-size read buffer allocated per shard worker (must be `> 0`). + pub buffer_bytes: usize, +} + +impl Default for IlpSendOptions { + fn default() -> Self { + Self { + buffer_bytes: DEFAULT_ILP_SEND_BUFFER_BYTES, + } + } +} + +/// Socket options for [`tcp_ilp_connector`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct IlpTcpOptions { + /// Connect timeout applied to each shard socket (must be `> Duration::ZERO`). + pub connect_timeout: Duration, + /// Write timeout applied to each shard socket (must be `> Duration::ZERO`). + pub write_timeout: Duration, +} + +impl Default for IlpTcpOptions { + fn default() -> Self { + Self { + connect_timeout: DEFAULT_ILP_TCP_CONNECT_TIMEOUT, + write_timeout: DEFAULT_ILP_TCP_WRITE_TIMEOUT, + } + } +} + +/// Per-shard delivery summary recorded in [`IlpSendReport`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IlpShardSendReport { + pub shard: usize, + pub path: PathBuf, + pub bytes_sent: u64, +} + +/// Delivery summary returned by [`send_ilp_shard_files`] (and attached as a partial report on +/// [`IlpSendError::ShardIo`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IlpSendReport { + pub shards: Vec, + pub total_shards: usize, + pub total_bytes_sent: u64, +} + +/// Operation stage in which a per-shard I/O failure occurred. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IlpSendOp { + SpawnWorker, + OpenFile, + Connect, + Read, + Write, + Flush, +} + +impl fmt::Display for IlpSendOp { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::SpawnWorker => f.write_str("spawn_worker"), + Self::OpenFile => f.write_str("open_file"), + Self::Connect => f.write_str("connect"), + Self::Read => f.write_str("read"), + Self::Write => f.write_str("write"), + Self::Flush => f.write_str("flush"), + } + } +} + +/// Typed errors returned by [`discover_ilp_shard_files`], [`send_ilp_shard_files`], and +/// [`tcp_ilp_connector`]. +#[derive(Debug)] +pub enum IlpSendError { + /// Shard prefix was empty or contained characters outside `[A-Za-z0-9_-]`. + InvalidPrefix { prefix: String }, + /// Target directory exists but is not a directory. + InvalidDirectory { path: PathBuf, detail: String }, + /// Failed to stat or read the shard directory. + ReadDir { path: PathBuf, source: io::Error }, + /// No `.shard-.ilp` files matched in `dir`. + NoShardFiles { dir: PathBuf, prefix: String }, + /// A matching shard file's numeric suffix overflowed `usize`. + ShardIndexOverflow { path: PathBuf, digits: String }, + /// A matching entry was not a regular file (for example, a directory or symlink). + NotRegularFile { path: PathBuf, detail: String }, + /// Two matching files resolved to the same numeric shard index (e.g. `shard-0` and `shard-00`). + DuplicateShardIndex { + shard: usize, + first: PathBuf, + second: PathBuf, + }, + /// Discovered shard indices did not form a contiguous `0..n` sequence. + MissingShardIndex { + expected: usize, + found: usize, + path: PathBuf, + }, + /// `IlpSendOptions::buffer_bytes` was zero. + ZeroBufferBytes, + /// TCP target address was empty, malformed, or could not be resolved. + InvalidAddress { addr: String, detail: String }, + /// A TCP timeout option was zero. + InvalidTimeout { field: &'static str }, + /// One or more shards failed during open, connect, read, write, or flush. + /// + /// `op`, `shard`, `path`, and `source` identify the lowest-index failing shard; + /// `partial_report` records `bytes_sent` for every shard after all workers finish. + ShardIo { + op: IlpSendOp, + shard: usize, + path: PathBuf, + source: io::Error, + partial_report: IlpSendReport, + }, +} + +impl IlpSendError { + /// Returns the partial delivery report when this error is [`IlpSendError::ShardIo`]. + pub fn partial_report(&self) -> Option<&IlpSendReport> { + match self { + Self::ShardIo { partial_report, .. } => Some(partial_report), + _ => None, + } + } +} + +impl fmt::Display for IlpSendError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidPrefix { prefix } => write!( + f, + "invalid ILP shard prefix {prefix:?}: must be non-empty ASCII [A-Za-z0-9_-]" + ), + Self::InvalidDirectory { path, detail } => { + write!(f, "invalid ILP shard directory '{}': {detail}", path.display()) + } + Self::ReadDir { path, source } => { + write!(f, "failed to read ILP shard directory '{}': {source}", path.display()) + } + Self::NoShardFiles { dir, prefix } => write!( + f, + "no ILP shard files matching '{prefix}.shard-.ilp' in '{}'", + dir.display() + ), + Self::ShardIndexOverflow { path, digits } => write!( + f, + "ILP shard index '{digits}' overflows usize in '{}'", + path.display() + ), + Self::NotRegularFile { path, detail } => write!( + f, + "ILP shard path '{}' is not a regular file: {detail}", + path.display() + ), + Self::DuplicateShardIndex { + shard, + first, + second, + } => write!( + f, + "duplicate ILP shard index {shard}: '{}' and '{}'", + first.display(), + second.display() + ), + Self::MissingShardIndex { + expected, + found, + path, + } => write!( + f, + "missing ILP shard index {expected}: next shard is {found} ('{}')", + path.display() + ), + Self::ZeroBufferBytes => write!(f, "ILP send buffer_bytes must be > 0"), + Self::InvalidAddress { addr, detail } => { + write!(f, "invalid ILP TCP address {addr:?}: {detail}") + } + Self::InvalidTimeout { field } => { + write!(f, "ILP TCP {field} must be > 0") + } + Self::ShardIo { + op, + shard, + path, + source, + partial_report, + } => write!( + f, + "ILP shard {shard} ('{}') failed during {op} ({source}; total_bytes_sent={})", + path.display(), + partial_report.total_bytes_sent + ), + } + } +} + +impl Error for IlpSendError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::ReadDir { source, .. } | Self::ShardIo { source, .. } => Some(source), + _ => None, + } + } +} + +/// Validates that `prefix` is non-empty and consists solely of ASCII letters, digits, `_`, or `-`. +fn validate_prefix(prefix: &str) -> Result<(), IlpSendError> { + if prefix.is_empty() + || !prefix + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') + { + return Err(IlpSendError::InvalidPrefix { + prefix: prefix.to_string(), + }); + } + Ok(()) +} + +/// Discovers published `.shard-.ilp` files in a completed output directory `dir`. +/// +/// Files are returned sorted by ascending numeric shard index `0..n`. Fails closed on: +/// - blank or invalid `prefix` (must match `[A-Za-z0-9_-]+`), +/// - missing or non-directory `dir`, +/// - zero matching files, +/// - any matching entry that is not a regular file (including symlinks and directories), +/// - numeric shard suffix overflowing `usize`, +/// - duplicate numeric shard indices (e.g. `shard-0` and `shard-00`), or +/// - any gap in `0..n`. +pub fn discover_ilp_shard_files( + dir: &Path, + prefix: &str, +) -> Result, IlpSendError> { + validate_prefix(prefix)?; + + let dir_meta = fs::metadata(dir).map_err(|source| IlpSendError::ReadDir { + path: dir.to_path_buf(), + source, + })?; + if !dir_meta.is_dir() { + return Err(IlpSendError::InvalidDirectory { + path: dir.to_path_buf(), + detail: "path exists and is not a directory".to_string(), + }); + } + + let entries = fs::read_dir(dir).map_err(|source| IlpSendError::ReadDir { + path: dir.to_path_buf(), + source, + })?; + + let mut discovered: Vec = Vec::new(); + for entry in entries { + let entry = entry.map_err(|source| IlpSendError::ReadDir { + path: dir.to_path_buf(), + source, + })?; + let file_name = entry.file_name(); + if !is_final_shard_file_name_for_table(prefix, &file_name) { + continue; + } + + let path = entry.path(); + let meta = fs::symlink_metadata(&path).map_err(|source| IlpSendError::ReadDir { + path: path.clone(), + source, + })?; + let file_type = meta.file_type(); + if file_type.is_symlink() { + return Err(IlpSendError::NotRegularFile { + path, + detail: "entry is a symlink".to_string(), + }); + } + if !file_type.is_file() { + let detail = if file_type.is_dir() { + "entry is a directory" + } else { + "entry is not a regular file" + }; + return Err(IlpSendError::NotRegularFile { + path, + detail: detail.to_string(), + }); + } + + let name_str = file_name + .to_str() + .expect("is_final_shard_file_name_for_table guarantees valid UTF-8"); + let digits = name_str + .strip_prefix(prefix) + .and_then(|s| s.strip_prefix(".shard-")) + .and_then(|s| s.strip_suffix(".ilp")) + .expect("is_final_shard_file_name_for_table guarantees shard filename shape"); + + let shard = digits + .parse::() + .map_err(|_| IlpSendError::ShardIndexOverflow { + path: path.clone(), + digits: digits.to_string(), + })?; + + discovered.push(IlpShardFile { shard, path }); + } + + if discovered.is_empty() { + return Err(IlpSendError::NoShardFiles { + dir: dir.to_path_buf(), + prefix: prefix.to_string(), + }); + } + + discovered.sort_by(|a, b| a.shard.cmp(&b.shard).then_with(|| a.path.cmp(&b.path))); + + for pair in discovered.windows(2) { + if pair[0].shard == pair[1].shard { + return Err(IlpSendError::DuplicateShardIndex { + shard: pair[0].shard, + first: pair[0].path.clone(), + second: pair[1].path.clone(), + }); + } + } + + for (expected, item) in discovered.iter().enumerate() { + if item.shard != expected { + return Err(IlpSendError::MissingShardIndex { + expected, + found: item.shard, + path: item.path.clone(), + }); + } + } + + Ok(discovered) +} + +/// Streams each shard file in `files` verbatim to its own sink opened via `connector`, running one +/// scoped worker thread per shard. +/// +/// Guarantees: +/// - Rejects `options.buffer_bytes == 0` before any file open or `connector` call. +/// - Opens each shard file before calling `connector(file.shard)`. +/// - Uses one reusable fixed-size read buffer per worker; never loads a whole file into memory and +/// never splits or re-encodes bytes. +/// - Calls `flush()` exactly once at EOF on every opened sink, including zero-length shard files. +/// - Joins every worker before returning; fails closed with [`IlpSendError::ShardIo`] carrying +/// the failing shard index, path, operation, `io::Error`, and full per-shard partial report if +/// any shard errors. +pub fn send_ilp_shard_files( + files: &[IlpShardFile], + connector: C, + options: IlpSendOptions, +) -> Result +where + W: Write + Send, + C: Fn(usize) -> io::Result + Sync, +{ + if options.buffer_bytes == 0 { + return Err(IlpSendError::ZeroBufferBytes); + } + + if files.is_empty() { + return Ok(IlpSendReport { + shards: Vec::new(), + total_shards: 0, + total_bytes_sent: 0, + }); + } + + let connector_ref = &connector; + let buffer_bytes = options.buffer_bytes; + + let outcomes: Vec = thread::scope(|scope| { + enum WorkerSlot<'scope> { + Running(thread::ScopedJoinHandle<'scope, ShardWorkerOutcome>), + SpawnFailed(io::Error), + } + + let mut slots = Vec::with_capacity(files.len()); + for shard_file in files { + let spawned = thread::Builder::new() + .name(format!("ilp-send-shard-{}", shard_file.shard)) + .spawn_scoped(scope, move || { + send_single_shard(shard_file, connector_ref, buffer_bytes) + }); + match spawned { + Ok(handle) => slots.push(WorkerSlot::Running(handle)), + Err(err) => slots.push(WorkerSlot::SpawnFailed(err)), + } + } + + let mut results = Vec::with_capacity(slots.len()); + let mut first_panic = None; + for slot in slots { + match slot { + WorkerSlot::Running(handle) => match handle.join() { + Ok(outcome) => results.push(outcome), + Err(payload) => { + if first_panic.is_none() { + first_panic = Some(payload); + } + } + }, + WorkerSlot::SpawnFailed(err) => results.push(ShardWorkerOutcome { + bytes_sent: 0, + failure: Some((IlpSendOp::SpawnWorker, err)), + }), + } + } + if let Some(payload) = first_panic { + std::panic::resume_unwind(payload); + } + results + }); + + let mut ordered: Vec<(&IlpShardFile, ShardWorkerOutcome)> = + files.iter().zip(outcomes).collect(); + ordered.sort_by(|(a, _), (b, _)| a.shard.cmp(&b.shard).then_with(|| a.path.cmp(&b.path))); + + let mut shard_reports = Vec::with_capacity(ordered.len()); + let mut total_bytes_sent: u64 = 0; + let mut first_failure: Option<(IlpSendOp, usize, PathBuf, io::Error)> = None; + + for (shard_file, outcome) in ordered { + total_bytes_sent = total_bytes_sent.saturating_add(outcome.bytes_sent); + shard_reports.push(IlpShardSendReport { + shard: shard_file.shard, + path: shard_file.path.clone(), + bytes_sent: outcome.bytes_sent, + }); + if first_failure.is_none() { + if let Some((op, source)) = outcome.failure { + first_failure = Some((op, shard_file.shard, shard_file.path.clone(), source)); + } + } + } + + let report = IlpSendReport { + total_shards: shard_reports.len(), + total_bytes_sent, + shards: shard_reports, + }; + + if let Some((op, shard, path, source)) = first_failure { + return Err(IlpSendError::ShardIo { + op, + shard, + path, + source, + partial_report: report, + }); + } + + Ok(report) +} + +struct ShardWorkerOutcome { + bytes_sent: u64, + failure: Option<(IlpSendOp, io::Error)>, +} + +fn send_single_shard( + shard_file: &IlpShardFile, + connector: &C, + buffer_bytes: usize, +) -> ShardWorkerOutcome +where + W: Write, + C: Fn(usize) -> io::Result, +{ + let mut file = match File::open(&shard_file.path) { + Ok(file) => file, + Err(err) => { + return ShardWorkerOutcome { + bytes_sent: 0, + failure: Some((IlpSendOp::OpenFile, err)), + }; + } + }; + + let mut sink = match connector(shard_file.shard) { + Ok(sink) => sink, + Err(err) => { + return ShardWorkerOutcome { + bytes_sent: 0, + failure: Some((IlpSendOp::Connect, err)), + }; + } + }; + + let mut buf = vec![0u8; buffer_bytes]; + let mut bytes_sent: u64 = 0; + + loop { + let read_len = match file.read(&mut buf) { + Ok(0) => break, + Ok(n) => n, + Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, + Err(err) => { + return ShardWorkerOutcome { + bytes_sent, + failure: Some((IlpSendOp::Read, err)), + }; + } + }; + + let mut offset = 0usize; + while offset < read_len { + match sink.write(&buf[offset..read_len]) { + Ok(0) => { + return ShardWorkerOutcome { + bytes_sent, + failure: Some(( + IlpSendOp::Write, + io::Error::new( + io::ErrorKind::WriteZero, + "sink returned Ok(0) on non-empty write", + ), + )), + }; + } + Ok(written) => { + offset += written; + bytes_sent += written as u64; + } + Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, + Err(err) => { + return ShardWorkerOutcome { + bytes_sent, + failure: Some((IlpSendOp::Write, err)), + }; + } + } + } + } + + loop { + match sink.flush() { + Ok(()) => break, + Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, + Err(err) => { + return ShardWorkerOutcome { + bytes_sent, + failure: Some((IlpSendOp::Flush, err)), + }; + } + } + } + + ShardWorkerOutcome { + bytes_sent, + failure: None, + } +} + +/// [`TcpStream`] wrapper whose [`Write::flush`] flushes the stream and performs a write-side +/// half-close (`shutdown(Shutdown::Write)`) so the peer observes clean EOF. +#[derive(Debug)] +pub struct IlpTcpSink { + stream: TcpStream, +} + +impl IlpTcpSink { + /// Wraps a connected [`TcpStream`]. + pub fn new(stream: TcpStream) -> Self { + Self { stream } + } + + /// Borrows the underlying [`TcpStream`]. + pub fn inner(&self) -> &TcpStream { + &self.stream + } + + /// Unwraps and returns the underlying [`TcpStream`]. + pub fn into_inner(self) -> TcpStream { + self.stream + } +} + +impl Write for IlpTcpSink { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.stream.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.stream.flush()?; + self.stream.shutdown(Shutdown::Write) + } +} + +/// Validates and resolves `addr` into one or more [`SocketAddr`]s without performing DNS lookups +/// on syntactically malformed inputs. +fn resolve_tcp_addr(addr: &str) -> Result, IlpSendError> { + if addr.is_empty() || addr.trim() != addr { + return Err(IlpSendError::InvalidAddress { + addr: addr.to_string(), + detail: "address must be non-empty without surrounding whitespace".to_string(), + }); + } + + if let Ok(sock_addr) = addr.parse::() { + return Ok(vec![sock_addr]); + } + + let Some((host, port_str)) = addr.rsplit_once(':') else { + return Err(IlpSendError::InvalidAddress { + addr: addr.to_string(), + detail: "expected 'host:port'".to_string(), + }); + }; + + if host.is_empty() + || host + .bytes() + .any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) + { + return Err(IlpSendError::InvalidAddress { + addr: addr.to_string(), + detail: "host component is empty or contains invalid characters".to_string(), + }); + } + + if port_str.is_empty() || port_str.parse::().is_err() { + return Err(IlpSendError::InvalidAddress { + addr: addr.to_string(), + detail: "port must be a valid u16".to_string(), + }); + } + + let resolved: Vec = addr + .to_socket_addrs() + .map_err(|err| IlpSendError::InvalidAddress { + addr: addr.to_string(), + detail: format!("failed to resolve address: {err}"), + })? + .collect(); + + if resolved.is_empty() { + return Err(IlpSendError::InvalidAddress { + addr: addr.to_string(), + detail: "address resolved to zero socket addresses".to_string(), + }); + } + + Ok(resolved) +} + +fn connect_tcp_sink( + sock_addr: &SocketAddr, + connect_timeout: Duration, + write_timeout: Duration, +) -> io::Result { + let stream = TcpStream::connect_timeout(sock_addr, connect_timeout)?; + stream.set_nodelay(true)?; + stream.set_write_timeout(Some(write_timeout))?; + Ok(IlpTcpSink::new(stream)) +} + +fn tcp_ilp_connector_for_addrs( + resolved: Vec, + options: IlpTcpOptions, +) -> Result io::Result, IlpSendError> { + if options.connect_timeout.is_zero() { + return Err(IlpSendError::InvalidTimeout { + field: "connect_timeout", + }); + } + if options.write_timeout.is_zero() { + return Err(IlpSendError::InvalidTimeout { + field: "write_timeout", + }); + } + + let connect_timeout = options.connect_timeout; + let write_timeout = options.write_timeout; + // Pin one resolved endpoint for the lifetime of this connector so shards can never silently + // split a single load across two different QuestDB instances if a hostname resolves to + // multiple addresses. + let pinned_addr: Mutex> = Mutex::new(None); + + Ok(move |_shard: usize| -> io::Result { + let already_pinned = { + let guard = pinned_addr + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + *guard + }; + + if let Some(sock_addr) = already_pinned { + return connect_tcp_sink(&sock_addr, connect_timeout, write_timeout); + } + + let mut guard = pinned_addr + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(sock_addr) = *guard { + drop(guard); + return connect_tcp_sink(&sock_addr, connect_timeout, write_timeout); + } + + let mut last_err: Option = None; + for sock_addr in &resolved { + match TcpStream::connect_timeout(sock_addr, connect_timeout) { + Ok(stream) => { + *guard = Some(*sock_addr); + drop(guard); + stream.set_nodelay(true)?; + stream.set_write_timeout(Some(write_timeout))?; + return Ok(IlpTcpSink::new(stream)); + } + Err(err) => { + last_err = Some(err); + } + } + } + Err(last_err.unwrap_or_else(|| { + io::Error::new( + io::ErrorKind::AddrNotAvailable, + "no resolved socket addresses available", + ) + })) + }) +} + +/// Builds a thread-safe TCP connector for [`send_ilp_shard_files`]. +/// +/// Validates `options` and resolves `addr` once before returning the connector closure so invalid +/// addresses fail closed before any connection attempt. Pins a single resolved [`SocketAddr`] for +/// all shards so a load can never split across multiple backend instances. Each shard invocation +/// opens a fresh [`TcpStream`] with `connect_timeout`, `set_nodelay(true)`, and `write_timeout`, +/// wrapped in [`IlpTcpSink`] so the sender's final `flush()` half-closes the write side +/// (`Shutdown::Write`). +pub fn tcp_ilp_connector( + addr: &str, + options: IlpTcpOptions, +) -> Result io::Result, IlpSendError> { + if options.connect_timeout.is_zero() { + return Err(IlpSendError::InvalidTimeout { + field: "connect_timeout", + }); + } + if options.write_timeout.is_zero() { + return Err(IlpSendError::InvalidTimeout { + field: "write_timeout", + }); + } + + let resolved = resolve_tcp_addr(addr)?; + tcp_ilp_connector_for_addrs(resolved, options) +} + +/// Formats [`IlpSendReport`] into a deterministic machine-readable `key=value` summary in the +/// style of the crate's `format_curate_*_report` helpers. +pub fn format_ilp_send_report(report: &IlpSendReport) -> String { + let per_shard = if report.shards.is_empty() { + "none".to_string() + } else { + report + .shards + .iter() + .map(|entry| format!("{:02}={}", entry.shard, entry.bytes_sent)) + .collect::>() + .join(",") + }; + + format!( + "curate-etl ilp-send\n\ + \x20 ilp_send: shards={} total_bytes_sent={} per_shard_bytes={per_shard}", + report.total_shards, report.total_bytes_sent, + ) +} + +#[cfg(test)] +#[path = "ilp_send_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/ilp_send_tests.rs b/tools/curate-etl/src/ilp_send_tests.rs new file mode 100644 index 00000000..fed8ce23 --- /dev/null +++ b/tools/curate-etl/src/ilp_send_tests.rs @@ -0,0 +1,1302 @@ +use std::collections::{BTreeMap, HashSet}; +use std::fs::{self, File}; +use std::io::{self, Read, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +use super::*; +use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD}; +use crate::ilp::{shard_for_listing_id, IlpShardedWriter, IlpWriterOptions}; +use crate::run_curate_bars_1m::tests::TempDirGuard; + +fn write_bytes(path: &Path, bytes: &[u8]) { + fs::write(path, bytes).expect("write test shard file"); +} + +#[test] +fn discovers_exact_prefix_in_numeric_order() { + let dir = TempDirGuard::new("ilp-send-discover"); + write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), b"shard1"); + write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), b"shard0"); + write_bytes(&dir.path().join("bars_1m_qm.shard-00.ilp"), b"qm0"); + write_bytes(&dir.path().join("fx_1m.shard-00.ilp"), b"fx0"); + write_bytes(&dir.path().join("unrelated.txt"), b"ignore"); + write_bytes(&dir.path().join(".bars_1m.shard-00.123.tmp"), b"staging"); + + let bars = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover bars_1m"); + assert_eq!( + bars, + vec![ + IlpShardFile { + shard: 0, + path: dir.path().join("bars_1m.shard-00.ilp"), + }, + IlpShardFile { + shard: 1, + path: dir.path().join("bars_1m.shard-01.ilp"), + }, + ] + ); + + let qm = discover_ilp_shard_files(dir.path(), "bars_1m_qm").expect("discover bars_1m_qm"); + assert_eq!(qm.len(), 1); + assert_eq!(qm[0].shard, 0); + assert_eq!(qm[0].path, dir.path().join("bars_1m_qm.shard-00.ilp")); + + let fx = discover_ilp_shard_files(dir.path(), "fx_1m").expect("discover fx_1m"); + assert_eq!(fx.len(), 1); + assert_eq!(fx[0].shard, 0); + assert_eq!(fx[0].path, dir.path().join("fx_1m.shard-00.ilp")); + + // Verify numeric ordering (not lexicographic) across 0..=10. + let multi = TempDirGuard::new("ilp-send-discover-numeric"); + for idx in [10usize, 2, 0, 9, 1, 8, 3, 7, 4, 6, 5] { + write_bytes(&multi.path().join(format!("bars_1m.shard-{idx}.ilp")), b"x"); + } + let ordered = discover_ilp_shard_files(multi.path(), "bars_1m").expect("numeric order"); + let indices: Vec = ordered.iter().map(|f| f.shard).collect(); + assert_eq!(indices, (0..=10).collect::>()); +} + +#[test] +fn rejects_invalid_shard_sets() { + // 1. Blank and invalid prefixes. + let empty_dir = TempDirGuard::new("ilp-send-empty"); + for bad in ["", " ", "bars.1m", "bars/1m", "bars 1m"] { + let err = discover_ilp_shard_files(empty_dir.path(), bad).unwrap_err(); + assert!( + matches!(err, IlpSendError::InvalidPrefix { .. }), + "expected InvalidPrefix for {bad:?}, got {err:?}" + ); + } + + // 2. Non-directory path. + let file_path = empty_dir.path().join("not_a_dir"); + write_bytes(&file_path, b"x"); + let err = discover_ilp_shard_files(&file_path, "bars_1m").unwrap_err(); + assert!( + matches!(err, IlpSendError::InvalidDirectory { .. }), + "expected InvalidDirectory, got {err:?}" + ); + + // 3. No matching files. + let err = discover_ilp_shard_files(empty_dir.path(), "bars_1m").unwrap_err(); + assert!( + matches!(err, IlpSendError::NoShardFiles { .. }), + "expected NoShardFiles, got {err:?}" + ); + + // 4. Gap in indices (00, 02). + let gap_dir = TempDirGuard::new("ilp-send-gap"); + write_bytes(&gap_dir.path().join("bars_1m.shard-00.ilp"), b"a"); + write_bytes(&gap_dir.path().join("bars_1m.shard-02.ilp"), b"c"); + let err = discover_ilp_shard_files(gap_dir.path(), "bars_1m").unwrap_err(); + assert!( + matches!( + err, + IlpSendError::MissingShardIndex { + expected: 1, + found: 2, + .. + } + ), + "expected MissingShardIndex(1, 2), got {err:?}" + ); + + // 5. Missing shard 0 (01, 02). + let no_zero_dir = TempDirGuard::new("ilp-send-no-zero"); + write_bytes(&no_zero_dir.path().join("bars_1m.shard-01.ilp"), b"b"); + write_bytes(&no_zero_dir.path().join("bars_1m.shard-02.ilp"), b"c"); + let err = discover_ilp_shard_files(no_zero_dir.path(), "bars_1m").unwrap_err(); + assert!( + matches!( + err, + IlpSendError::MissingShardIndex { + expected: 0, + found: 1, + .. + } + ), + "expected MissingShardIndex(0, 1), got {err:?}" + ); + + // 6. Duplicate numeric index (shard-0 and shard-00). + let dup_dir = TempDirGuard::new("ilp-send-dup"); + write_bytes(&dup_dir.path().join("bars_1m.shard-0.ilp"), b"a"); + write_bytes(&dup_dir.path().join("bars_1m.shard-00.ilp"), b"b"); + let err = discover_ilp_shard_files(dup_dir.path(), "bars_1m").unwrap_err(); + assert!( + matches!(err, IlpSendError::DuplicateShardIndex { shard: 0, .. }), + "expected DuplicateShardIndex(0), got {err:?}" + ); + + // 7. Numeric suffix overflow. + let overflow_dir = TempDirGuard::new("ilp-send-overflow"); + write_bytes( + &overflow_dir + .path() + .join("bars_1m.shard-999999999999999999999999999999999999999.ilp"), + b"x", + ); + let err = discover_ilp_shard_files(overflow_dir.path(), "bars_1m").unwrap_err(); + assert!( + matches!(err, IlpSendError::ShardIndexOverflow { .. }), + "expected ShardIndexOverflow, got {err:?}" + ); + + // 8. Directory named like a shard file. + let dir_shard = TempDirGuard::new("ilp-send-dir-shard"); + fs::create_dir(dir_shard.path().join("bars_1m.shard-00.ilp")).expect("create shard dir"); + let err = discover_ilp_shard_files(dir_shard.path(), "bars_1m").unwrap_err(); + assert!( + matches!(err, IlpSendError::NotRegularFile { .. }), + "expected NotRegularFile for directory, got {err:?}" + ); + + // 9. Symlink named like a shard file. + #[cfg(unix)] + { + let sym_dir = TempDirGuard::new("ilp-send-sym-shard"); + let target = sym_dir.path().join("real.ilp"); + write_bytes(&target, b"payload"); + std::os::unix::fs::symlink(&target, sym_dir.path().join("bars_1m.shard-00.ilp")) + .expect("create symlink"); + let err = discover_ilp_shard_files(sym_dir.path(), "bars_1m").unwrap_err(); + assert!( + matches!(err, IlpSendError::NotRegularFile { .. }), + "expected NotRegularFile for symlink, got {err:?}" + ); + } +} + +struct RecordingSinkState { + bytes: Vec, + flushes: usize, +} + +struct RecordingSink { + state: Arc>, +} + +impl Write for RecordingSink { + fn write(&mut self, buf: &[u8]) -> io::Result { + let mut guard = self.state.lock().expect("lock recording sink"); + guard.bytes.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + let mut guard = self.state.lock().expect("lock recording sink"); + guard.flushes += 1; + Ok(()) + } +} + +#[test] +fn streams_writer_bytes_and_flushes_every_shard() { + let dir = TempDirGuard::new("ilp-send-fidelity"); + let shard_count = 3usize; + + // Pick two listing_ids that hash to shards 0 and 2 so shard 1 stays zero-length. + let id_shard_0 = (1..10_000i32) + .find(|&id| shard_for_listing_id(id, shard_count) == 0) + .expect("find listing_id for shard 0"); + let id_shard_2 = (1..10_000i32) + .find(|&id| shard_for_listing_id(id, shard_count) == 2) + .expect("find listing_id for shard 2"); + + // Construct a finite positive f64 whose IEEE-754 LE bytes include 0x0A ('\n'). + let close_with_lf = f64::from_le_bytes([0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59, 0x40]); + assert!(close_with_lf.is_finite() && close_with_lf > 0.0); + assert!(close_with_lf.to_le_bytes().contains(&0x0A)); + + let shard_paths: Vec = (0..shard_count) + .map(|idx| dir.path().join(format!("bars_1m.shard-{idx:02}.ilp"))) + .collect(); + let sinks: Vec = shard_paths + .iter() + .map(|p| File::create(p).expect("create shard file")) + .collect(); + + let mut writer = + IlpShardedWriter::new(sinks, IlpWriterOptions::default()).expect("create ILP writer"); + let rows = [ + ( + Bar1mRow { + key: id_shard_0, + ts: 1_700_000_000_000_000, + session_date: 19_675, + open: 100.0, + high: 101.5, + low: 99.5, + close: close_with_lf, + volume: 12_345.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_EOD, + }, + 1_700_000_060_000_000i64, + ), + ( + Bar1mRow { + key: id_shard_0, + ts: 1_700_000_060_000_000, + session_date: 19_675, + open: close_with_lf, + high: 102.0, + low: 99.0, + close: 101.25, + volume: 6_789.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_EOD, + }, + 1_700_000_120_000_000i64, + ), + ( + Bar1mRow { + key: id_shard_2, + ts: 1_700_000_000_000_000, + session_date: 19_675, + open: 42.0, + high: 43.0, + low: 41.0, + close: close_with_lf, + volume: 999.0, + session: IntradaySession::Pre, + source: BARS_1M_SOURCE_EOD, + }, + 1_700_000_060_000_000i64, + ), + ]; + for (row, known_at) in &rows { + writer.write_bar_1m(row, *known_at).expect("write bar_1m"); + } + writer.finish().expect("finish ILP writer"); + + let expected_bytes: Vec> = shard_paths + .iter() + .map(|p| fs::read(p).expect("read written shard")) + .collect(); + assert!(!expected_bytes[0].is_empty()); + assert!(expected_bytes[1].is_empty(), "shard 1 must be zero-length"); + assert!(!expected_bytes[2].is_empty()); + assert!(expected_bytes[0].windows(8).any(|w| w == close_with_lf.to_le_bytes())); + + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover shards"); + assert_eq!(files.len(), shard_count); + + // Bounded rendezvous to verify all 3 shard workers run concurrently. + let rendezvous = Arc::new((Mutex::new(0usize), Condvar::new())); + let connect_counts = Arc::new(Mutex::new(BTreeMap::::new())); + let recorded: Arc>>> = Arc::new( + (0..shard_count) + .map(|_| { + Arc::new(Mutex::new(RecordingSinkState { + bytes: Vec::new(), + flushes: 0, + })) + }) + .collect(), + ); + + let report = send_ilp_shard_files( + &files, + |shard| { + { + let mut counts = connect_counts.lock().expect("lock connect_counts"); + *counts.entry(shard).or_insert(0) += 1; + } + { + let (lock, cvar) = &*rendezvous; + let mut arrived = lock.lock().expect("lock rendezvous"); + *arrived += 1; + if *arrived == shard_count { + cvar.notify_all(); + } else { + let (guard, timeout) = cvar + .wait_timeout_while(arrived, Duration::from_secs(2), |n| *n < shard_count) + .expect("wait rendezvous"); + assert!( + !timeout.timed_out() && *guard == shard_count, + "expected all {shard_count} shard workers to overlap concurrently" + ); + } + } + Ok(RecordingSink { + state: Arc::clone(&recorded[shard]), + }) + }, + IlpSendOptions { buffer_bytes: 7 }, + ) + .expect("send shards"); + + // Verify connector called once per shard. + let counts = connect_counts.lock().expect("lock connect_counts"); + assert_eq!(counts.len(), shard_count); + for shard in 0..shard_count { + assert_eq!(counts.get(&shard), Some(&1)); + } + + // Verify exact byte fidelity, single flush per shard (including empty shard 1), and report. + assert_eq!(report.total_shards, shard_count); + let expected_total: u64 = expected_bytes.iter().map(|b| b.len() as u64).sum(); + assert_eq!(report.total_bytes_sent, expected_total); + + for shard in 0..shard_count { + let state = recorded[shard].lock().expect("lock recorded"); + assert_eq!(state.bytes, expected_bytes[shard], "byte mismatch on shard {shard}"); + assert_eq!(state.flushes, 1, "expected exactly one flush on shard {shard}"); + assert_eq!(report.shards[shard].shard, shard); + assert_eq!(report.shards[shard].path, files[shard].path); + assert_eq!(report.shards[shard].bytes_sent, expected_bytes[shard].len() as u64); + } + + let formatted = format_ilp_send_report(&report); + assert_eq!( + formatted, + format!( + "curate-etl ilp-send\n ilp_send: shards=3 total_bytes_sent={expected_total} per_shard_bytes=00={},01=0,02={}", + expected_bytes[0].len(), + expected_bytes[2].len() + ) + ); +} + +#[test] +fn reports_connect_failure() { + let dir = TempDirGuard::new("ilp-send-connect-fail"); + let p0 = dir.path().join("bars_1m.shard-00.ilp"); + let p1 = dir.path().join("bars_1m.shard-01.ilp"); + let p2 = dir.path().join("bars_1m.shard-02.ilp"); + write_bytes(&p0, b"0123456789"); + write_bytes(&p1, b"will-not-connect"); + write_bytes(&p2, b"abcdef"); + + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); + let err = send_ilp_shard_files( + &files, + |shard| { + if shard == 1 { + Err(io::Error::new( + io::ErrorKind::ConnectionRefused, + "refused shard 1", + )) + } else { + Ok(Vec::::new()) + } + }, + IlpSendOptions { buffer_bytes: 4 }, + ) + .unwrap_err(); + + match err { + IlpSendError::ShardIo { + op, + shard, + path, + source, + partial_report, + } => { + assert_eq!(op, IlpSendOp::Connect); + assert_eq!(shard, 1); + assert_eq!(path, p1); + assert_eq!(source.kind(), io::ErrorKind::ConnectionRefused); + assert_eq!(partial_report.total_shards, 3); + assert_eq!(partial_report.shards[0].bytes_sent, 10); + assert_eq!(partial_report.shards[1].bytes_sent, 0); + assert_eq!(partial_report.shards[2].bytes_sent, 6); + assert_eq!(partial_report.total_bytes_sent, 16); + } + other => panic!("expected ShardIo(Connect), got {other:?}"), + } +} + +struct PartialFailWriter { + step: usize, + written: Vec, +} + +impl Write for PartialFailWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.step += 1; + match self.step { + 1 => { + let take = buf.len().min(5); + self.written.extend_from_slice(&buf[..take]); + Ok(take) + } + 2 => Err(io::Error::new( + io::ErrorKind::Interrupted, + "transient interrupt", + )), + 3 => { + let take = buf.len().min(4); + self.written.extend_from_slice(&buf[..take]); + Ok(take) + } + _ => Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "peer closed mid-write", + )), + } + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +struct WriteZeroSink; + +impl Write for WriteZeroSink { + fn write(&mut self, _buf: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn reports_partial_write_failure() { + let dir = TempDirGuard::new("ilp-send-write-fail"); + let p0 = dir.path().join("bars_1m.shard-00.ilp"); + let p1 = dir.path().join("bars_1m.shard-01.ilp"); + let p2 = dir.path().join("bars_1m.shard-02.ilp"); + write_bytes(&p0, b"shard0-payload"); + write_bytes(&p1, &[b'B'; 32]); + write_bytes(&p2, b"shard2"); + + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); + let err = send_ilp_shard_files( + &files, + |shard| -> io::Result> { + if shard == 1 { + Ok(Box::new(PartialFailWriter { + step: 0, + written: Vec::new(), + })) + } else { + Ok(Box::new(Vec::::new())) + } + }, + IlpSendOptions { buffer_bytes: 16 }, + ) + .unwrap_err(); + + match err { + IlpSendError::ShardIo { + op, + shard, + path, + source, + partial_report, + } => { + assert_eq!(op, IlpSendOp::Write); + assert_eq!(shard, 1); + assert_eq!(path, p1); + assert_eq!(source.kind(), io::ErrorKind::BrokenPipe); + assert_eq!(partial_report.shards[0].bytes_sent, 14); + assert_eq!(partial_report.shards[1].bytes_sent, 9); + assert_eq!(partial_report.shards[2].bytes_sent, 6); + assert_eq!(partial_report.total_bytes_sent, 29); + } + other => panic!("expected ShardIo(Write), got {other:?}"), + } + + // Also verify Ok(0) on a non-empty slice surfaces as WriteZero. + let err_zero = send_ilp_shard_files( + &files[..1], + |_shard| Ok(WriteZeroSink), + IlpSendOptions { buffer_bytes: 8 }, + ) + .unwrap_err(); + match err_zero { + IlpSendError::ShardIo { + op, + shard, + source, + partial_report, + .. + } => { + assert_eq!(op, IlpSendOp::Write); + assert_eq!(shard, 0); + assert_eq!(source.kind(), io::ErrorKind::WriteZero); + assert_eq!(partial_report.shards[0].bytes_sent, 0); + } + other => panic!("expected ShardIo(WriteZero), got {other:?}"), + } +} + +struct FlushFailWriter { + written: Vec, +} + +impl Write for FlushFailWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.written.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Err(io::Error::new(io::ErrorKind::TimedOut, "flush timed out")) + } +} + +#[test] +fn reports_flush_failure() { + let dir = TempDirGuard::new("ilp-send-flush-fail"); + let p0 = dir.path().join("bars_1m.shard-00.ilp"); + let p1 = dir.path().join("bars_1m.shard-01.ilp"); + let p2 = dir.path().join("bars_1m.shard-02.ilp"); + write_bytes(&p0, b"12345"); + write_bytes(&p1, b"678"); + write_bytes(&p2, b"abcdefghij"); + + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); + let err = send_ilp_shard_files( + &files, + |shard| -> io::Result> { + if shard == 2 { + Ok(Box::new(FlushFailWriter { + written: Vec::new(), + })) + } else { + Ok(Box::new(Vec::::new())) + } + }, + IlpSendOptions { buffer_bytes: 4 }, + ) + .unwrap_err(); + + match err { + IlpSendError::ShardIo { + op, + shard, + path, + source, + partial_report, + } => { + assert_eq!(op, IlpSendOp::Flush); + assert_eq!(shard, 2); + assert_eq!(path, p2); + assert_eq!(source.kind(), io::ErrorKind::TimedOut); + assert_eq!(partial_report.shards[0].bytes_sent, 5); + assert_eq!(partial_report.shards[1].bytes_sent, 3); + assert_eq!(partial_report.shards[2].bytes_sent, 10); + assert_eq!(partial_report.total_bytes_sent, 18); + } + other => panic!("expected ShardIo(Flush), got {other:?}"), + } +} + +#[test] +fn reports_removed_shard() { + let dir = TempDirGuard::new("ilp-send-removed"); + let p0 = dir.path().join("bars_1m.shard-00.ilp"); + let p1 = dir.path().join("bars_1m.shard-01.ilp"); + let p2 = dir.path().join("bars_1m.shard-02.ilp"); + write_bytes(&p0, b"hello"); + write_bytes(&p1, b"disappearing"); + write_bytes(&p2, b"world!"); + + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); + fs::remove_file(&p1).expect("remove shard 1 after discovery"); + + let connected_shards = Arc::new(Mutex::new(HashSet::::new())); + let err = send_ilp_shard_files( + &files, + |shard| { + connected_shards.lock().expect("lock").insert(shard); + Ok(Vec::::new()) + }, + IlpSendOptions { buffer_bytes: 4 }, + ) + .unwrap_err(); + + match err { + IlpSendError::ShardIo { + op, + shard, + path, + source, + partial_report, + } => { + assert_eq!(op, IlpSendOp::OpenFile); + assert_eq!(shard, 1); + assert_eq!(path, p1); + assert_eq!(source.kind(), io::ErrorKind::NotFound); + assert_eq!(partial_report.shards[0].bytes_sent, 5); + assert_eq!(partial_report.shards[1].bytes_sent, 0); + assert_eq!(partial_report.shards[2].bytes_sent, 6); + assert_eq!(partial_report.total_bytes_sent, 11); + } + other => panic!("expected ShardIo(OpenFile), got {other:?}"), + } + + let connected = connected_shards.lock().expect("lock"); + assert!( + !connected.contains(&1), + "connector must not be called when opening shard file fails" + ); +} + +#[test] +fn rejects_zero_buffer_before_connect() { + let dir = TempDirGuard::new("ilp-send-zero-buf"); + write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), b"abc"); + write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), b"def"); + + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); + let calls = AtomicUsize::new(0); + let err = send_ilp_shard_files( + &files, + |_shard| { + calls.fetch_add(1, Ordering::SeqCst); + Ok(Vec::::new()) + }, + IlpSendOptions { buffer_bytes: 0 }, + ) + .unwrap_err(); + + assert!(matches!(err, IlpSendError::ZeroBufferBytes)); + assert_eq!(calls.load(Ordering::SeqCst), 0); +} + +fn accept_with_deadline( + listener: &TcpListener, + deadline: Instant, + accepted_so_far: usize, + expected_total: usize, +) -> (TcpStream, SocketAddr) { + loop { + match listener.accept() { + Ok((stream, peer)) => { + stream + .set_nonblocking(false) + .expect("set accepted stream blocking"); + return (stream, peer); + } + Err(err) if err.kind() == io::ErrorKind::WouldBlock => { + if Instant::now() >= deadline { + panic!( + "timed out waiting for shard TCP connection: received {accepted_so_far} of {expected_total} connections" + ); + } + thread::sleep(Duration::from_millis(5)); + } + Err(err) => panic!( + "accept failed after receiving {accepted_so_far} of {expected_total} connections: {err}" + ), + } + } +} + +#[test] +fn tcp_sends_separate_shards_and_half_closes() { + let dir = TempDirGuard::new("ilp-send-tcp"); + let payload0: Vec = b"bars_1m,listing_id=1 open==\x10\x0A\x00\x00\x00\x00\x00\x59\x40 1700000000000000t\n".to_vec(); + let payload1: Vec = Vec::new(); + let payload2: Vec = b"bars_1m,listing_id=2 open==\x10\x01\x02\x03\x04\x05\x06\x07\x40 1700000060000000t\n".to_vec(); + + write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), &payload0); + write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), &payload1); + write_bytes(&dir.path().join("bars_1m.shard-02.ilp"), &payload2); + + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); + let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); + let listen_addr = listener.local_addr().expect("local addr"); + listener + .set_nonblocking(true) + .expect("set loopback listener nonblocking"); + + let server_handle = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(3); + let mut reader_handles = Vec::with_capacity(3); + for accepted in 0..3 { + let (mut stream, peer) = accept_with_deadline(&listener, deadline, accepted, 3); + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("set server read timeout"); + reader_handles.push(thread::spawn(move || { + let mut buf = Vec::new(); + stream + .read_to_end(&mut buf) + .expect("read shard stream to EOF via half-close"); + (peer, buf) + })); + } + reader_handles + .into_iter() + .map(|h| h.join().expect("join reader thread")) + .collect::)>>() + }); + + let base_connector = tcp_ilp_connector( + &listen_addr.to_string(), + IlpTcpOptions { + connect_timeout: Duration::from_secs(2), + write_timeout: Duration::from_secs(2), + }, + ) + .expect("create tcp connector"); + + // Keep a cloned handle of every client socket open until AFTER the server observes EOF. + // Because drop/close only sends FIN when the last fd closes, this proves IlpTcpSink::flush() + // explicitly invoked shutdown(Shutdown::Write). + let kept_handles = Mutex::new(Vec::::new()); + let report = send_ilp_shard_files( + &files, + |shard| { + let sink = base_connector(shard)?; + assert!(sink.inner().nodelay().expect("query nodelay")); + kept_handles + .lock() + .expect("lock kept_handles") + .push(sink.inner().try_clone().expect("clone client TcpStream")); + Ok(sink) + }, + IlpSendOptions { buffer_bytes: 13 }, + ) + .expect("send over loopback tcp"); + + // Wait for all 3 server readers to reach EOF while client socket clones are still alive. + let received = server_handle.join().expect("join server thread"); + assert_eq!(kept_handles.lock().expect("lock kept_handles").len(), 3); + drop(kept_handles); + + assert_eq!(received.len(), 3); + let distinct_peers: HashSet = received.iter().map(|(peer, _)| *peer).collect(); + assert_eq!( + distinct_peers.len(), + 3, + "expected 3 separate accepted TCP connections" + ); + + let mut received_payloads: Vec> = received.into_iter().map(|(_, buf)| buf).collect(); + received_payloads.sort(); + let mut expected_payloads = vec![payload0.clone(), payload1.clone(), payload2.clone()]; + expected_payloads.sort(); + assert_eq!(received_payloads, expected_payloads); + + assert_eq!(report.total_shards, 3); + assert_eq!(report.shards[0].bytes_sent, payload0.len() as u64); + assert_eq!(report.shards[1].bytes_sent, 0); + assert_eq!(report.shards[2].bytes_sent, payload2.len() as u64); + assert_eq!( + report.total_bytes_sent, + (payload0.len() + payload1.len() + payload2.len()) as u64 + ); +} + +#[test] +fn tcp_rejects_invalid_address_before_connect() { + for bad in [ + "", + " ", + "127.0.0.1", + "127.0.0.1:", + "127.0.0.1:notaport", + "127.0.0.1:99999", + ":9009", + "bad host:9009", + " 127.0.0.1:9009", + "127.0.0.1:9009 ", + ] { + let err = match tcp_ilp_connector(bad, IlpTcpOptions::default()) { + Ok(_) => panic!("expected InvalidAddress for {bad:?}"), + Err(err) => err, + }; + assert!( + matches!(err, IlpSendError::InvalidAddress { .. }), + "expected InvalidAddress for {bad:?}, got {err:?}" + ); + } + + let zero_connect = match tcp_ilp_connector( + "127.0.0.1:9009", + IlpTcpOptions { + connect_timeout: Duration::ZERO, + write_timeout: Duration::from_secs(1), + }, + ) { + Ok(_) => panic!("expected InvalidTimeout for zero connect_timeout"), + Err(err) => err, + }; + assert!(matches!( + zero_connect, + IlpSendError::InvalidTimeout { + field: "connect_timeout" + } + )); + + let zero_write = match tcp_ilp_connector( + "127.0.0.1:9009", + IlpTcpOptions { + connect_timeout: Duration::from_secs(1), + write_timeout: Duration::ZERO, + }, + ) { + Ok(_) => panic!("expected InvalidTimeout for zero write_timeout"), + Err(err) => err, + }; + assert!(matches!( + zero_write, + IlpSendError::InvalidTimeout { + field: "write_timeout" + } + )); +} + +#[test] +fn tcp_pins_single_endpoint_and_does_not_fail_over_mid_send() { + let dir = TempDirGuard::new("ilp-send-tcp-pin"); + let p0 = dir.path().join("bars_1m.shard-00.ilp"); + let p1 = dir.path().join("bars_1m.shard-01.ilp"); + let payload0 = b"bars_1m,listing_id=1 open=1.0 1700000000000000t\n"; + let payload1 = b"bars_1m,listing_id=2 open=2.0 1700000060000000t\n"; + write_bytes(&p0, payload0); + write_bytes(&p1, payload1); + + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); + + let listener_a = TcpListener::bind("127.0.0.1:0").expect("bind endpoint A"); + let addr_a = listener_a.local_addr().expect("addr A"); + listener_a + .set_nonblocking(true) + .expect("set listener A nonblocking"); + + let listener_b = TcpListener::bind("127.0.0.1:0").expect("bind endpoint B"); + let addr_b = listener_b.local_addr().expect("addr B"); + listener_b + .set_nonblocking(true) + .expect("set listener B nonblocking"); + + let a_closed = Arc::new((Mutex::new(false), Condvar::new())); + let a_closed_server = Arc::clone(&a_closed); + + // Server A accepts shard 0, closes its listener (simulating restart/refusal for shard 1), + // signals shard 1 to attempt connect, and finishes reading shard 0 to EOF. + let server_a = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(3); + let (mut stream, _) = accept_with_deadline(&listener_a, deadline, 0, 1); + drop(listener_a); + { + let (lock, cvar) = &*a_closed_server; + let mut closed = lock.lock().expect("lock a_closed"); + *closed = true; + cvar.notify_all(); + } + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("set read timeout"); + let mut buf = Vec::new(); + stream.read_to_end(&mut buf).expect("read shard 0 to EOF"); + buf + }); + + let base_connector = tcp_ilp_connector_for_addrs( + vec![addr_a, addr_b], + IlpTcpOptions { + connect_timeout: Duration::from_secs(2), + write_timeout: Duration::from_secs(2), + }, + ) + .expect("create multi-addr tcp connector"); + + let err = send_ilp_shard_files( + &files, + |shard| { + if shard == 1 { + let (lock, cvar) = &*a_closed; + let closed = lock.lock().expect("lock a_closed"); + let (guard, timeout) = cvar + .wait_timeout_while(closed, Duration::from_secs(3), |c| !*c) + .expect("wait for listener A to close"); + assert!( + !timeout.timed_out() && *guard, + "timed out waiting for endpoint A listener to close" + ); + } + base_connector(shard) + }, + IlpSendOptions { buffer_bytes: 16 }, + ) + .unwrap_err(); + + let received_a = server_a.join().expect("join server A"); + assert_eq!(received_a, payload0); + + // Endpoint B must never have received a connection attempt. + match listener_b.accept() { + Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} + Ok((_, peer)) => panic!("shard 1 unexpectedly failed over to endpoint B from {peer}"), + Err(err) => panic!("unexpected error checking endpoint B: {err}"), + } + + match err { + IlpSendError::ShardIo { + op, + shard, + path, + partial_report, + .. + } => { + assert_eq!(op, IlpSendOp::Connect); + assert_eq!(shard, 1); + assert_eq!(path, p1); + assert_eq!(partial_report.total_shards, 2); + assert_eq!(partial_report.shards[0].shard, 0); + assert_eq!(partial_report.shards[0].bytes_sent, payload0.len() as u64); + assert_eq!(partial_report.shards[1].shard, 1); + assert_eq!(partial_report.shards[1].bytes_sent, 0); + assert_eq!(partial_report.total_bytes_sent, payload0.len() as u64); + } + other => panic!("expected ShardIo(Connect) on shard 1, got {other:?}"), + } +} + +#[test] +fn orders_report_and_lowest_failure_for_unsorted_input() { + let dir = TempDirGuard::new("ilp-send-unsorted"); + let p0 = dir.path().join("bars_1m.shard-00.ilp"); + let p1 = dir.path().join("bars_1m.shard-01.ilp"); + let p2 = dir.path().join("bars_1m.shard-02.ilp"); + write_bytes(&p0, b"aaaa"); + write_bytes(&p1, b"bb"); + write_bytes(&p2, b"cccccc"); + + let unsorted = vec![ + IlpShardFile { + shard: 2, + path: p2.clone(), + }, + IlpShardFile { + shard: 0, + path: p0.clone(), + }, + IlpShardFile { + shard: 1, + path: p1.clone(), + }, + ]; + + let ok_report = send_ilp_shard_files( + &unsorted, + |_shard| Ok(Vec::::new()), + IlpSendOptions { buffer_bytes: 4 }, + ) + .expect("send unsorted slice"); + assert_eq!( + ok_report + .shards + .iter() + .map(|s| (s.shard, s.bytes_sent)) + .collect::>(), + vec![(0, 4), (1, 2), (2, 6)] + ); + + let err = send_ilp_shard_files( + &unsorted, + |shard| { + if shard == 1 || shard == 2 { + Err(io::Error::new( + io::ErrorKind::ConnectionRefused, + format!("refused shard {shard}"), + )) + } else { + Ok(Vec::::new()) + } + }, + IlpSendOptions { buffer_bytes: 4 }, + ) + .unwrap_err(); + + match err { + IlpSendError::ShardIo { + op, + shard, + path, + partial_report, + .. + } => { + assert_eq!(op, IlpSendOp::Connect); + assert_eq!(shard, 1, "must report lowest-index failing shard"); + assert_eq!(path, p1); + assert_eq!( + partial_report + .shards + .iter() + .map(|s| (s.shard, s.bytes_sent)) + .collect::>(), + vec![(0, 4), (1, 0), (2, 0)] + ); + assert_eq!(partial_report.total_bytes_sent, 4); + } + other => panic!("expected ShardIo(Connect) on shard 1, got {other:?}"), + } +} + +// --------------------------------------------------------------------------- +// QA (T-188) edge-case coverage. +// --------------------------------------------------------------------------- + +fn refused_loopback_addr() -> SocketAddr { + // Bind an ephemeral loopback port and immediately release it so connects are refused. + let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral loopback port"); + let addr = listener.local_addr().expect("ephemeral local addr"); + drop(listener); + addr +} + +#[test] +fn discovery_ignores_near_miss_shard_names_and_accepts_hyphen_prefix() { + let dir = TempDirGuard::new("ilp-send-near-miss"); + write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), b"real"); + for near_miss in [ + "bars_1m.shard-.ilp", + "bars_1m.shard-0a.ilp", + "bars_1m.shard-+1.ilp", + "bars_1m.shard--1.ilp", + "bars_1m.shard-01.ilp.tmp", + "bars_1m.shard-01.ILP", + "BARS_1M.shard-01.ilp", + "xbars_1m.shard-01.ilp", + "bars_1m.shard01.ilp", + "bars_1m_qm.shard-01.ilp", + ] { + write_bytes(&dir.path().join(near_miss), b"ignored"); + } + + let found = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover bars_1m"); + assert_eq!( + found, + vec![IlpShardFile { + shard: 0, + path: dir.path().join("bars_1m.shard-00.ilp"), + }] + ); + + let hyphen = TempDirGuard::new("ilp-send-hyphen-prefix"); + write_bytes(&hyphen.path().join("fx-1m.shard-00.ilp"), b"fx"); + let found = discover_ilp_shard_files(hyphen.path(), "fx-1m").expect("hyphen prefix"); + assert_eq!(found.len(), 1); + assert_eq!(found[0].shard, 0); + + let missing = dir.path().join("does-not-exist"); + match discover_ilp_shard_files(&missing, "bars_1m").unwrap_err() { + IlpSendError::ReadDir { path, source } => { + assert_eq!(path, missing); + assert_eq!(source.kind(), io::ErrorKind::NotFound); + } + other => panic!("expected ReadDir(NotFound), got {other:?}"), + } +} + +#[test] +fn streams_multi_chunk_file_with_one_byte_buffer_and_handles_empty_slice() { + let dir = TempDirGuard::new("ilp-send-one-byte"); + // Deterministic pseudo-random payload covering every byte value, including 0x0A. + let mut state: u32 = 0x1234_5678; + let payload: Vec = (0..4099) + .map(|_| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 24) as u8 + }) + .chain(0u8..=255) + .collect(); + let path = dir.path().join("fx_1m.shard-00.ilp"); + write_bytes(&path, &payload); + + let files = discover_ilp_shard_files(dir.path(), "fx_1m").expect("discover"); + let state_cell = Arc::new(Mutex::new(RecordingSinkState { + bytes: Vec::new(), + flushes: 0, + })); + let report = send_ilp_shard_files( + &files, + |_shard| { + Ok(RecordingSink { + state: Arc::clone(&state_cell), + }) + }, + IlpSendOptions { buffer_bytes: 1 }, + ) + .expect("send one-byte buffer"); + let recorded = state_cell.lock().expect("lock recorded"); + assert_eq!(recorded.bytes, payload); + assert_eq!(recorded.flushes, 1); + assert_eq!(report.total_bytes_sent, payload.len() as u64); + + let calls = AtomicUsize::new(0); + let empty = send_ilp_shard_files( + &[], + |_shard| { + calls.fetch_add(1, Ordering::SeqCst); + Ok(Vec::::new()) + }, + IlpSendOptions::default(), + ) + .expect("empty slice is a no-op"); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert_eq!(empty.total_shards, 0); + assert_eq!(empty.total_bytes_sent, 0); + assert_eq!( + format_ilp_send_report(&empty), + "curate-etl ilp-send\n ilp_send: shards=0 total_bytes_sent=0 per_shard_bytes=none" + ); + assert_eq!(IlpSendOptions::default().buffer_bytes, 64 * 1024); +} + +#[test] +fn shard_io_error_display_and_source_name_shard_path_and_op() { + let dir = TempDirGuard::new("ilp-send-display"); + let p0 = dir.path().join("bars_1m.shard-00.ilp"); + let p1 = dir.path().join("bars_1m.shard-01.ilp"); + write_bytes(&p0, b"abc"); + write_bytes(&p1, b"defg"); + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); + + let err = send_ilp_shard_files( + &files, + |shard| { + if shard == 1 { + Err(io::Error::new(io::ErrorKind::ConnectionRefused, "refused")) + } else { + Ok(Vec::::new()) + } + }, + IlpSendOptions { buffer_bytes: 2 }, + ) + .unwrap_err(); + + let text = err.to_string(); + assert!(text.contains("ILP shard 1"), "{text}"); + assert!(text.contains(&p1.display().to_string()), "{text}"); + assert!(text.contains("during connect"), "{text}"); + assert!(text.contains("total_bytes_sent=3"), "{text}"); + + let source = std::error::Error::source(&err).expect("ShardIo exposes io::Error source"); + let io_source = source + .downcast_ref::() + .expect("source is io::Error"); + assert_eq!(io_source.kind(), io::ErrorKind::ConnectionRefused); + + let partial = err.partial_report().expect("ShardIo carries partial report"); + assert_eq!( + format_ilp_send_report(partial), + "curate-etl ilp-send\n ilp_send: shards=2 total_bytes_sent=3 per_shard_bytes=00=3,01=0" + ); + assert!(IlpSendError::ZeroBufferBytes.partial_report().is_none()); +} + +#[test] +fn tcp_reports_refused_connection_as_connect_failure() { + let dir = TempDirGuard::new("ilp-send-tcp-refused"); + let p0 = dir.path().join("bars_1m.shard-00.ilp"); + write_bytes(&p0, b"bars_1m,listing_id=1 open=1.0 1700000000000000t\n"); + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); + + let dead = refused_loopback_addr(); + let connector = tcp_ilp_connector( + &dead.to_string(), + IlpTcpOptions { + connect_timeout: Duration::from_secs(2), + write_timeout: Duration::from_secs(2), + }, + ) + .expect("connector creation must not connect"); + + match send_ilp_shard_files(&files, connector, IlpSendOptions::default()).unwrap_err() { + IlpSendError::ShardIo { + op, + shard, + path, + source, + partial_report, + } => { + assert_eq!(op, IlpSendOp::Connect); + assert_eq!(shard, 0); + assert_eq!(path, p0); + assert_eq!(source.kind(), io::ErrorKind::ConnectionRefused); + assert_eq!(partial_report.total_bytes_sent, 0); + } + other => panic!("expected ShardIo(Connect), got {other:?}"), + } +} + +#[test] +fn tcp_connector_skips_unreachable_address_then_pins_reachable_one_for_all_shards() { + let dir = TempDirGuard::new("ilp-send-tcp-pin-first-live"); + let payloads: Vec> = (0..3) + .map(|i| format!("bars_1m,listing_id={i} open=1.0 170000000000000{i}t\n").into_bytes()) + .collect(); + for (i, payload) in payloads.iter().enumerate() { + write_bytes(&dir.path().join(format!("bars_1m.shard-{i:02}.ilp")), payload); + } + let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); + + let dead = refused_loopback_addr(); + let live = TcpListener::bind("127.0.0.1:0").expect("bind live endpoint"); + let live_addr = live.local_addr().expect("live addr"); + live.set_nonblocking(true).expect("nonblocking live"); + + let server = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(3); + let mut readers = Vec::new(); + for accepted in 0..3 { + let (mut stream, _) = accept_with_deadline(&live, deadline, accepted, 3); + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("read timeout"); + readers.push(thread::spawn(move || { + let mut buf = Vec::new(); + stream.read_to_end(&mut buf).expect("read to EOF"); + buf + })); + } + readers + .into_iter() + .map(|h| h.join().expect("join reader")) + .collect::>() + }); + + let connector = tcp_ilp_connector_for_addrs( + vec![dead, live_addr], + IlpTcpOptions { + connect_timeout: Duration::from_secs(2), + write_timeout: Duration::from_secs(2), + }, + ) + .expect("connector"); + let peers = Mutex::new(Vec::::new()); + let report = send_ilp_shard_files( + &files, + |shard| { + let sink = connector(shard)?; + peers + .lock() + .expect("lock peers") + .push(sink.inner().peer_addr().expect("peer addr")); + Ok(sink) + }, + IlpSendOptions { buffer_bytes: 5 }, + ) + .expect("send via first reachable address"); + + let mut received = server.join().expect("join server"); + received.sort(); + let mut expected = payloads.clone(); + expected.sort(); + assert_eq!(received, expected); + let peers = peers.into_inner().expect("peers"); + assert_eq!(peers.len(), 3); + assert!(peers.iter().all(|p| *p == live_addr), "{peers:?}"); + assert_eq!( + report.total_bytes_sent, + payloads.iter().map(|p| p.len() as u64).sum::() + ); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index c1dcf4ee..a351d5e4 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -22,6 +22,7 @@ pub mod events; pub mod fundamentals; pub mod fx; pub mod ilp; +pub mod ilp_send; pub mod macro_series; pub mod mongo_safety; pub mod mongo_stream; @@ -105,7 +106,8 @@ pub use bson_stream::{ decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_financials_chunks, decode_qm_financials_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_chunks, decode_qm_price_stream, decode_qm_split_chunks, - decode_qm_split_stream, decode_te_market_data_chunks, decode_te_market_data_stream, + decode_qm_split_stream, decode_te_data_chunks, decode_te_data_stream, + decode_te_market_data_chunks, decode_te_market_data_stream, BsonCeoPostsStreamError, BsonCeoShortsStreamError, BsonQmEventsStreamError, BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, @@ -155,6 +157,12 @@ pub use ilp::{ DEFAULT_ILP_MAX_BATCH_BYTES, DEFAULT_ILP_MAX_BATCH_ROWS, FNV1A_64_OFFSET_BASIS, FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M, }; +pub use ilp_send::{ + discover_ilp_shard_files, format_ilp_send_report, send_ilp_shard_files, tcp_ilp_connector, + IlpSendError, IlpSendOp, IlpSendOptions, IlpSendReport, IlpShardFile, IlpShardSendReport, + IlpTcpOptions, IlpTcpSink, DEFAULT_ILP_SEND_BUFFER_BYTES, DEFAULT_ILP_TCP_CONNECT_TIMEOUT, + DEFAULT_ILP_TCP_WRITE_TIMEOUT, +}; pub use macro_series::{ build_macro_rows, MacroBuild, MacroBuildStats, MacroError, MacroLagClass, MacroObservation, MacroRow, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, MONTHLY_RELEASE_LAG_DAYS, @@ -326,6 +334,26 @@ pub use run_curate_bars::{ SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE, }; +pub mod run_curate_bars_1m; +pub use run_curate_bars_1m::{ + format_curate_bars_1m_report, run_curate_bars_1m, run_curate_bars_1m_with_readers, + CurateBars1mArgs, CurateBars1mRunReport, RunCurateBars1mError, + DEFAULT_BARS_1M_MAPPING_SOURCE, +}; + +pub mod run_curate_fx_1m; +pub use run_curate_fx_1m::{ + format_curate_fx_1m_report, run_curate_fx_1m, run_curate_fx_1m_with_readers, CurateFx1mArgs, + CurateFx1mRunReport, RunCurateFx1mError, +}; + +pub mod run_curate_qm_bars_1m; +pub use run_curate_qm_bars_1m::{ + format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, run_curate_qm_bars_1m_with_readers, + CurateQmBars1mArgs, CurateQmBars1mRunReport, RunCurateQmBars1mError, + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, +}; + pub mod run_curate_adj; pub use run_curate_adj::{ format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 936c0d64..c23b3457 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -23,11 +23,13 @@ use curate_etl::run_curate_adj::{ format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced, }; use curate_etl::run_curate_bars::{format_curate_bars_report, run_curate_bars_1d}; +use curate_etl::run_curate_bars_1m::{format_curate_bars_1m_report, run_curate_bars_1m}; use curate_etl::run_curate_corporate_actions::{ format_curate_corporate_actions_report, run_curate_corporate_actions, }; use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events}; use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d}; +use curate_etl::run_curate_fx_1m::{format_curate_fx_1m_report, run_curate_fx_1m}; use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts}; use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts}; use curate_etl::run_mongo::{ @@ -198,6 +200,26 @@ fn main() -> ExitCode { } } } + Ok(CliAction::CurateBars1m(curate_args)) => match run_curate_bars_1m(&curate_args) { + Ok(report) => { + println!("{}", format_curate_bars_1m_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + }, + Ok(CliAction::CurateFx1m(curate_args)) => match run_curate_fx_1m(&curate_args) { + Ok(report) => { + println!("{}", format_curate_fx_1m_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + }, Ok(CliAction::CuratePosts(curate_args)) => match run_curate_posts(&curate_args) { Ok(report) => { println!("{}", format_curate_posts_report(&report)); diff --git a/tools/curate-etl/src/parquet_publish.rs b/tools/curate-etl/src/parquet_publish.rs index 00d6f1a4..358bbf27 100644 --- a/tools/curate-etl/src/parquet_publish.rs +++ b/tools/curate-etl/src/parquet_publish.rs @@ -310,6 +310,10 @@ impl StagingFileGuard { pub(crate) fn disarm(&mut self) { self.path = None; } + + pub(crate) fn is_armed(&self) -> bool { + self.path.is_some() + } } impl Drop for StagingFileGuard { diff --git a/tools/curate-etl/src/run_curate_bars.rs b/tools/curate-etl/src/run_curate_bars.rs index 00283b63..c45eec76 100644 --- a/tools/curate-etl/src/run_curate_bars.rs +++ b/tools/curate-etl/src/run_curate_bars.rs @@ -516,12 +516,34 @@ struct LoadedCurateBarsInputs { buffered_bar_bytes: usize, } -struct EodListingRange { +pub(crate) struct EodListingRange { valid_from: i32, valid_to: Option, key: Arc, } +pub(crate) struct EodMappingIndex { + pub(crate) eod_keys: HashSet>, + pub(crate) eod_by_listing: HashMap>>, + pub(crate) eod_ranges_by_listing: HashMap>, +} + +pub(crate) struct DecodedQmSplits { + pub(crate) compacted_splits: Vec<(i32, SplitEvent)>, + pub(crate) splits_docs_framed: u64, + pub(crate) splits_bytes_read: u64, + pub(crate) splits_decode: BsonQmActionDecodeStats, + pub(crate) split_rekey: SplitRekeyStats, +} + +pub(crate) struct LoadedQmSplits { + pub(crate) splits: SplitTable>, + pub(crate) splits_docs_framed: u64, + pub(crate) splits_bytes_read: u64, + pub(crate) splits_decode: BsonQmActionDecodeStats, + pub(crate) split_rekey: SplitRekeyStats, +} + #[inline] fn valid_to_sort_key(valid_to: Option) -> (u8, i32) { match valid_to { @@ -530,6 +552,170 @@ fn valid_to_sort_key(valid_to: Option) -> (u8, i32) { } } +/// Builds the interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once. +/// When `track_eod_ranges` is true, also builds a date-aware reverse index +/// `listing_id -> [(valid_from, valid_to, Arc)]` so reused EOD tickers never receive +/// cross-check observations outside their mapping range. +pub(crate) fn build_eod_mapping_index( + mapping_rows: &[ProviderMappingRow], + track_eod_ranges: bool, +) -> EodMappingIndex { + let mut eod_keys: HashSet> = HashSet::new(); + let mut eod_by_listing: HashMap>> = HashMap::new(); + let mut eod_ranges_by_listing: HashMap> = HashMap::new(); + for row in mapping_rows { + if row.source == "eod" { + let key = match eod_keys.get(row.source_id.as_str()) { + Some(existing) => Arc::clone(existing), + None => { + let arc: Arc = Arc::from(row.source_id.as_str()); + eod_keys.insert(Arc::clone(&arc)); + arc + } + }; + if track_eod_ranges { + eod_ranges_by_listing + .entry(row.listing_id) + .or_default() + .push(EodListingRange { + valid_from: row.valid_from, + valid_to: row.valid_to, + key: Arc::clone(&key), + }); + } + eod_by_listing.entry(row.listing_id).or_default().push(key); + } + } + for partners in eod_by_listing.values_mut() { + partners.sort_unstable(); + partners.dedup(); + } + for ranges in eod_ranges_by_listing.values_mut() { + ranges.sort_unstable_by(|a, b| { + a.valid_from + .cmp(&b.valid_from) + .then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to))) + .then_with(|| a.key.cmp(&b.key)) + }); + } + EodMappingIndex { + eod_keys, + eod_by_listing, + eod_ranges_by_listing, + } +} + +/// Streams `qmSplits` BSON, resolves `("qm", qmSearchCode, ex_date) -> listing_id`, filters out +/// listings without an `"eod"` partner, and compacts cross-key QM aliases per `(listing_id, ex_date)` +/// while retaining permanent `listing_id` identity. +pub(crate) fn decode_and_compact_qm_splits_from_reader( + splits_stream: R, + qm_splits_path: &Path, + mapping: &ProviderMappingTable, + eod_by_listing: &HashMap>>, +) -> Result { + let mut splits_reader = RawBsonChunkReader::new(splits_stream); + let mut split_rekey = SplitRekeyStats::default(); + let mut mapped_splits: Vec = Vec::new(); + let splits_decode = decode_qm_split_chunks( + &mut splits_reader, + |split| { + if split.ratio == 1.0 { + split_rekey.splits_noop_dropped += 1; + return; + } + let Some(listing_id) = mapping.resolve("qm", split.qm_search_code, split.ex_date) + else { + split_rekey.splits_unmapped_qm += 1; + return; + }; + let has_eod_partner = eod_by_listing + .get(&listing_id) + .is_some_and(|partners| !partners.is_empty()); + if !has_eod_partner { + split_rekey.splits_no_eod_partner += 1; + return; + } + mapped_splits.push(MappedQmSplit { + listing_id, + ex_date: split.ex_date, + qm_key: split.qm_search_code.to_owned(), + ratio: split.ratio, + }); + }, + |_offset, _err| {}, + ) + .map_err(|source| RunCurateBarsError::BsonStream { + label: "qm-splits", + path: qm_splits_path.to_path_buf(), + source, + })?; + let splits_docs_framed = splits_reader.docs_framed(); + let splits_bytes_read = splits_reader.bytes_read(); + split_rekey.splits_in = splits_decode.docs_in; + + // Compact cross-key QM aliases per `(listing_id, ex_date)`. + let (compacted_splits, splits_collision_collapsed) = + compact_mapped_qm_splits(qm_splits_path, mapped_splits)?; + split_rekey.splits_collision_collapsed = splits_collision_collapsed; + + Ok(DecodedQmSplits { + compacted_splits, + splits_docs_framed, + splits_bytes_read, + splits_decode, + split_rekey, + }) +} + +/// Streams `qmSplits` BSON, resolves `("qm", qmSearchCode, ex_date) -> listing_id`, compacts +/// cross-key QM aliases per `(listing_id, ex_date)`, fans out to `"eod"` partners, and builds +/// [`SplitTable>`]. +pub(crate) fn load_qm_splits_from_reader( + splits_stream: R, + qm_splits_path: &Path, + mapping: &ProviderMappingTable, + eod_by_listing: &HashMap>>, +) -> Result { + let DecodedQmSplits { + compacted_splits, + splits_docs_framed, + splits_bytes_read, + splits_decode, + mut split_rekey, + } = decode_and_compact_qm_splits_from_reader( + splits_stream, + qm_splits_path, + mapping, + eod_by_listing, + )?; + + let mut split_events: Vec<(Arc, SplitEvent)> = Vec::with_capacity(compacted_splits.len()); + for (listing_id, event) in compacted_splits { + let partners = &eod_by_listing[&listing_id]; + split_rekey.splits_applied += 1; + for eod_key in partners { + split_events.push((Arc::clone(eod_key), event)); + } + split_rekey.split_events_attached += partners.len(); + } + + let splits = SplitTable::>::from_events(split_events).map_err(|source| { + RunCurateBarsError::SplitTable { + path: qm_splits_path.to_path_buf(), + source, + } + })?; + + Ok(LoadedQmSplits { + splits, + splits_docs_framed, + splits_bytes_read, + splits_decode, + split_rekey, + }) +} + fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateBarsError> { if out_dir.exists() && !out_dir.is_dir() { return Err(RunCurateBarsError::InvalidOutDir { @@ -718,49 +904,11 @@ where let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)?; let currencies = load_listing_currencies_tsv(listing_currencies_path)?; - // Build interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once. - // When `--qm-prices` is provided, also build a date-aware reverse index - // `listing_id -> [(valid_from, valid_to, Arc)]` so reused EOD tickers never receive - // cross-check observations outside their mapping range. - let mut eod_keys: HashSet> = HashSet::new(); - let mut eod_by_listing: HashMap>> = HashMap::new(); - let mut eod_ranges_by_listing: HashMap> = HashMap::new(); - let track_eod_ranges = qm_prices_path.is_some(); - for row in &mapping_rows { - if row.source == "eod" { - let key = match eod_keys.get(row.source_id.as_str()) { - Some(existing) => Arc::clone(existing), - None => { - let arc: Arc = Arc::from(row.source_id.as_str()); - eod_keys.insert(Arc::clone(&arc)); - arc - } - }; - if track_eod_ranges { - eod_ranges_by_listing - .entry(row.listing_id) - .or_default() - .push(EodListingRange { - valid_from: row.valid_from, - valid_to: row.valid_to, - key: Arc::clone(&key), - }); - } - eod_by_listing.entry(row.listing_id).or_default().push(key); - } - } - for partners in eod_by_listing.values_mut() { - partners.sort_unstable(); - partners.dedup(); - } - for ranges in eod_ranges_by_listing.values_mut() { - ranges.sort_unstable_by(|a, b| { - a.valid_from - .cmp(&b.valid_from) - .then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to))) - .then_with(|| a.key.cmp(&b.key)) - }); - } + let EodMappingIndex { + eod_keys, + eod_by_listing, + eod_ranges_by_listing, + } = build_eod_mapping_index(&mapping_rows, qm_prices_path.is_some()); let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { RunCurateBarsError::ProviderMapping { @@ -771,67 +919,13 @@ where // Stream `qmSplits` and resolve `("qm", qmSearchCode, ex_date) -> listing_id`. let splits_stream = open_splits()?; - let mut splits_reader = RawBsonChunkReader::new(splits_stream); - let mut split_rekey = SplitRekeyStats::default(); - let mut mapped_splits: Vec = Vec::new(); - let splits_decode = decode_qm_split_chunks( - &mut splits_reader, - |split| { - if split.ratio == 1.0 { - split_rekey.splits_noop_dropped += 1; - return; - } - let Some(listing_id) = mapping.resolve("qm", split.qm_search_code, split.ex_date) - else { - split_rekey.splits_unmapped_qm += 1; - return; - }; - let has_eod_partner = eod_by_listing - .get(&listing_id) - .is_some_and(|partners| !partners.is_empty()); - if !has_eod_partner { - split_rekey.splits_no_eod_partner += 1; - return; - } - mapped_splits.push(MappedQmSplit { - listing_id, - ex_date: split.ex_date, - qm_key: split.qm_search_code.to_owned(), - ratio: split.ratio, - }); - }, - |_offset, _err| {}, - ) - .map_err(|source| RunCurateBarsError::BsonStream { - label: "qm-splits", - path: qm_splits_path.to_path_buf(), - source, - })?; - let splits_docs_framed = splits_reader.docs_framed(); - let splits_bytes_read = splits_reader.bytes_read(); - split_rekey.splits_in = splits_decode.docs_in; - - // Compact cross-key QM aliases per `(listing_id, ex_date)` before fanning out to `"eod"` keys. - let (compacted_splits, splits_collision_collapsed) = - compact_mapped_qm_splits(qm_splits_path, mapped_splits)?; - split_rekey.splits_collision_collapsed = splits_collision_collapsed; - - let mut split_events: Vec<(Arc, SplitEvent)> = Vec::with_capacity(compacted_splits.len()); - for (listing_id, event) in compacted_splits { - let partners = &eod_by_listing[&listing_id]; - split_rekey.splits_applied += 1; - for eod_key in partners { - split_events.push((Arc::clone(eod_key), event)); - } - split_rekey.split_events_attached += partners.len(); - } - - let splits = SplitTable::>::from_events(split_events).map_err(|source| { - RunCurateBarsError::SplitTable { - path: qm_splits_path.to_path_buf(), - source, - } - })?; + let LoadedQmSplits { + splits, + splits_docs_framed, + splits_bytes_read, + splits_decode, + split_rekey, + } = load_qm_splits_from_reader(splits_stream, qm_splits_path, &mapping, &eod_by_listing)?; // Stream `eodPrices`, dropping unmapped `"eod"` keys before buffering and interning keys. let eod_stream = open_eod()?; diff --git a/tools/curate-etl/src/run_curate_bars_1m.rs b/tools/curate-etl/src/run_curate_bars_1m.rs new file mode 100644 index 00000000..86c6c8e5 --- /dev/null +++ b/tools/curate-etl/src/run_curate_bars_1m.rs @@ -0,0 +1,892 @@ +//! Bounded-memory file-to-file `bars_1m` runner (`M2.3k`). +//! +//! Streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a +//! headerless 5-column `provider_mapping.tsv` into per-shard QuestDB ILP v2 files +//! (`/bars_1m.shard-.ilp`) via listing-keyed [`crate::curate_bars_1m`] curation. +//! +//! # Bounded-Memory Chunking +//! - Drives [`RawBsonChunkReader::with_options`], [`RawBsonChunkReader::next_chunk`], and +//! [`decode_eod_intraday_buffer`] directly—the exact reader and buffer decoder wrapped by +//! `crate::bson_stream::decode_eod_intraday_chunks`, whose callback API hides chunk boundaries. +//! - Each framed chunk is decoded into a chunk-local `Vec>>` (reusing +//! interned `"eod"` keys from `provider_mapping.tsv` and retaining unknown codes so +//! `curate_bars_1m` counts them in `dropped_unmapped`) and curated per chunk against one shared +//! [`IlpShardedWriter`] (resolving `listing_id` on each bar's Eastern Time `session_date` before +//! applying listing-keyed splits). +//! - [`IlpShardedWriter::finish`] is called exactly once after clean EOF. +//! - Peak memory is bounded by the reference tables (`provider_mapping` + `SplitTable`), the +//! current BSON chunk (`BsonStreamOptions::chunk_capacity_bytes`, growing only for a single +//! document up to `max_doc_bytes`), that chunk's curation buffers, and one ILP batch buffer per +//! shard—independent of the total `eodIntraday1M` input size. +//! +//! # Cross-Chunk Semantics & Reporting +//! - Collision collapse/drop in `curate_bars_1m` and row ordering apply **per chunk**: output is +//! sorted by `(listing_id, ts)` within each chunk, and the same `(listing_id, ts)` appearing in +//! two different chunks is emitted twice (with zero within-chunk collapse between them) and +//! relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. +//! - `CurateBars1mRunReport::curate_stats` sums every field of [`CurateBars1mStats`] and its +//! nested [`Bars1mStats`] across chunks. In particular, `curate_stats.listings_out` and +//! `curate_stats.builder.keys_out` are **sums of per-chunk counts**, not global distinct counts. +//! - `mapping_source` must be `"eod"` because the shared `qmSplits` loader +//! (`run_curate_bars::decode_and_compact_qm_splits_from_reader`) filters to listings with `"eod"` +//! partners. Split events retain permanent `listing_id: i32` identity (`SplitTable`), and +//! each bar's listing is resolved via `provider_mapping` on its Eastern Time `session_date` +//! **before** choosing the split factor so reused tickers cannot leak splits across listings. +//! - `known_at_micros` is a caller-supplied run timestamp written verbatim to every ILP row's +//! `known_at` column; it supplies no evidence of earlier market availability. +//! +//! # File Publication & Fail-Closed Guarantees +//! - Preflight scans `out_dir` for **any** pre-existing `bars_1m.shard-.ilp` file +//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards +//! from a prior larger-shard-count run cannot survive alongside a new export. +//! - Each shard writes into an exclusively created staging file in `out_dir` +//! (`.bars_1m.shard-..tmp`), flushes and `sync_all`s on `finish`, and publishes to +//! `bars_1m.shard-.ilp` via same-directory `hard_link` followed by removing the staged name +//! (preserving no-overwrite semantics even if a final file appears after preflight). +//! - Any error (validation, missing/malformed inputs, fatal BSON framing/I/O, ILP write/flush, or +//! publication collision) rolls back only final files created by this run, removes this run's +//! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors +//! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`]. + +use std::collections::{HashMap, HashSet}; +use std::error::Error; +use std::ffi::OsStr; +use std::fmt; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; + +use crate::bars_1m::{Bars1mStats, EodIntradayBar}; +use crate::bson_eod_intraday::{decode_eod_intraday_buffer, BsonEodIntradayDecodeStats}; +use crate::bson_qm_actions::BsonQmActionDecodeStats; +use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader}; +use crate::curate_bars_1m::{ + curate_and_write_bars_1m_by_listing, CurateBars1mStats, CurateBars1mWriteError, +}; +use crate::ilp::{ + IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_BARS_1M, +}; +use crate::parquet_bars::RollbackFailure; +use crate::parquet_publish::{ + next_run_id, rollback_published, PublishedPartition, StagingFileGuard, FILE_BUF_CAPACITY_BYTES, +}; +use crate::provider_mapping::ProviderMappingTable; +use crate::run_curate_bars::{ + build_eod_mapping_index, decode_and_compact_qm_splits_from_reader, load_provider_mapping_tsv, + DecodedQmSplits, EodMappingIndex, RunCurateBarsError, SplitRekeyStats, +}; +use crate::split::SplitTable; + +/// Required `provider_mapping` source namespace for `eodIntraday1M` bars. +pub const DEFAULT_BARS_1M_MAPPING_SOURCE: &str = "eod"; + +/// Arguments for [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateBars1mArgs { + pub intraday_path: PathBuf, + pub splits_path: PathBuf, + pub provider_mapping_path: PathBuf, + pub out_dir: PathBuf, + pub mapping_source: String, + pub shard_count: usize, + pub known_at_micros: i64, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +/// Full run report produced by [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`]. +/// +/// Conservation invariants: +/// - `intraday_docs_framed as usize == intraday_decode.docs_seen` +/// - `intraday_decode.docs_seen == intraday_decode.rows_decoded + intraday_decode.rejected_total()` +/// - `intraday_decode.rows_decoded == curate_stats.builder.bars_in` +/// - `curate_stats.rows_in == curate_stats.builder.rows_out` +/// - `curate_stats.rows_in == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped` +/// - `curate_stats.pre_rows_out + curate_stats.rth_rows_out + curate_stats.post_rows_out == curate_stats.rows_out` +/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::()` +/// +/// Note: `curate_stats.listings_out` and `curate_stats.builder.keys_out` are summed across chunks +/// (not global distinct counts). +#[derive(Debug, Clone, PartialEq)] +pub struct CurateBars1mRunReport { + pub intraday_docs_framed: u64, + pub intraday_bytes_read: u64, + pub intraday_decode: BsonEodIntradayDecodeStats, + pub splits_docs_framed: u64, + pub splits_bytes_read: u64, + pub splits_decode: BsonQmActionDecodeStats, + pub split_rekey: SplitRekeyStats, + pub chunks: usize, + pub max_rows_per_chunk: usize, + pub curate_stats: CurateBars1mStats, + pub rows_written: usize, + pub ilp_stats: IlpWriteStats, + pub shard_count: usize, + pub elapsed_secs: f64, +} + +/// Typed errors returned by [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`]. +#[derive(Debug)] +pub enum RunCurateBars1mError { + /// `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, + /// `mapping_source` was non-blank but not `"eod"`. + UnsupportedMappingSource { mapping_source: String }, + /// `shard_count` was `0`. + ZeroShardCount, + /// Caller-supplied `IlpShardedWriter` shard count did not match `args.shard_count`. + ShardCountMismatch { expected: usize, actual: usize }, + /// `out_dir` exists and is not a directory. + InvalidOutDir { path: PathBuf, detail: String }, + /// A final shard output file (`bars_1m.shard-.ilp`) already existed. + OutputFileExists { path: PathBuf }, + /// Failed to open an input dump file. + OpenInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + /// Failed to load `provider_mapping.tsv` or `qmSplits` via the shared reference loader. + LoadReference(RunCurateBarsError), + /// Fatal BSON framing, option validation, or I/O error while reading `eodIntraday1M`. + BsonStream { + label: &'static str, + path: PathBuf, + source: BsonStreamError, + }, + /// Curation or per-row ILP write error inside the per-chunk `bars_1m` curation stage. + CurateWrite(CurateBars1mWriteError), + /// ILP writer initialization or final flush error. + Ilp(IlpWriterError), + /// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files. + Io { path: PathBuf, source: io::Error }, + /// Publication failed and rolling back one or more already-published shards also failed. + RollbackFailed { + cause: Box, + failures: Vec, + }, +} + +impl fmt::Display for RunCurateBars1mError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyMappingSource => write!(f, "mapping_source must not be empty or blank"), + Self::UnsupportedMappingSource { mapping_source } => write!( + f, + "unsupported mapping_source '{mapping_source}': only '{DEFAULT_BARS_1M_MAPPING_SOURCE}' is supported" + ), + Self::ZeroShardCount => write!(f, "shard_count must be >= 1"), + Self::ShardCountMismatch { expected, actual } => write!( + f, + "ILP writer shard count mismatch: expected {expected}, got {actual}" + ), + Self::InvalidOutDir { path, detail } => { + write!(f, "invalid out_dir '{}': {detail}", path.display()) + } + Self::OutputFileExists { path } => write!( + f, + "refusing to overwrite existing output file '{}'", + path.display() + ), + Self::OpenInput { + label, + path, + source, + } => write!(f, "failed to open {label} '{}': {source}", path.display()), + Self::LoadReference(err) => write!(f, "failed loading reference inputs: {err}"), + Self::BsonStream { + label, + path, + source, + } => write!(f, "failed reading {label} '{}': {source}", path.display()), + Self::CurateWrite(err) => write!(f, "{err}"), + Self::Ilp(err) => write!(f, "bars_1m ILP writer failed: {err}"), + Self::Io { path, source } => { + write!(f, "I/O error on '{}': {source}", path.display()) + } + Self::RollbackFailed { cause, failures } => { + write!(f, "{cause}; rollback also failed for: ")?; + for (i, failure) in failures.iter().enumerate() { + if i > 0 { + write!(f, ", ")?; + } + write!(f, "{failure}")?; + } + Ok(()) + } + } + } +} + +impl Error for RunCurateBars1mError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source), + Self::LoadReference(err) => Some(err), + Self::BsonStream { source, .. } => Some(source), + Self::CurateWrite(err) => Some(err), + Self::Ilp(err) => Some(err), + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::EmptyMappingSource + | Self::UnsupportedMappingSource { .. } + | Self::ZeroShardCount + | Self::ShardCountMismatch { .. } + | Self::InvalidOutDir { .. } + | Self::OutputFileExists { .. } => None, + } + } +} + +struct LoadedReferenceInputs { + mapping: ProviderMappingTable, + eod_keys: HashSet>, + splits: SplitTable, + splits_docs_framed: u64, + splits_bytes_read: u64, + splits_decode: BsonQmActionDecodeStats, + split_rekey: SplitRekeyStats, +} + +fn validate_common_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mError> { + if args.mapping_source.trim().is_empty() { + return Err(RunCurateBars1mError::EmptyMappingSource); + } + if args.mapping_source != DEFAULT_BARS_1M_MAPPING_SOURCE { + return Err(RunCurateBars1mError::UnsupportedMappingSource { + mapping_source: args.mapping_source.clone(), + }); + } + if args.shard_count == 0 { + return Err(RunCurateBars1mError::ZeroShardCount); + } + args.stream_options + .validate() + .map_err(|source| RunCurateBars1mError::BsonStream { + label: "eod-intraday", + path: args.intraday_path.clone(), + source, + })?; + Ok(()) +} + +pub(crate) enum ShardPublishError { + InvalidOutDir { path: PathBuf, detail: String }, + OutputFileExists { path: PathBuf }, + Io { path: PathBuf, source: io::Error }, + RollbackFailed { + cause: Box, + failures: Vec, + }, +} + +impl From for RunCurateBars1mError { + fn from(err: ShardPublishError) -> Self { + match err { + ShardPublishError::InvalidOutDir { path, detail } => { + Self::InvalidOutDir { path, detail } + } + ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path }, + ShardPublishError::Io { path, source } => Self::Io { path, source }, + ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed { + cause: Box::new((*cause).into()), + failures, + }, + } + } +} + +fn validate_file_mode_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mError> { + validate_common_args(args)?; + if args.ilp_options.max_batch_bytes == 0 { + return Err(RunCurateBars1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes)); + } + if args.ilp_options.max_batch_rows == 0 { + return Err(RunCurateBars1mError::Ilp(IlpWriterError::ZeroMaxBatchRows)); + } + preflight_shard_out_dir(&args.out_dir, TABLE_BARS_1M)?; + Ok(()) +} + +pub(crate) fn preflight_shard_out_dir( + out_dir: &Path, + table: &str, +) -> Result<(), ShardPublishError> { + if out_dir.exists() { + if !out_dir.is_dir() { + return Err(ShardPublishError::InvalidOutDir { + path: out_dir.to_path_buf(), + detail: "path exists and is not a directory".to_string(), + }); + } + let entries = fs::read_dir(out_dir).map_err(|source| ShardPublishError::Io { + path: out_dir.to_path_buf(), + source, + })?; + let mut existing_shards: Vec = Vec::new(); + for entry in entries { + let entry = entry.map_err(|source| ShardPublishError::Io { + path: out_dir.to_path_buf(), + source, + })?; + if is_final_shard_file_name_for_table(table, &entry.file_name()) { + existing_shards.push(entry.path()); + } + } + if !existing_shards.is_empty() { + existing_shards.sort(); + return Err(ShardPublishError::OutputFileExists { + path: existing_shards.remove(0), + }); + } + } + Ok(()) +} + +#[inline] +pub(crate) fn is_final_shard_file_name_for_table(table: &str, name: &OsStr) -> bool { + let Some(s) = name.to_str() else { + return false; + }; + let Some(after_table) = s.strip_prefix(table) else { + return false; + }; + let Some(rest) = after_table.strip_prefix(".shard-") else { + return false; + }; + let Some(digits) = rest.strip_suffix(".ilp") else { + return false; + }; + !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) +} + +#[inline] +pub(crate) fn final_shard_path_for_table( + out_dir: &Path, + table: &str, + shard_idx: usize, +) -> PathBuf { + out_dir.join(format!("{table}.shard-{shard_idx:02}.ilp")) +} + +fn load_reference_inputs( + provider_mapping_path: &Path, + splits_path: &Path, + splits_reader: RS, +) -> Result { + let mapping_rows = + load_provider_mapping_tsv(provider_mapping_path).map_err(RunCurateBars1mError::LoadReference)?; + let EodMappingIndex { + eod_keys, + eod_by_listing, + .. + } = build_eod_mapping_index(&mapping_rows, false); + + let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { + RunCurateBars1mError::LoadReference(RunCurateBarsError::ProviderMapping { + path: provider_mapping_path.to_path_buf(), + source, + }) + })?; + + let DecodedQmSplits { + compacted_splits, + splits_docs_framed, + splits_bytes_read, + splits_decode, + mut split_rekey, + } = decode_and_compact_qm_splits_from_reader( + splits_reader, + splits_path, + &mapping, + &eod_by_listing, + ) + .map_err(RunCurateBars1mError::LoadReference)?; + + split_rekey.splits_applied = compacted_splits.len(); + split_rekey.split_events_attached = compacted_splits.len(); + + let splits = SplitTable::::from_events(compacted_splits).map_err(|source| { + RunCurateBars1mError::LoadReference(RunCurateBarsError::SplitTable { + path: splits_path.to_path_buf(), + source, + }) + })?; + + Ok(LoadedReferenceInputs { + mapping, + eod_keys, + splits, + splits_docs_framed, + splits_bytes_read, + splits_decode, + split_rekey, + }) +} + +#[inline] +fn add_bars_1m_stats(total: &mut Bars1mStats, chunk: &Bars1mStats) { + total.bars_in += chunk.bars_in; + total.rows_out += chunk.rows_out; + total.keys_out += chunk.keys_out; + total.pre_rows_out += chunk.pre_rows_out; + total.rth_rows_out += chunk.rth_rows_out; + total.post_rows_out += chunk.post_rows_out; + total.dropped_invalid_ohlc += chunk.dropped_invalid_ohlc; + total.dropped_inconsistent_ohlc += chunk.dropped_inconsistent_ohlc; + total.dropped_invalid_volume += chunk.dropped_invalid_volume; + total.dropped_ts_out_of_range += chunk.dropped_ts_out_of_range; + total.duplicate_collapsed += chunk.duplicate_collapsed; + total.duplicate_conflict_dropped += chunk.duplicate_conflict_dropped; +} + +#[inline] +pub(crate) fn add_curate_bars_1m_stats(total: &mut CurateBars1mStats, chunk: &CurateBars1mStats) { + add_bars_1m_stats(&mut total.builder, &chunk.builder); + total.rows_in += chunk.rows_in; + total.rows_out += chunk.rows_out; + total.listings_out += chunk.listings_out; + total.pre_rows_out += chunk.pre_rows_out; + total.rth_rows_out += chunk.rth_rows_out; + total.post_rows_out += chunk.post_rows_out; + total.dropped_unmapped += chunk.dropped_unmapped; + total.listing_collision_collapsed += chunk.listing_collision_collapsed; + total.listing_collision_dropped += chunk.listing_collision_dropped; +} + +fn stream_intraday_chunks_to_writer( + args: &CurateBars1mArgs, + reference: LoadedReferenceInputs, + intraday: RI, + mut writer: IlpShardedWriter, + start: Instant, +) -> Result +where + RI: io::Read, + W: Write + Send, +{ + let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err( + |source| RunCurateBars1mError::BsonStream { + label: "eod-intraday", + path: args.intraday_path.clone(), + source, + }, + )?; + + let mut intraday_decode = BsonEodIntradayDecodeStats::default(); + let mut curate_stats = CurateBars1mStats::default(); + let mut chunks: usize = 0; + let mut max_rows_per_chunk: usize = 0; + let mut rows_written: usize = 0; + + // Reusable per-chunk buffers; cleared before each chunk so peak RAM stays bounded by chunk size. + let mut chunk_bars: Vec>> = Vec::new(); + let mut unknown_keys: HashMap> = HashMap::new(); + + while let Some(chunk) = + reader + .next_chunk() + .map_err(|source| RunCurateBars1mError::BsonStream { + label: "eod-intraday", + path: args.intraday_path.clone(), + source, + })? + { + chunk_bars.clear(); + unknown_keys.clear(); + + let chunk_decode = decode_eod_intraday_buffer( + chunk.bytes, + |raw| { + let key = if let Some(existing) = reference.eod_keys.get(raw.eod_search_code) { + Arc::clone(existing) + } else if let Some(existing) = unknown_keys.get(raw.eod_search_code) { + Arc::clone(existing) + } else { + let arc: Arc = Arc::from(raw.eod_search_code); + unknown_keys.insert(raw.eod_search_code.to_owned(), Arc::clone(&arc)); + arc + }; + chunk_bars.push(raw.into_eod_intraday_bar(|_, _| key)); + }, + |_local_offset, _err| {}, + ); + intraday_decode += chunk_decode; + + chunks += 1; + let chunk_len = chunk_bars.len(); + if chunk_len > max_rows_per_chunk { + max_rows_per_chunk = chunk_len; + } + + let write_report = curate_and_write_bars_1m_by_listing( + chunk_bars.drain(..), + &reference.splits, + &reference.mapping, + &args.mapping_source, + &mut writer, + args.known_at_micros, + ) + .map_err(RunCurateBars1mError::CurateWrite)?; + + add_curate_bars_1m_stats(&mut curate_stats, &write_report.curate_stats); + rows_written += write_report.rows_written; + } + + let intraday_docs_framed = reader.docs_framed(); + let intraday_bytes_read = reader.bytes_read(); + let ilp_stats = writer.finish().map_err(RunCurateBars1mError::Ilp)?; + + Ok(CurateBars1mRunReport { + intraday_docs_framed, + intraday_bytes_read, + intraday_decode, + splits_docs_framed: reference.splits_docs_framed, + splits_bytes_read: reference.splits_bytes_read, + splits_decode: reference.splits_decode, + split_rekey: reference.split_rekey, + chunks, + max_rows_per_chunk, + curate_stats, + rows_written, + ilp_stats, + shard_count: args.shard_count, + elapsed_secs: start.elapsed().as_secs_f64(), + }) +} + +/// Runs the bounded-memory `bars_1m` curation pipeline from arbitrary [`io::Read`] streams into a +/// caller-owned [`IlpShardedWriter`]. +/// +/// Validates `args`, loads `provider_mapping.tsv` from `args.provider_mapping_path` and `qmSplits` +/// from `splits`, streams `intraday` through [`RawBsonChunkReader::with_options`] + +/// [`decode_eod_intraday_buffer`] curating and writing once per chunk with listing-keyed splits, +/// and calls [`IlpShardedWriter::finish`] exactly once after EOF. +pub fn run_curate_bars_1m_with_readers( + args: &CurateBars1mArgs, + intraday: RI, + splits: RS, + writer: IlpShardedWriter, +) -> Result +where + RI: io::Read, + RS: io::Read, + W: Write + Send, +{ + let start = Instant::now(); + validate_common_args(args)?; + if writer.shard_count() != args.shard_count { + return Err(RunCurateBars1mError::ShardCountMismatch { + expected: args.shard_count, + actual: writer.shard_count(), + }); + } + + let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?; + stream_intraday_chunks_to_writer(args, reference, intraday, writer, start) +} + +/// Buffered file sink that flushes and calls `File::sync_all()` on [`Write::flush`] (invoked once +/// per shard by [`IlpShardedWriter::finish`]). +pub(crate) struct SyncedBufFile { + inner: BufWriter, +} + +impl SyncedBufFile { + pub(crate) fn new(file: File) -> Self { + Self { + inner: BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file), + } + } +} + +impl Write for SyncedBufFile { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.inner.write(buf) + } + + fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { + self.inner.write_all(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.inner.flush()?; + self.inner.get_ref().sync_all() + } +} + +pub(crate) fn create_exclusive_shard_tmp_file_for_table( + out_dir: &Path, + table: &str, + shard_idx: usize, + run_id: &str, +) -> Result<(PathBuf, File), ShardPublishError> { + for attempt in 0..1024u32 { + let file_name = if attempt == 0 { + format!(".{table}.shard-{shard_idx:02}.{run_id}.tmp") + } else { + format!(".{table}.shard-{shard_idx:02}.{run_id}.{attempt}.tmp") + }; + let tmp_path = out_dir.join(file_name); + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path) + { + Ok(file) => return Ok((tmp_path, file)), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(ShardPublishError::Io { + path: tmp_path, + source, + }); + } + } + } + Err(ShardPublishError::Io { + path: out_dir.join(format!(".{table}.shard-{shard_idx:02}.{run_id}.tmp")), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique staging file names", + ), + }) +} + +pub(crate) fn publish_staged_shards_for_table( + out_dir: &Path, + table: &str, + staged: &mut [(PathBuf, StagingFileGuard)], + mut before_link: F, +) -> Result<(), ShardPublishError> +where + F: FnMut(usize, &Path), +{ + let mut published: Vec = Vec::with_capacity(staged.len()); + + for (shard_idx, (tmp_path, guard)) in staged.iter_mut().enumerate() { + let final_path = final_shard_path_for_table(out_dir, table, shard_idx); + before_link(shard_idx, &final_path); + + if let Err(source) = fs::hard_link(&tmp_path, &final_path) { + let cause = if source.kind() == io::ErrorKind::AlreadyExists { + ShardPublishError::OutputFileExists { path: final_path } + } else { + ShardPublishError::Io { + path: final_path, + source, + } + }; + let rollback_failures = rollback_published(&published); + if !rollback_failures.is_empty() { + return Err(ShardPublishError::RollbackFailed { + cause: Box::new(cause), + failures: rollback_failures, + }); + } + return Err(cause); + } + + published.push(PublishedPartition { + final_path, + backup_path: None, + }); + + if let Err(source) = fs::remove_file(&tmp_path) { + let cause = ShardPublishError::Io { + path: tmp_path.clone(), + source, + }; + let rollback_failures = rollback_published(&published); + if !rollback_failures.is_empty() { + return Err(ShardPublishError::RollbackFailed { + cause: Box::new(cause), + failures: rollback_failures, + }); + } + return Err(cause); + } + guard.disarm(); + } + + Ok(()) +} + +/// Private file-mode seam accepting injected readers, sink factory, and pre-link hook so tests can +/// exercise staging, writer failure, and post-preflight publication rollback through the exact +/// file publication path. +fn run_curate_bars_1m_to_dir_with_hooks( + args: &CurateBars1mArgs, + intraday: RI, + splits: RS, + mut make_sink: SF, + before_link: BL, +) -> Result +where + RI: io::Read, + RS: io::Read, + W: Write + Send, + SF: FnMut(usize, File) -> W, + BL: FnMut(usize, &Path), +{ + let start = Instant::now(); + validate_file_mode_args(args)?; + + let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?; + + fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateBars1mError::Io { + path: args.out_dir.clone(), + source, + })?; + + let run_id = next_run_id(); + let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count); + let mut sinks: Vec = Vec::with_capacity(args.shard_count); + for shard_idx in 0..args.shard_count { + let (tmp_path, file) = create_exclusive_shard_tmp_file_for_table( + &args.out_dir, + TABLE_BARS_1M, + shard_idx, + &run_id, + )?; + let guard = StagingFileGuard::new(tmp_path.clone()); + staged.push((tmp_path, guard)); + sinks.push(make_sink(shard_idx, file)); + } + + let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateBars1mError::Ilp)?; + let report = stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)?; + + publish_staged_shards_for_table(&args.out_dir, TABLE_BARS_1M, &mut staged, before_link)?; + Ok(report) +} + +/// Runs the bounded-memory file-to-file `bars_1m` curation pipeline, publishing exactly +/// `args.shard_count` QuestDB ILP v2 files (`/bars_1m.shard-.ilp`). +pub fn run_curate_bars_1m( + args: &CurateBars1mArgs, +) -> Result { + validate_file_mode_args(args)?; + + let splits_file = File::open(&args.splits_path).map_err(|source| { + RunCurateBars1mError::OpenInput { + label: "qm-splits", + path: args.splits_path.clone(), + source, + } + })?; + let intraday_file = File::open(&args.intraday_path).map_err(|source| { + RunCurateBars1mError::OpenInput { + label: "eod-intraday", + path: args.intraday_path.clone(), + source, + } + })?; + + run_curate_bars_1m_to_dir_with_hooks( + args, + intraday_file, + splits_file, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + +/// Formats [`CurateBars1mRunReport`] into a deterministic machine-readable `key=value` summary. +/// +/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). +pub fn format_curate_bars_1m_report(report: &CurateBars1mRunReport) -> String { + let per_shard = if report.ilp_stats.per_shard_rows.is_empty() { + "none".to_string() + } else { + report + .ilp_stats + .per_shard_rows + .iter() + .enumerate() + .map(|(idx, count)| format!("{idx:02}={count}")) + .collect::>() + .join(",") + }; + + let b = &report.curate_stats.builder; + let c = &report.curate_stats; + let d = &report.intraday_decode; + let sd = &report.splits_decode; + let sr = &report.split_rekey; + + format!( + "curate-etl curate-bars-1m\n\ + \x20 intraday_bson: docs_framed={} bytes_read={} docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\ + \x20 splits_bson: docs_framed={} bytes_read={} docs_in={} decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\ + \x20 splits: splits_in={} splits_applied={} splits_collision_collapsed={} splits_unmapped_qm={} splits_no_eod_partner={} splits_noop_dropped={} split_events_attached={}\n\ + \x20 chunking: chunks={} max_rows_per_chunk={} cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)\n\ + \x20 builder: bars_in={} rows_out={} keys_out_per_chunk_sum={} pre={} rth={} post={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_out_of_range={} dup_collapsed={} dup_conflict_dropped={}\n\ + \x20 curate: rows_in={} rows_out={} listings_out_per_chunk_sum={} pre={} rth={} post={} dropped_unmapped={} listing_collision_collapsed={} listing_collision_dropped={}\n\ + \x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\ + \x20 timing: elapsed_secs={:.6}", + report.intraday_docs_framed, + report.intraday_bytes_read, + d.docs_seen, + d.rows_decoded, + d.rejected_total(), + d.rejected_missing_field, + d.rejected_empty_field, + d.rejected_wrong_type, + d.rejected_invalid_timestamp, + d.rejected_invalid_number, + d.rejected_corrupt_document, + report.splits_docs_framed, + report.splits_bytes_read, + sd.docs_in, + sd.decoded, + sd.split_noop_ratio_one, + sd.rejected_total(), + sd.rejected_missing_field, + sd.rejected_empty_field, + sd.rejected_wrong_type, + sd.rejected_malformed_date, + sd.rejected_invalid_number, + sd.rejected_corrupt_document, + sr.splits_in, + sr.splits_applied, + sr.splits_collision_collapsed, + sr.splits_unmapped_qm, + sr.splits_no_eod_partner, + sr.splits_noop_dropped, + sr.split_events_attached, + report.chunks, + report.max_rows_per_chunk, + b.bars_in, + b.rows_out, + b.keys_out, + b.pre_rows_out, + b.rth_rows_out, + b.post_rows_out, + b.dropped_invalid_ohlc, + b.dropped_inconsistent_ohlc, + b.dropped_invalid_volume, + b.dropped_ts_out_of_range, + b.duplicate_collapsed, + b.duplicate_conflict_dropped, + c.rows_in, + c.rows_out, + c.listings_out, + c.pre_rows_out, + c.rth_rows_out, + c.post_rows_out, + c.dropped_unmapped, + c.listing_collision_collapsed, + c.listing_collision_dropped, + report.shard_count, + report.rows_written, + report.ilp_stats.rows, + report.ilp_stats.bytes, + report.ilp_stats.flushes, + report.elapsed_secs, + ) +} + +#[cfg(test)] +#[path = "run_curate_bars_1m_tests.rs"] +pub(crate) mod tests; diff --git a/tools/curate-etl/src/run_curate_bars_1m_tests.rs b/tools/curate-etl/src/run_curate_bars_1m_tests.rs new file mode 100644 index 00000000..6cf6c065 --- /dev/null +++ b/tools/curate-etl/src/run_curate_bars_1m_tests.rs @@ -0,0 +1,1998 @@ +use std::collections::BTreeMap; +use std::error::Error; +use std::fs; +use std::io::{self, Cursor, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use bson::raw::{cstr, RawDocumentBuf}; + +use super::*; +use crate::bars::Bar1dRow; +use crate::bars_1m::{ + Bar1mRow, IntradaySession, SessionCloseCutoffPolicy, BARS_1M_SOURCE_EOD, +}; +use crate::curate_bars_1m::check_curated_session_closes; +use crate::ilp::{shard_for_listing_id, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M}; +use crate::session_close::utc_micros_to_et_local; +use crate::shorts::et_to_utc_micros; +use crate::split::ymd_to_epoch_days; + +static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +pub(crate) struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + pub(crate) fn new(prefix: &str) -> Self { + let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-{prefix}-{}-{seq}", + std::process::id() + )); + fs::create_dir_all(&path).expect("create temp test dir"); + Self { path } + } + + pub(crate) fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn et_ts_sec(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { + let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp"); + assert_eq!(micros % 1_000_000, 0); + micros / 1_000_000 +} + +fn make_intraday_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_split_doc( + qm_search_code: &str, + ex_date: &str, + for_factor: f64, + to_factor: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), qm_search_code); + doc.append(cstr!("date"), ex_date); + doc.append(cstr!("forfactor"), for_factor); + doc.append(cstr!("tofactor"), to_factor); + doc.append(cstr!("splitratio"), for_factor / to_factor); + doc +} + +fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { + let mut out = Vec::new(); + for doc in docs { + out.extend_from_slice(doc.as_bytes()); + } + out +} + +fn write_mapping_tsv(dir: &Path, lines: &[&str]) -> PathBuf { + let path = dir.join("provider_mapping.tsv"); + let mut body = lines.join("\n"); + if !body.is_empty() { + body.push('\n'); + } + fs::write(&path, body).expect("write provider_mapping.tsv"); + path +} + +fn make_args( + mapping_path: PathBuf, + splits_path: PathBuf, + intraday_path: PathBuf, + out_dir: PathBuf, + shard_count: usize, + known_at_micros: i64, + stream_options: BsonStreamOptions, +) -> CurateBars1mArgs { + CurateBars1mArgs { + intraday_path, + splits_path, + provider_mapping_path: mapping_path, + out_dir, + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count, + known_at_micros, + stream_options, + ilp_options: IlpWriterOptions::default(), + } +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedIlpBar1m { + listing_id: i32, + session: IntradaySession, + source: String, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, + known_at: i64, + ts: i64, +} + +impl DecodedIlpBar1m { + fn to_bar_1m_row(&self) -> Bar1mRow { + let et = utc_micros_to_et_local(self.ts).expect("valid ET timestamp"); + Bar1mRow { + key: self.listing_id, + ts: self.ts, + session_date: et.session_date, + open: self.open, + high: self.high, + low: self.low, + close: self.close, + volume: self.volume, + session: self.session, + source: match self.source.as_str() { + BARS_1M_SOURCE_EOD => BARS_1M_SOURCE_EOD, + other => panic!("unexpected source '{other}'"), + }, + } + } + + fn sort_key(&self) -> (i32, i64, u64, u64, u64, u64, u64, i64) { + ( + self.listing_id, + self.ts, + self.open.to_bits(), + self.high.to_bits(), + self.low.to_bits(), + self.close.to_bits(), + self.volume.to_bits(), + self.known_at, + ) + } +} + +/// Decodes QuestDB ILP v2 `bars_1m` records respecting fixed-width 8-byte binary `DOUBLE` +/// payloads (`==\x10<8 LE bytes>`) so embedded `0x0a` bytes inside doubles never split rows. +fn decode_ilp_bars_1m(data: &[u8]) -> Vec { + let mut rows = Vec::new(); + let mut i = 0usize; + let len = data.len(); + + while i < len { + // 1. Tag set ends at unescaped space. + let tag_start = i; + while i < len { + match data[i] { + b'\\' => { + assert!(i + 1 < len, "dangling backslash in ILP tag set"); + i += 2; + } + b' ' => break, + _ => i += 1, + } + } + assert!(i < len && data[i] == b' ', "missing space after ILP tag set"); + let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("valid UTF-8 tag set"); + i += 1; + + let mut tags = tag_str.split(','); + assert_eq!(tags.next(), Some(TABLE_BARS_1M), "expected bars_1m table"); + let listing_tag = tags.next().expect("listing_id tag"); + let session_tag = tags.next().expect("session tag"); + let source_tag = tags.next().expect("source tag"); + assert!(tags.next().is_none(), "unexpected extra ILP tag"); + + let listing_id: i32 = listing_tag + .strip_prefix("listing_id=") + .expect("listing_id= prefix") + .parse() + .expect("i32 listing_id"); + let session = match session_tag + .strip_prefix("session=") + .expect("session= prefix") + { + "PRE" => IntradaySession::Pre, + "RTH" => IntradaySession::Rth, + "POST" => IntradaySession::Post, + other => panic!("unexpected session '{other}'"), + }; + let source = source_tag + .strip_prefix("source=") + .expect("source= prefix") + .to_string(); + + // 2. Fixed-width binary f64 fields: open, high, low, close, volume, then known_at=t. + let read_bin_f64 = |pos: &mut usize, name: &str| -> f64 { + let prefix = format!("{name}=="); + assert!( + data[*pos..].starts_with(prefix.as_bytes()), + "expected field prefix '{prefix}' at offset {}", + *pos + ); + *pos += prefix.len(); + assert_eq!( + data[*pos], ILP_V2_DOUBLE_TYPE, + "expected binary DOUBLE type tag for '{name}'" + ); + *pos += 1; + let bytes: [u8; 8] = data[*pos..*pos + 8] + .try_into() + .expect("8 bytes for binary double"); + *pos += 8; + f64::from_le_bytes(bytes) + }; + + let open = read_bin_f64(&mut i, "open"); + assert_eq!(data[i], b','); + i += 1; + let high = read_bin_f64(&mut i, "high"); + assert_eq!(data[i], b','); + i += 1; + let low = read_bin_f64(&mut i, "low"); + assert_eq!(data[i], b','); + i += 1; + let close = read_bin_f64(&mut i, "close"); + assert_eq!(data[i], b','); + i += 1; + let volume = read_bin_f64(&mut i, "volume"); + assert!( + data[i..].starts_with(b",known_at="), + "expected ,known_at= field" + ); + i += b",known_at=".len(); + + let known_start = i; + while i < len && data[i] != b' ' { + i += 1; + } + assert!(i < len && data[i] == b' ', "missing space after known_at"); + let known_str = std::str::from_utf8(&data[known_start..i]).expect("valid UTF-8 known_at"); + let known_at: i64 = known_str + .strip_suffix('t') + .expect("known_at trailing t") + .parse() + .expect("i64 known_at"); + i += 1; + + // 3. Designated timestamp `t\n`. + let ts_start = i; + while i < len && data[i] != b'\n' { + i += 1; + } + assert!(i < len && data[i] == b'\n', "missing trailing LF"); + let ts_str = std::str::from_utf8(&data[ts_start..i]).expect("valid UTF-8 ts"); + let ts: i64 = ts_str + .strip_suffix('t') + .expect("ts trailing t") + .parse() + .expect("i64 ts"); + i += 1; + + rows.push(DecodedIlpBar1m { + listing_id, + session, + source, + open, + high, + low, + close, + volume, + known_at, + ts, + }); + } + + rows +} + +fn assert_report_conservation(report: &CurateBars1mRunReport) { + assert_eq!( + report.intraday_docs_framed as usize, report.intraday_decode.docs_seen, + "docs_framed != docs_seen" + ); + assert_eq!( + report.intraday_decode.docs_seen, + report.intraday_decode.rows_decoded + report.intraday_decode.rejected_total(), + "decode conservation failed" + ); + let b = &report.curate_stats.builder; + assert_eq!( + report.intraday_decode.rows_decoded, b.bars_in, + "rows_decoded != builder.bars_in" + ); + assert_eq!( + b.bars_in, + b.rows_out + + b.dropped_invalid_ohlc + + b.dropped_inconsistent_ohlc + + b.dropped_invalid_volume + + b.dropped_ts_out_of_range + + b.duplicate_collapsed + + b.duplicate_conflict_dropped, + "builder conservation failed: {b:?}" + ); + assert_eq!( + b.pre_rows_out + b.rth_rows_out + b.post_rows_out, + b.rows_out, + "builder session breakdown failed" + ); + + let c = &report.curate_stats; + assert_eq!(c.rows_in, b.rows_out, "curate.rows_in != builder.rows_out"); + assert_eq!( + c.rows_in, + c.rows_out + + c.dropped_unmapped + + c.listing_collision_collapsed + + c.listing_collision_dropped, + "curate conservation failed: {c:?}" + ); + assert_eq!( + c.pre_rows_out + c.rth_rows_out + c.post_rows_out, + c.rows_out, + "curate session breakdown failed" + ); + + assert_eq!(report.rows_written, c.rows_out, "rows_written != rows_out"); + assert_eq!( + report.rows_written, report.ilp_stats.rows, + "rows_written != ilp_stats.rows" + ); + assert_eq!( + report.ilp_stats.per_shard_rows.iter().sum::(), + report.ilp_stats.rows, + "sum(per_shard_rows) != ilp_stats.rows" + ); + assert_eq!(report.ilp_stats.per_shard_rows.len(), report.shard_count); +} + +/// Split-boundary replay fixture (`run_curate_bars_1m_tests::split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`): +/// +/// SYNTHETIC fixture built from the figures in `REVIEW.md:88` and `design/DATA-CONTRACTS.md` §1 +/// (lines 13, 15, 25): +/// - `NVDA.US` (`listing_id=1001`, `eod: NVDA.US`, `qm: NVDA`, 10:1 forward split ex-date +/// `2024-06-10`, `forfactor=1, tofactor=10, splitratio=0.1`): +/// - `2024-06-07` (pre-split): adj 1m close `120.888`, adj vol `412_390.0` -> raw `1208.88`, +/// vol `41_239.0`; synthetic daily baseline `1208.88`. +/// - `2024-06-10` (ex-date): 1m close `121.79`, vol `350_000.0` (unchanged); synthetic daily +/// baseline `121.79`. +/// - `NEXM.V` (`listing_id=2002`, `eod: NEXM.V`, `qm: NEXM:CA`, 1:20 reverse split ex-date +/// `2025-06-20`, `forfactor=20, tofactor=1, splitratio=20.0`, aligned to `REVIEW.md:88`): +/// - `2025-06-18` (pre-split): adj 1m close `24.29`, adj vol `5_000.0` -> raw `1.2145`, +/// vol `100_000.0`; synthetic daily baseline `1.215` (~0.041% rel diff, matching `~1.21`). +/// - `2025-06-19` (intervening pre-split session): adj 1m close `24.40`, adj vol `4_000.0` -> +/// raw `1.22`, vol `80_000.0`; synthetic daily baseline `1.22`. +/// - `2025-06-20` (ex-date): 1m close `24.28` (`REVIEW.md:88` records `24.2799`), vol `12_500.0` +/// (unchanged); synthetic daily baseline `24.28`. +/// +/// Scope of this test: +/// - Proves split arithmetic, listing resolution, and ex-date boundary handling in the runner. +/// - Does NOT prove provider mapping, ex-date, or RTH close against retained `bars_1d` data. +/// - Open item: M2 exit criterion 3 observed-data split-boundary check (NEXM.V, NVDA.US vs +/// retained raw `bars_1d` closes) — open, owned by the live-host `bars_1m` load verification task. +#[test] +fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes() { + let dir = TempDirGuard::new("bars1m-split"); + let nvda_id = 1001; + let nexm_id = 2002; + let known_at_micros: i64 = 1_750_500_000_000_000; + + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + &format!("eod\tNVDA.US\t2020-01-01\t\t{nvda_id}"), + &format!("qm\tNVDA\t2020-01-01\t\t{nvda_id}"), + &format!("eod\tNEXM.V\t2020-01-01\t\t{nexm_id}"), + &format!("qm\tNEXM:CA\t2020-01-01\t\t{nexm_id}"), + ], + ); + + let splits_bytes = concat_docs(&[ + // NVDA 10:1 forward split on 2024-06-10 (QM: forfactor=1, tofactor=10, splitratio=0.1 -> ratio=10.0) + make_split_doc("NVDA", "2024-06-10", 1.0, 10.0), + // NEXM.V / NEXM:CA 1:20 reverse split on 2025-06-20 (QM: forfactor=20, tofactor=1, splitratio=20.0 -> ratio=0.05) + make_split_doc("NEXM:CA", "2025-06-20", 20.0, 1.0), + ]); + + let intraday_bytes = concat_docs(&[ + make_intraday_doc( + "NVDA.US", + et_ts_sec(2024, 6, 7, 15, 58), + 120.45, + 120.95, + 120.35, + 120.75, + 300_000.0, + ), + make_intraday_doc( + "NVDA.US", + et_ts_sec(2024, 6, 7, 15, 59), + 120.50, + 121.00, + 120.40, + 120.888, + 412_390.0, + ), + make_intraday_doc( + "NVDA.US", + et_ts_sec(2024, 6, 10, 15, 59), + 121.50, + 121.95, + 121.40, + 121.79, + 350_000.0, + ), + make_intraday_doc( + "NEXM.V", + et_ts_sec(2025, 6, 18, 9, 30), + 24.00, + 24.60, + 23.80, + 24.20, + 2_000.0, + ), + make_intraday_doc( + "NEXM.V", + et_ts_sec(2025, 6, 18, 15, 59), + 24.20, + 24.40, + 24.10, + 24.29, + 5_000.0, + ), + make_intraday_doc( + "NEXM.V", + et_ts_sec(2025, 6, 19, 15, 59), + 24.30, + 24.50, + 24.10, + 24.40, + 4_000.0, + ), + make_intraday_doc( + "NEXM.V", + et_ts_sec(2025, 6, 20, 15, 59), + 24.10, + 24.50, + 23.90, + 24.28, + 12_500.0, + ), + ]); + + let mut sink0 = Vec::new(); + let mut sink1 = Vec::new(); + let writer = + IlpShardedWriter::new(vec![&mut sink0, &mut sink1], IlpWriterOptions::default()).unwrap(); + + let args = make_args( + mapping_path.clone(), + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out"), + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report = run_curate_bars_1m_with_readers( + &args, + Cursor::new(&intraday_bytes), + Cursor::new(&splits_bytes), + writer, + ) + .expect("split-boundary run should succeed"); + + assert_report_conservation(&report); + assert_eq!(report.rows_written, 7); + assert_eq!(report.split_rekey.splits_applied, 2); + + let mut decoded = decode_ilp_bars_1m(&sink0); + decoded.extend(decode_ilp_bars_1m(&sink1)); + assert_eq!(decoded.len(), 7); + for row in &decoded { + assert_eq!(row.known_at, known_at_micros); + assert_eq!(row.source, BARS_1M_SOURCE_EOD); + } + + // Verify inverse volume scaling on pre-split bars (including intervening session 2025-06-19) + // and unchanged OHLCV on ex-date bars. + let find_row = |id: i32, ts_sec: i64| -> &DecodedIlpBar1m { + decoded + .iter() + .find(|r| r.listing_id == id && r.ts == ts_sec * 1_000_000) + .expect("expected row") + }; + + let nvda_pre = find_row(nvda_id, et_ts_sec(2024, 6, 7, 15, 59)); + assert!((nvda_pre.close - 1208.88).abs() < 1e-9); + assert!((nvda_pre.volume - 41_239.0).abs() < 1e-9); + + let nvda_ex = find_row(nvda_id, et_ts_sec(2024, 6, 10, 15, 59)); + assert_eq!(nvda_ex.open.to_bits(), 121.50_f64.to_bits()); + assert_eq!(nvda_ex.high.to_bits(), 121.95_f64.to_bits()); + assert_eq!(nvda_ex.low.to_bits(), 121.40_f64.to_bits()); + assert_eq!(nvda_ex.close.to_bits(), 121.79_f64.to_bits()); + assert_eq!(nvda_ex.volume.to_bits(), 350_000.0_f64.to_bits()); + + let nexm_pre_18 = find_row(nexm_id, et_ts_sec(2025, 6, 18, 15, 59)); + assert!((nexm_pre_18.close - 1.2145).abs() < 1e-9); + assert!((nexm_pre_18.volume - 100_000.0).abs() < 1e-9); + + let nexm_pre_19 = find_row(nexm_id, et_ts_sec(2025, 6, 19, 15, 59)); + assert!((nexm_pre_19.open - 1.215).abs() < 1e-9); + assert!((nexm_pre_19.high - 1.225).abs() < 1e-9); + assert!((nexm_pre_19.low - 1.205).abs() < 1e-9); + assert!((nexm_pre_19.close - 1.22).abs() < 1e-9); + assert!((nexm_pre_19.volume - 80_000.0).abs() < 1e-9); + + let nexm_ex = find_row(nexm_id, et_ts_sec(2025, 6, 20, 15, 59)); + assert_eq!(nexm_ex.open.to_bits(), 24.10_f64.to_bits()); + assert_eq!(nexm_ex.high.to_bits(), 24.50_f64.to_bits()); + assert_eq!(nexm_ex.low.to_bits(), 23.90_f64.to_bits()); + assert_eq!(nexm_ex.close.to_bits(), 24.28_f64.to_bits()); + assert_eq!(nexm_ex.volume.to_bits(), 12_500.0_f64.to_bits()); + + // Check all five synthetic RTH session closes against synthetic daily baselines within 0.5%. + let mut rows_1m: Vec> = decoded.iter().map(DecodedIlpBar1m::to_bar_1m_row).collect(); + rows_1m.sort_by_key(|r| (r.key, r.ts)); + + let bars_1d = vec![ + Bar1dRow { + key: nvda_id, + session_date: day(2024, 6, 7), + open: 1197.7, + high: 1216.92, + low: 1180.22, + close: 1208.88, + volume: 41_239_000.0, + }, + Bar1dRow { + key: nvda_id, + session_date: day(2024, 6, 10), + open: 120.37, + high: 123.10, + low: 117.01, + close: 121.79, + volume: 314_162_700.0, + }, + Bar1dRow { + key: nexm_id, + session_date: day(2025, 6, 18), + open: 1.20, + high: 1.23, + low: 1.19, + close: 1.215, // ~0.041% rel diff vs 1.2145 (REVIEW.md:88 / DATA-CONTRACTS.md §1: ~1.21 raw) + volume: 100_000.0, + }, + Bar1dRow { + key: nexm_id, + session_date: day(2025, 6, 19), + open: 1.215, + high: 1.225, + low: 1.205, + close: 1.22, + volume: 80_000.0, + }, + Bar1dRow { + key: nexm_id, + session_date: day(2025, 6, 20), + open: 24.10, + high: 24.50, + low: 23.90, + close: 24.28, + volume: 12_500.0, + }, + ]; + + let check = check_curated_session_closes( + &rows_1m, + &bars_1d, + &SessionCloseCutoffPolicy::standard_rth(), + 0.005, + ) + .expect("session close check should succeed"); + assert_eq!(check.stats.checked, 5); + assert_eq!(check.stats.within_tolerance, 5); + assert_eq!(check.stats.mismatched, 0); + assert!(check.stats.max_rel_diff < 0.005); + + // Negative control: omitting qmSplits leaves pre-split bars retroactively adjusted and fails + // the 0.5% check on all three pre-split sessions (NVDA 2024-06-07, NEXM 2025-06-18, and + // intervening NEXM 2025-06-19). + let mut neg_sink = Vec::new(); + let neg_writer = + IlpShardedWriter::new(vec![&mut neg_sink], IlpWriterOptions::default()).unwrap(); + let neg_args = make_args( + mapping_path, + dir.path().join("empty_splits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out-neg"), + 1, + known_at_micros, + BsonStreamOptions::default(), + ); + let _ = run_curate_bars_1m_with_readers( + &neg_args, + Cursor::new(&intraday_bytes), + Cursor::new(Vec::::new()), + neg_writer, + ) + .expect("negative-control run should succeed"); + let mut neg_rows: Vec> = decode_ilp_bars_1m(&neg_sink) + .iter() + .map(DecodedIlpBar1m::to_bar_1m_row) + .collect(); + neg_rows.sort_by_key(|r| (r.key, r.ts)); + let neg_check = check_curated_session_closes( + &neg_rows, + &bars_1d, + &SessionCloseCutoffPolicy::standard_rth(), + 0.005, + ) + .expect("negative-control close check should succeed"); + assert_eq!(neg_check.stats.checked, 5); + assert_eq!(neg_check.stats.within_tolerance, 2); + assert_eq!(neg_check.stats.mismatched, 3); +} + +#[test] +fn reused_ticker_does_not_leak_later_listing_split_to_earlier_listing() { + let dir = TempDirGuard::new("bars1m-reused-ticker"); + let known_at_micros: i64 = 1_750_550_000_000_000; + + // Same non-overlapping FB.US reuse layout as the daily runner fixture: + // listing 10 through 2022-06-08, gap, listing 20 starting 2025-01-01. + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "eod\tFB.US\t2012-01-01\t2022-06-08\t10", + "qm\tFB:US\t2012-01-01\t2022-06-08\t10", + "eod\tFB.US\t2025-01-01\t\t20", + "qm\tFBETF:US\t2025-01-01\t\t20", + ], + ); + + // 2:1 forward split belonging strictly to listing 20 (ex-date 2025-06-02). + let splits_bytes = concat_docs(&[make_split_doc("FBETF:US", "2025-06-02", 1.0, 2.0)]); + + let ts_old = et_ts_sec(2022, 6, 8, 15, 59); + let ts_new_pre = et_ts_sec(2025, 5, 30, 15, 59); + let ts_new_ex = et_ts_sec(2025, 6, 2, 15, 59); + + let intraday_bytes = concat_docs(&[ + // Listing 10 bar in 2022: must NOT receive listing 20's 2025 2:1 split. + make_intraday_doc("FB.US", ts_old, 190.0, 195.0, 188.0, 192.0, 1_000.0), + // Listing 20 pre-split bar in May 2025: MUST be un-adjusted by 2:1 (price * 2, vol / 2). + make_intraday_doc("FB.US", ts_new_pre, 25.0, 26.0, 24.5, 25.5, 5_000.0), + // Listing 20 ex-date bar on 2025-06-02: MUST remain unchanged. + make_intraday_doc("FB.US", ts_new_ex, 25.5, 26.5, 25.0, 26.0, 4_000.0), + ]); + + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let args = make_args( + mapping_path, + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out"), + 1, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report = run_curate_bars_1m_with_readers( + &args, + Cursor::new(&intraday_bytes), + Cursor::new(&splits_bytes), + writer, + ) + .expect("reused-ticker run should succeed"); + + assert_report_conservation(&report); + assert_eq!(report.rows_written, 3); + assert_eq!(report.split_rekey.splits_applied, 1); + + let rows = decode_ilp_bars_1m(&sink); + assert_eq!(rows.len(), 3); + + // Listing 10 (2022): bitwise unchanged — no split leakage from listing 20. + let old_row = rows + .iter() + .find(|r| r.listing_id == 10 && r.ts == ts_old * 1_000_000) + .expect("listing 10 row"); + assert_eq!(old_row.open.to_bits(), 190.0_f64.to_bits()); + assert_eq!(old_row.high.to_bits(), 195.0_f64.to_bits()); + assert_eq!(old_row.low.to_bits(), 188.0_f64.to_bits()); + assert_eq!(old_row.close.to_bits(), 192.0_f64.to_bits()); + assert_eq!(old_row.volume.to_bits(), 1_000.0_f64.to_bits()); + + // Listing 20 (2025-05-30 pre-split): un-adjusted by 2:1. + let new_pre = rows + .iter() + .find(|r| r.listing_id == 20 && r.ts == ts_new_pre * 1_000_000) + .expect("listing 20 pre-split row"); + assert!((new_pre.open - 50.0).abs() < 1e-9); + assert!((new_pre.high - 52.0).abs() < 1e-9); + assert!((new_pre.low - 49.0).abs() < 1e-9); + assert!((new_pre.close - 51.0).abs() < 1e-9); + assert!((new_pre.volume - 2_500.0).abs() < 1e-9); + + // Listing 20 (2025-06-02 ex-date): bitwise unchanged. + let new_ex = rows + .iter() + .find(|r| r.listing_id == 20 && r.ts == ts_new_ex * 1_000_000) + .expect("listing 20 ex-date row"); + assert_eq!(new_ex.open.to_bits(), 25.5_f64.to_bits()); + assert_eq!(new_ex.high.to_bits(), 26.5_f64.to_bits()); + assert_eq!(new_ex.low.to_bits(), 25.0_f64.to_bits()); + assert_eq!(new_ex.close.to_bits(), 26.0_f64.to_bits()); + assert_eq!(new_ex.volume.to_bits(), 4_000.0_f64.to_bits()); +} + +#[test] +fn chunking_equivalence_and_bounded_memory_across_small_and_large_chunks() { + let dir = TempDirGuard::new("bars1m-chunk-eq"); + let known_at_micros: i64 = 1_750_600_000_000_000; + + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "eod\tAAA.US\t2020-01-01\t\t101", + "eod\tBBB.US\t2020-01-01\t\t102", + "eod\tCCC.US\t2020-01-01\t\t103", + "eod\tDDD.US\t2020-01-01\t\t104", + ], + ); + + let mut docs = Vec::new(); + let codes = ["AAA.US", "BBB.US", "CCC.US", "DDD.US", "UNMAPPED.US"]; + for idx in 0..15i64 { + let code = codes[(idx as usize) % codes.len()]; + let ts = et_ts_sec(2025, 3, 10, 10, (idx % 60) as u8); + let px = 10.0 + idx as f64; + let doc = make_intraday_doc( + code, + ts, + px, + px + 0.5, + px - 0.5, + px + 0.25, + 100.0 + idx as f64, + ); + docs.push(doc); + } + + let min_doc_bytes = docs.iter().map(|d| d.as_bytes().len()).min().unwrap(); + let max_doc_bytes_in_fixture = docs.iter().map(|d| d.as_bytes().len()).max().unwrap(); + let intraday_bytes = concat_docs(&docs); + let splits_bytes: Vec = Vec::new(); + + // Small chunk capacity: holds at most 2 documents per chunk, forcing >= 3 chunks. + let small_cap = min_doc_bytes * 2 + 16; + let small_opts = BsonStreamOptions { + chunk_capacity_bytes: small_cap, + max_doc_bytes: max_doc_bytes_in_fixture + 64, + }; + let large_opts = BsonStreamOptions { + chunk_capacity_bytes: intraday_bytes.len() + 1024, + max_doc_bytes: intraday_bytes.len() + 1024, + }; + + let run_with = |opts: BsonStreamOptions| -> (CurateBars1mRunReport, Vec>) { + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let mut s2 = Vec::new(); + let writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1, &mut s2], + IlpWriterOptions::default(), + ) + .unwrap(); + let args = make_args( + mapping_path.clone(), + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out"), + 3, + known_at_micros, + opts, + ); + let report = run_curate_bars_1m_with_readers( + &args, + Cursor::new(&intraday_bytes), + Cursor::new(&splits_bytes), + writer, + ) + .expect("run should succeed"); + assert_report_conservation(&report); + let mut per_shard = vec![ + decode_ilp_bars_1m(&s0), + decode_ilp_bars_1m(&s1), + decode_ilp_bars_1m(&s2), + ]; + for shard_rows in &mut per_shard { + shard_rows.sort_by_key(DecodedIlpBar1m::sort_key); + } + (report, per_shard) + }; + + let (small_report, small_shards) = run_with(small_opts); + let (large_report, large_shards) = run_with(large_opts); + + assert_eq!(large_report.chunks, 1); + assert!( + small_report.chunks >= 3, + "expected >= 3 chunks, got {}", + small_report.chunks + ); + // Bounded-memory invariant: max rows per chunk <= small_cap / min_doc_bytes and < total decoded. + assert!( + small_report.max_rows_per_chunk <= small_cap / min_doc_bytes, + "max_rows_per_chunk={} exceeded bound {}", + small_report.max_rows_per_chunk, + small_cap / min_doc_bytes + ); + assert!(small_report.max_rows_per_chunk < small_report.intraday_decode.rows_decoded); + + // Equivalence on duplicate-free fixture. + assert_eq!(small_report.rows_written, large_report.rows_written); + assert_eq!( + small_report.curate_stats.dropped_unmapped, + large_report.curate_stats.dropped_unmapped + ); + assert_eq!(small_report.curate_stats.dropped_unmapped, 3); + assert_eq!(small_report.rows_written, 12); + assert_eq!(small_shards, large_shards); + + // Also exercise an oversized single document (> chunk_capacity_bytes, <= max_doc_bytes). + let mut big_doc = make_intraday_doc( + "AAA.US", + et_ts_sec(2025, 3, 10, 11, 0), + 25.0, + 25.5, + 24.5, + 25.25, + 900.0, + ); + let pad = "x".repeat(small_cap + 256); + big_doc.append(cstr!("_note"), pad.as_str()); + let big_doc_len = big_doc.as_bytes().len(); + assert!(big_doc_len > small_cap); + let big_bytes = concat_docs(&[big_doc]); + + let mut big_sink = Vec::new(); + let big_writer = IlpShardedWriter::new(vec![&mut big_sink], IlpWriterOptions::default()).unwrap(); + let big_args = make_args( + mapping_path, + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out-big"), + 1, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: small_cap, + max_doc_bytes: big_doc_len + 64, + }, + ); + let big_report = run_curate_bars_1m_with_readers( + &big_args, + Cursor::new(&big_bytes), + Cursor::new(&splits_bytes), + big_writer, + ) + .expect("oversized single document within max_doc_bytes should succeed"); + assert_report_conservation(&big_report); + assert_eq!(big_report.chunks, 1); + assert_eq!(big_report.rows_written, 1); +} + +#[test] +fn cross_chunk_duplicate_is_emitted_twice_and_reported() { + let dir = TempDirGuard::new("bars1m-cross-chunk-dup"); + let known_at_micros: i64 = 1_750_700_000_000_000; + let mapping_path = write_mapping_tsv(dir.path(), &["eod\tDUP.US\t2020-01-01\t\t505"]); + + let ts = et_ts_sec(2025, 4, 15, 11, 0); + let doc1 = make_intraday_doc("DUP.US", ts, 50.0, 51.0, 49.0, 50.5, 1_000.0); + let doc2 = make_intraday_doc("DUP.US", ts, 50.0, 51.0, 49.0, 50.5, 1_000.0); + let doc_len = doc1.as_bytes().len(); + let intraday_bytes = concat_docs(&[doc1, doc2]); + + // Capacity fits exactly 1 doc per chunk so doc1 and doc2 land in separate chunks. + let stream_opts = BsonStreamOptions { + chunk_capacity_bytes: doc_len, + max_doc_bytes: doc_len + 64, + }; + + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let args = make_args( + mapping_path, + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out"), + 1, + known_at_micros, + stream_opts, + ); + + let report = run_curate_bars_1m_with_readers( + &args, + Cursor::new(&intraday_bytes), + Cursor::new(Vec::::new()), + writer, + ) + .expect("cross-chunk duplicate run should succeed"); + + assert_report_conservation(&report); + assert_eq!(report.chunks, 2); + assert_eq!(report.max_rows_per_chunk, 1); + assert_eq!(report.curate_stats.builder.duplicate_collapsed, 0); + assert_eq!(report.curate_stats.listing_collision_collapsed, 0); + assert_eq!(report.curate_stats.listings_out, 2); + assert_eq!(report.curate_stats.builder.keys_out, 2); + assert_eq!(report.rows_written, 2); + + let rows = decode_ilp_bars_1m(&sink); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0], rows[1]); + assert_eq!(rows[0].listing_id, 505); + assert_eq!(rows[0].ts, ts * 1_000_000); + + let formatted = format_curate_bars_1m_report(&report); + assert!(formatted.contains("cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)")); + assert!(formatted.contains("listings_out_per_chunk_sum=2")); + assert!(formatted.contains("keys_out_per_chunk_sum=2")); +} + +#[test] +fn stats_conservation_with_within_chunk_collisions_and_malformed_docs() { + let dir = TempDirGuard::new("bars1m-conservation"); + let known_at_micros: i64 = 1_750_800_000_000_000; + + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "eod\tA1.US\t2020-01-01\t\t701", + "eod\tA2.US\t2020-01-01\t\t701", + "eod\tB.US\t2020-01-01\t\t702", + ], + ); + + let ts_pre = et_ts_sec(2025, 5, 1, 8, 15); + let ts_rth = et_ts_sec(2025, 5, 1, 10, 30); + let ts_post = et_ts_sec(2025, 5, 1, 16, 45); + let ts_conflict = et_ts_sec(2025, 5, 1, 11, 0); + + // Malformed document: missing `close` field. + let mut bad_missing = RawDocumentBuf::new(); + bad_missing.append(cstr!("eodSearchCode"), "B.US"); + bad_missing.append(cstr!("timestamp"), ts_rth); + bad_missing.append(cstr!("open"), 10.0); + bad_missing.append(cstr!("high"), 11.0); + bad_missing.append(cstr!("low"), 9.0); + bad_missing.append(cstr!("volume"), 100.0); + + // Malformed document: negative timestamp. + let bad_ts = make_intraday_doc("B.US", -10, 10.0, 11.0, 9.0, 10.5, 100.0); + + let docs = vec![ + // PRE bar on B.US + make_intraday_doc("B.US", ts_pre, 20.0, 20.5, 19.8, 20.2, 500.0), + // POST bar on B.US + make_intraday_doc("B.US", ts_post, 21.0, 21.2, 20.9, 21.1, 300.0), + // Identical cross-source_id alias collision on listing 701 at ts_rth -> collapses to 1 + make_intraday_doc("A1.US", ts_rth, 10.0, 10.5, 9.9, 10.2, 1_000.0), + make_intraday_doc("A2.US", ts_rth, 10.0, 10.5, 9.9, 10.2, 1_000.0), + // Conflicting cross-source_id alias collision on listing 701 at ts_conflict -> drops both (2) + make_intraday_doc("A1.US", ts_conflict, 10.0, 10.5, 9.9, 10.2, 1_000.0), + make_intraday_doc("A2.US", ts_conflict, 10.0, 10.5, 9.9, 10.4, 1_000.0), + // Unmapped code -> dropped_unmapped = 1 + make_intraday_doc("GHOST.US", ts_rth, 5.0, 5.2, 4.9, 5.1, 50.0), + // Malformed docs -> counted in intraday_decode.rejected_total() = 2 + bad_missing, + bad_ts, + ]; + let intraday_bytes = concat_docs(&docs); + + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let args = make_args( + mapping_path, + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out"), + 1, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report = run_curate_bars_1m_with_readers( + &args, + Cursor::new(&intraday_bytes), + Cursor::new(Vec::::new()), + writer, + ) + .expect("conservation test run should succeed"); + + assert_report_conservation(&report); + assert_eq!(report.intraday_docs_framed, 9); + assert_eq!(report.intraday_decode.rows_decoded, 7); + assert_eq!(report.intraday_decode.rejected_total(), 2); + assert_eq!(report.intraday_decode.rejected_missing_field, 1); + assert_eq!(report.intraday_decode.rejected_invalid_timestamp, 1); + + assert_eq!(report.curate_stats.rows_in, 7); + assert_eq!(report.curate_stats.rows_out, 3); + assert_eq!(report.curate_stats.pre_rows_out, 1); + assert_eq!(report.curate_stats.rth_rows_out, 1); + assert_eq!(report.curate_stats.post_rows_out, 1); + assert_eq!(report.curate_stats.dropped_unmapped, 1); + assert_eq!(report.curate_stats.listing_collision_collapsed, 1); + assert_eq!(report.curate_stats.listing_collision_dropped, 2); +} + +struct FailingWriteSink { + fail_on_write: bool, + fail_on_flush: bool, +} + +impl Write for FailingWriteSink { + fn write(&mut self, buf: &[u8]) -> io::Result { + if self.fail_on_write { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected write failure")) + } else { + Ok(buf.len()) + } + } + + fn flush(&mut self) -> io::Result<()> { + if self.fail_on_flush { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected flush failure")) + } else { + Ok(()) + } + } +} + +struct FailingReader; + +impl io::Read for FailingReader { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + Err(io::Error::new(io::ErrorKind::UnexpectedEof, "injected read I/O failure")) + } +} + +fn list_dir_names(dir: &Path) -> Vec { + if !dir.exists() { + return Vec::new(); + } + let mut names: Vec = fs::read_dir(dir) + .expect("read_dir") + .map(|entry| { + entry + .expect("dir entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .collect(); + names.sort(); + names +} + +#[test] +fn fail_closed_validation_and_stream_and_writer_errors() { + let dir = TempDirGuard::new("bars1m-fail-closed"); + let mapping_path = write_mapping_tsv(dir.path(), &["eod\tAAA.US\t2020-01-01\t\t101"]); + let ts = et_ts_sec(2025, 5, 2, 10, 0); + let doc1 = make_intraday_doc("AAA.US", ts, 10.0, 11.0, 9.0, 10.5, 100.0); + let doc2 = make_intraday_doc("AAA.US", ts + 60, 10.5, 11.5, 10.0, 11.0, 200.0); + + // 1. Blank mapping_source + { + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let mut args = make_args( + mapping_path.clone(), + dir.path().join("splits.bson"), + dir.path().join("intraday.bson"), + dir.path().join("out-blank"), + 1, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + args.mapping_source = " ".to_string(); + let err = run_curate_bars_1m_with_readers( + &args, + Cursor::new(Vec::::new()), + Cursor::new(Vec::::new()), + writer, + ) + .unwrap_err(); + assert!(matches!(err, RunCurateBars1mError::EmptyMappingSource)); + } + + // 2. Unsupported mapping_source + { + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let mut args = make_args( + mapping_path.clone(), + dir.path().join("splits.bson"), + dir.path().join("intraday.bson"), + dir.path().join("out-unsup"), + 1, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + args.mapping_source = "qm".to_string(); + let err = run_curate_bars_1m_with_readers( + &args, + Cursor::new(Vec::::new()), + Cursor::new(Vec::::new()), + writer, + ) + .unwrap_err(); + assert!(matches!( + err, + RunCurateBars1mError::UnsupportedMappingSource { ref mapping_source } if mapping_source == "qm" + )); + } + + // 3. Zero shard_count + { + let args = make_args( + mapping_path.clone(), + dir.path().join("splits.bson"), + dir.path().join("intraday.bson"), + dir.path().join("out-zero"), + 0, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + let err = run_curate_bars_1m(&args).unwrap_err(); + assert!(matches!(err, RunCurateBars1mError::ZeroShardCount)); + assert!(!args.out_dir.exists()); + } + + // 4. Writer shard count mismatch + { + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let args = make_args( + mapping_path.clone(), + dir.path().join("splits.bson"), + dir.path().join("intraday.bson"), + dir.path().join("out-mismatch"), + 2, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + let err = run_curate_bars_1m_with_readers( + &args, + Cursor::new(Vec::::new()), + Cursor::new(Vec::::new()), + writer, + ) + .unwrap_err(); + assert!(matches!( + err, + RunCurateBars1mError::ShardCountMismatch { expected: 2, actual: 1 } + )); + } + + // 5. Missing input file + { + let args = make_args( + mapping_path.clone(), + dir.path().join("does-not-exist-splits.bson"), + dir.path().join("does-not-exist-intraday.bson"), + dir.path().join("out-missing"), + 1, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + let err = run_curate_bars_1m(&args).unwrap_err(); + assert!(matches!(err, RunCurateBars1mError::OpenInput { label: "qm-splits", .. })); + assert!(err.source().is_some()); + assert!(!args.out_dir.exists()); + } + + // 6. Truncated BSON tail after a successful first chunk -> BsonStream, no published files + { + let mut truncated = concat_docs(&[doc1.clone()]); + let partial = &doc2.as_bytes()[..doc2.as_bytes().len() - 5]; + truncated.extend_from_slice(partial); + + let splits_file = dir.path().join("empty_splits.bson"); + fs::write(&splits_file, []).unwrap(); + let intraday_file = dir.path().join("truncated_intraday.bson"); + fs::write(&intraday_file, &truncated).unwrap(); + let out_dir = dir.path().join("out-trunc"); + + let args = make_args( + mapping_path.clone(), + splits_file, + intraday_file, + out_dir.clone(), + 2, + 1_750_000_000_000_000, + BsonStreamOptions { + chunk_capacity_bytes: doc1.as_bytes().len(), + max_doc_bytes: doc1.as_bytes().len() + 64, + }, + ); + let err = run_curate_bars_1m(&args).unwrap_err(); + assert!(matches!(err, RunCurateBars1mError::BsonStream { label: "eod-intraday", .. })); + assert!(err.source().is_some()); + assert!(list_dir_names(&out_dir).is_empty(), "no final or staging files should remain"); + } + + // 7. Fatal read I/O error -> BsonStream, no published files + { + let out_dir = dir.path().join("out-io-read"); + let args = make_args( + mapping_path.clone(), + dir.path().join("splits.bson"), + dir.path().join("intraday.bson"), + out_dir.clone(), + 2, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + let err = run_curate_bars_1m_to_dir_with_hooks( + &args, + FailingReader, + Cursor::new(Vec::::new()), + |_idx, file| SyncedBufFile::new(file), + |_idx, _path| {}, + ) + .unwrap_err(); + assert!(matches!(err, RunCurateBars1mError::BsonStream { label: "eod-intraday", .. })); + assert!(err.source().is_some()); + assert!(list_dir_names(&out_dir).is_empty()); + } + + // 8. Failing sink on write -> CurateWrite(Ilp), no published files + { + let out_dir = dir.path().join("out-write-fail"); + let mut args = make_args( + mapping_path.clone(), + dir.path().join("splits.bson"), + dir.path().join("intraday.bson"), + out_dir.clone(), + 1, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + args.ilp_options.max_batch_rows = 1; + let err = run_curate_bars_1m_to_dir_with_hooks( + &args, + Cursor::new(concat_docs(&[doc1.clone()])), + Cursor::new(Vec::::new()), + |_idx, _file| FailingWriteSink { + fail_on_write: true, + fail_on_flush: false, + }, + |_idx, _path| {}, + ) + .unwrap_err(); + assert!(matches!( + err, + RunCurateBars1mError::CurateWrite(CurateBars1mWriteError::Ilp(IlpWriterError::Io { .. })) + )); + assert!(err.source().is_some()); + assert!(list_dir_names(&out_dir).is_empty()); + } + + // 9. Failing sink on finish flush -> Ilp(Io), no published files + { + let out_dir = dir.path().join("out-flush-fail"); + let args = make_args( + mapping_path.clone(), + dir.path().join("splits.bson"), + dir.path().join("intraday.bson"), + out_dir.clone(), + 1, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + let err = run_curate_bars_1m_to_dir_with_hooks( + &args, + Cursor::new(concat_docs(&[doc1.clone()])), + Cursor::new(Vec::::new()), + |_idx, _file| FailingWriteSink { + fail_on_write: false, + fail_on_flush: true, + }, + |_idx, _path| {}, + ) + .unwrap_err(); + assert!(matches!( + err, + RunCurateBars1mError::Ilp(IlpWriterError::Io { .. }) + )); + assert!(err.source().is_some()); + assert!(list_dir_names(&out_dir).is_empty()); + } +} + +#[test] +fn fail_closed_preexisting_and_post_preflight_rollback() { + let dir = TempDirGuard::new("bars1m-no-overwrite"); + let mapping_path = write_mapping_tsv(dir.path(), &["eod\tAAA.US\t2020-01-01\t\t101"]); + let ts = et_ts_sec(2025, 5, 2, 10, 0); + let intraday_bytes = concat_docs(&[make_intraday_doc("AAA.US", ts, 10.0, 11.0, 9.0, 10.5, 100.0)]); + let splits_file = dir.path().join("splits.bson"); + let intraday_file = dir.path().join("intraday.bson"); + fs::write(&splits_file, []).unwrap(); + fs::write(&intraday_file, &intraday_bytes).unwrap(); + + // Case A: pre-existing final shard file detected at preflight. + let out_preexisting = dir.path().join("out-preexisting"); + fs::create_dir_all(&out_preexisting).unwrap(); + let sentinel = b"existing-shard-bytes-must-not-change"; + let existing_path = out_preexisting.join("bars_1m.shard-01.ilp"); + fs::write(&existing_path, sentinel).unwrap(); + + let args_a = make_args( + mapping_path.clone(), + splits_file.clone(), + intraday_file.clone(), + out_preexisting.clone(), + 3, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + let err_a = run_curate_bars_1m(&args_a).unwrap_err(); + assert!(matches!( + err_a, + RunCurateBars1mError::OutputFileExists { ref path } if path == &existing_path + )); + assert_eq!(fs::read(&existing_path).unwrap(), sentinel); + assert_eq!(list_dir_names(&out_preexisting), vec!["bars_1m.shard-01.ilp"]); + + // Case B: destination appears AFTER preflight on shard 1 (after shard 0 has been linked). + // Shard 0 must be rolled back, shard 1's external file must remain intact, and no .tmp survives. + let out_race = dir.path().join("out-race"); + let args_b = make_args( + mapping_path, + splits_file, + intraday_file, + out_race.clone(), + 3, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + let race_sentinel = b"concurrent-writer-shard-01"; + let err_b = run_curate_bars_1m_to_dir_with_hooks( + &args_b, + Cursor::new(&intraday_bytes), + Cursor::new(Vec::::new()), + |_idx, file| SyncedBufFile::new(file), + |shard_idx, final_path| { + if shard_idx == 1 { + fs::write(final_path, race_sentinel).expect("inject concurrent final shard"); + } + }, + ) + .unwrap_err(); + let expected_race_path = out_race.join("bars_1m.shard-01.ilp"); + assert!(matches!( + err_b, + RunCurateBars1mError::OutputFileExists { ref path } if path == &expected_race_path + )); + assert_eq!(fs::read(&expected_race_path).unwrap(), race_sentinel); + assert_eq!(list_dir_names(&out_race), vec!["bars_1m.shard-01.ilp"]); + + // Case C: stale final shard OUTSIDE the requested shard_count range (e.g. bars_1m.shard-03.ilp + // left over from a prior 4-shard export when retrying with shard_count = 2). Preflight must + // reject it, preserve its bytes, and create no new files. + let out_stale = dir.path().join("out-stale-shard"); + fs::create_dir_all(&out_stale).unwrap(); + let stale_sentinel = b"stale-shard-03-from-prior-four-shard-export"; + let stale_path = out_stale.join("bars_1m.shard-03.ilp"); + fs::write(&stale_path, stale_sentinel).unwrap(); + + let args_c = make_args( + dir.path().join("provider_mapping.tsv"), + dir.path().join("splits.bson"), + dir.path().join("intraday.bson"), + out_stale.clone(), + 2, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + let err_c = run_curate_bars_1m(&args_c).unwrap_err(); + assert!(matches!( + err_c, + RunCurateBars1mError::OutputFileExists { ref path } if path == &stale_path + )); + assert_eq!(fs::read(&stale_path).unwrap(), stale_sentinel); + assert_eq!(list_dir_names(&out_stale), vec!["bars_1m.shard-03.ilp"]); +} + +#[test] +fn file_mode_publishes_exact_zero_padded_shards_including_empty_shards() { + let dir = TempDirGuard::new("bars1m-file-mode"); + let known_at_micros: i64 = 1_750_900_000_000_000; + let shard_count = 4usize; + + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "eod\tAAA.US\t2020-01-01\t\t1001", + "eod\tBBB.US\t2020-01-01\t\t2002", + ], + ); + let splits_file = dir.path().join("qmSplits.bson"); + fs::write(&splits_file, []).unwrap(); + + let intraday_bytes = concat_docs(&[ + make_intraday_doc("AAA.US", et_ts_sec(2025, 5, 5, 9, 30), 10.0, 10.5, 9.9, 10.2, 100.0), + make_intraday_doc("AAA.US", et_ts_sec(2025, 5, 5, 9, 31), 10.2, 10.6, 10.1, 10.4, 150.0), + make_intraday_doc("BBB.US", et_ts_sec(2025, 5, 5, 9, 30), 25.0, 25.4, 24.8, 25.1, 500.0), + ]); + let intraday_file = dir.path().join("eodIntraday1M.bson"); + fs::write(&intraday_file, &intraday_bytes).unwrap(); + + let out_dir = dir.path().join("shards_out"); + let args = make_args( + mapping_path, + splits_file, + intraday_file, + out_dir.clone(), + shard_count, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report = run_curate_bars_1m(&args).expect("file-mode run should succeed"); + assert_report_conservation(&report); + assert_eq!(report.rows_written, 3); + + assert_eq!( + list_dir_names(&out_dir), + vec![ + "bars_1m.shard-00.ilp", + "bars_1m.shard-01.ilp", + "bars_1m.shard-02.ilp", + "bars_1m.shard-03.ilp", + ] + ); + + let mut total_rows = 0usize; + let mut total_bytes = 0usize; + let mut empty_shards = 0usize; + let mut listing_counts: BTreeMap = BTreeMap::new(); + + for shard_idx in 0..shard_count { + let path = out_dir.join(format!("bars_1m.shard-{shard_idx:02}.ilp")); + let bytes = fs::read(&path).expect("read shard file"); + total_bytes += bytes.len(); + let rows = decode_ilp_bars_1m(&bytes); + if rows.is_empty() { + empty_shards += 1; + } + assert_eq!( + rows.len(), + report.ilp_stats.per_shard_rows[shard_idx], + "shard {shard_idx} row count mismatch" + ); + for row in &rows { + assert_eq!( + shard_for_listing_id(row.listing_id, shard_count), + shard_idx, + "row landed on wrong shard" + ); + assert_eq!(row.known_at, known_at_micros); + *listing_counts.entry(row.listing_id).or_default() += 1; + } + total_rows += rows.len(); + } + + assert!(empty_shards >= 2, "expected at least 2 empty shards with 2 listings across 4 shards"); + assert_eq!(total_rows, report.rows_written); + assert_eq!(total_bytes, report.ilp_stats.bytes); + assert_eq!(listing_counts.get(&1001), Some(&2)); + assert_eq!(listing_counts.get(&2002), Some(&1)); +} + +// --------------------------------------------------------------------------------------------- +// QA (T-179) edge cases: legacy-path equivalence, ET-vs-UTC ex-date boundary, replay determinism. +// --------------------------------------------------------------------------------------------- + +/// Pinned fixture for the QA equivalence test. Non-reused tickers only, so the legacy +/// source-keyed `curate_bars_1m` (splits keyed by EOD ticker, un-adjusted inside the builder) and +/// the runner's listing-keyed path must agree bitwise on rows and on every stats counter, +/// including rows dropped only *after* un-adjustment (overflow to inf, volume underflow to 0) and +/// a key whose every row is dropped after un-adjustment (`builder.keys_out` decrement). +#[test] +fn qa_listing_keyed_runner_matches_legacy_source_keyed_curation_including_post_unadjust_drops() { + let dir = TempDirGuard::new("bars1m-qa-legacy-eq"); + let known_at_micros: i64 = 1_760_000_000_000_000; + + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "eod\tNVDA.US\t2020-01-01\t\t1001", + "qm\tNVDA\t2020-01-01\t\t1001", + "eod\tOVF.US\t2020-01-01\t\t1002", + "qm\tOVF\t2020-01-01\t\t1002", + "eod\tREV.US\t2020-01-01\t\t1003", + "qm\tREV\t2020-01-01\t\t1003", + ], + ); + let splits_bytes = concat_docs(&[ + make_split_doc("NVDA", "2024-06-10", 1.0, 10.0), + make_split_doc("OVF", "2024-06-10", 1.0, 10.0), + make_split_doc("REV", "2024-06-10", 20.0, 1.0), + ]); + + let t = |d: u32, h: u8, m: u8| et_ts_sec(2024, 6, d, h, m); + let docs = vec![ + // NVDA: normal pre-split bar, pre-split overflow bar (price * 10 -> inf), pre-split + // volume underflow (5e-324 / 10 -> 0), identical duplicate, conflicting duplicate, ex-date bar. + make_intraday_doc("NVDA.US", t(7, 10, 0), 120.0, 121.0, 119.0, 120.5, 1_000.0), + make_intraday_doc("NVDA.US", t(7, 10, 1), 1e308, 1e308, 1e308, 1e308, 10.0), + make_intraday_doc("NVDA.US", t(7, 10, 2), 120.0, 121.0, 119.0, 120.5, 5e-324), + make_intraday_doc("NVDA.US", t(7, 10, 3), 120.0, 121.0, 119.0, 120.5, 7.0), + make_intraday_doc("NVDA.US", t(7, 10, 3), 120.0, 121.0, 119.0, 120.5, 7.0), + make_intraday_doc("NVDA.US", t(7, 10, 4), 120.0, 121.0, 119.0, 120.5, 7.0), + make_intraday_doc("NVDA.US", t(7, 10, 4), 120.0, 121.0, 119.0, 120.6, 7.0), + make_intraday_doc("NVDA.US", t(10, 10, 0), 121.0, 122.0, 120.0, 121.5, 3_000.0), + // OVF: every row overflows after un-adjustment -> key contributes nothing. + make_intraday_doc("OVF.US", t(7, 9, 45), 1e308, 1e308, 1e308, 1e308, 1.0), + make_intraday_doc("OVF.US", t(7, 16, 30), 1.5e308, 1.5e308, 1.5e308, 1.5e308, 1.0), + // REV: reverse split (factor 0.05) scales prices down / volume up. + make_intraday_doc("REV.US", t(7, 8, 0), 24.0, 24.6, 23.8, 24.2, 2_000.0), + make_intraday_doc("REV.US", t(10, 15, 59), 1.2, 1.3, 1.1, 1.25, 40_000.0), + // Unmapped code. + make_intraday_doc("ZZZ.US", t(7, 10, 0), 5.0, 5.0, 5.0, 5.0, 1.0), + ]; + let intraday_bytes = concat_docs(&docs); + + // Runner path. + let mut sink0 = Vec::new(); + let mut sink1 = Vec::new(); + let mut sink2 = Vec::new(); + let writer = IlpShardedWriter::new( + vec![&mut sink0, &mut sink1, &mut sink2], + IlpWriterOptions::default(), + ) + .unwrap(); + let args = make_args( + mapping_path.clone(), + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out"), + 3, + known_at_micros, + BsonStreamOptions::default(), + ); + let report = run_curate_bars_1m_with_readers( + &args, + Cursor::new(&intraday_bytes), + Cursor::new(&splits_bytes), + writer, + ) + .expect("runner should succeed"); + assert_report_conservation(&report); + assert_eq!(report.chunks, 1, "fixture must fit one default chunk for a 1:1 comparison"); + + // Legacy path: splits keyed by EOD ticker, un-adjusted inside `build_bars_1m`. + let mapping_rows = load_provider_mapping_tsv(&mapping_path).unwrap(); + let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); + let ex = day(2024, 6, 10); + let legacy_splits = SplitTable::>::from_events(vec![ + (Arc::::from("NVDA.US"), crate::split::SplitEvent { ex_date: ex, ratio: 10.0 }), + (Arc::::from("OVF.US"), crate::split::SplitEvent { ex_date: ex, ratio: 10.0 }), + (Arc::::from("REV.US"), crate::split::SplitEvent { ex_date: ex, ratio: 0.05 }), + ]) + .unwrap(); + let mut legacy_bars: Vec>> = Vec::new(); + crate::bson_eod_intraday::decode_eod_intraday_buffer( + &intraday_bytes, + |raw| { + let key: Arc = Arc::from(raw.eod_search_code); + legacy_bars.push(raw.into_eod_intraday_bar(|_, _| key)); + }, + |_, _| {}, + ); + let legacy = crate::curate_bars_1m::curate_bars_1m( + legacy_bars, + &legacy_splits, + &mapping, + DEFAULT_BARS_1M_MAPPING_SOURCE, + ) + .unwrap(); + + // Stats: every counter identical (single chunk, so per-chunk sums are exact). + assert_eq!(report.curate_stats, legacy.stats); + let b = &report.curate_stats.builder; + assert_eq!(b.dropped_invalid_ohlc, 3, "NVDA overflow + 2 OVF overflow rows"); + assert_eq!(b.dropped_invalid_volume, 1, "NVDA volume underflow"); + assert_eq!(b.duplicate_collapsed, 1); + assert_eq!(b.duplicate_conflict_dropped, 2); + assert_eq!(b.keys_out, 3, "NVDA, REV, ZZZ keep rows; OVF must not be counted"); + assert_eq!(report.curate_stats.dropped_unmapped, 1); + assert_eq!(report.curate_stats.listings_out, 2); + assert_eq!(report.rows_written, 5); + + // Rows: bitwise identical multiset. + let mut runner_rows: Vec<_> = [&sink0, &sink1, &sink2] + .iter() + .flat_map(|s| decode_ilp_bars_1m(s)) + .map(|r| { + assert_eq!(r.known_at, known_at_micros); + r.sort_key() + }) + .collect(); + runner_rows.sort_unstable(); + let mut legacy_rows: Vec<_> = legacy + .rows + .iter() + .map(|r| { + ( + r.key, + r.ts, + r.open.to_bits(), + r.high.to_bits(), + r.low.to_bits(), + r.close.to_bits(), + r.volume.to_bits(), + known_at_micros, + ) + }) + .collect(); + legacy_rows.sort_unstable(); + assert_eq!(runner_rows, legacy_rows); +} + +/// The split factor is chosen from the bar's Eastern Time `session_date`, not its UTC date. +/// A POST bar at 21:00 ET on 2024-06-07 (Friday) is 01:00 UTC on 2024-06-08, and a POST bar at +/// 20:30 ET on Sunday 2024-06-09 is 00:30 UTC on the 2024-06-10 ex-date: both belong to pre-split +/// ET sessions and must be un-adjusted. A PRE bar at 04:00 ET on the ex-date (08:00 UTC) must be +/// left unchanged. +#[test] +fn qa_split_factor_uses_eastern_session_date_not_utc_date_around_ex_date() { + let dir = TempDirGuard::new("bars1m-qa-et-boundary"); + let mapping_path = write_mapping_tsv( + dir.path(), + &["eod\tNVDA.US\t2020-01-01\t\t1001", "qm\tNVDA\t2020-01-01\t\t1001"], + ); + let splits_bytes = concat_docs(&[make_split_doc("NVDA", "2024-06-10", 1.0, 10.0)]); + + let fri_late = et_ts_sec(2024, 6, 7, 21, 0); + let sun_late = et_ts_sec(2024, 6, 9, 20, 30); + let ex_pre = et_ts_sec(2024, 6, 10, 4, 0); + // Sanity: the UTC calendar date of the late bars is later than their ET session date. + assert_eq!(fri_late.div_euclid(86_400) as i32, day(2024, 6, 8)); + assert_eq!(sun_late.div_euclid(86_400) as i32, day(2024, 6, 10)); + + let intraday_bytes = concat_docs(&[ + make_intraday_doc("NVDA.US", fri_late, 120.0, 121.0, 119.0, 120.5, 500.0), + make_intraday_doc("NVDA.US", sun_late, 120.0, 121.0, 119.0, 120.5, 500.0), + make_intraday_doc("NVDA.US", ex_pre, 120.0, 121.0, 119.0, 120.5, 500.0), + ]); + + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let args = make_args( + mapping_path, + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out"), + 1, + 1_760_000_000_000_000, + BsonStreamOptions::default(), + ); + let report = run_curate_bars_1m_with_readers( + &args, + Cursor::new(&intraday_bytes), + Cursor::new(&splits_bytes), + writer, + ) + .unwrap(); + assert_report_conservation(&report); + assert_eq!(report.rows_written, 3); + + let rows = decode_ilp_bars_1m(&sink); + let by_ts = |ts_sec: i64| rows.iter().find(|r| r.ts == ts_sec * 1_000_000).unwrap(); + + for ts in [fri_late, sun_late] { + let r = by_ts(ts); + assert_eq!(r.session, IntradaySession::Post); + assert_eq!(r.close.to_bits(), (120.5_f64 * 10.0).to_bits(), "ts={ts}"); + assert_eq!(r.volume.to_bits(), (500.0_f64 / 10.0).to_bits(), "ts={ts}"); + } + let r = by_ts(ex_pre); + assert_eq!(r.session, IntradaySession::Pre); + assert_eq!(r.close.to_bits(), 120.5_f64.to_bits()); + assert_eq!(r.volume.to_bits(), 500.0_f64.to_bits()); +} + +/// Replay: the same pinned inputs and settings run twice through the public file-mode entry +/// produce byte-identical shard files and an identical report (ignoring wall-clock +/// `elapsed_secs`), and the formatted report is identical apart from its `timing:` line. +#[test] +fn qa_file_mode_replay_is_byte_identical_and_report_deterministic() { + let dir = TempDirGuard::new("bars1m-qa-replay"); + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "eod\tAAA.US\t2020-01-01\t\t11", + "eod\tBBB.US\t2020-01-01\t\t12", + "eod\tCCC.US\t2020-01-01\t\t13", + "qm\tAAA\t2020-01-01\t\t11", + ], + ); + let splits_path = dir.path().join("qmSplits.bson"); + fs::write(&splits_path, concat_docs(&[make_split_doc("AAA", "2025-03-11", 1.0, 4.0)])).unwrap(); + + let mut docs = Vec::new(); + for (i, code) in ["AAA.US", "BBB.US", "CCC.US", "NOPE.US"].iter().enumerate() { + for m in 0..6u8 { + let px = 10.0 + i as f64 + f64::from(m) * 0.01; + docs.push(make_intraday_doc( + code, + et_ts_sec(2025, 3, 10 + u32::from(m % 2), 9 + m, 30), + px, + px + 0.1, + px - 0.1, + px, + 100.0 + f64::from(m), + )); + } + } + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write(&intraday_path, concat_docs(&docs)).unwrap(); + + let small = BsonStreamOptions { + chunk_capacity_bytes: docs[0].as_bytes().len() * 5, + ..BsonStreamOptions::default() + }; + + let run = |out: &str| { + let out_dir = dir.path().join(out); + let args = make_args( + mapping_path.clone(), + splits_path.clone(), + intraday_path.clone(), + out_dir.clone(), + 3, + 1_760_000_000_000_000, + small, + ); + let report = run_curate_bars_1m(&args).expect("file-mode run"); + let files: Vec<(String, Vec)> = list_dir_names(&out_dir) + .into_iter() + .map(|name| { + let bytes = fs::read(out_dir.join(&name)).unwrap(); + (name, bytes) + }) + .collect(); + (report, files) + }; + + let (mut r1, f1) = run("out-a"); + let (mut r2, f2) = run("out-b"); + assert!(r1.chunks >= 3, "fixture must span several chunks, got {}", r1.chunks); + assert_report_conservation(&r1); + assert_eq!(f1.len(), 3); + assert_eq!(f1, f2, "replayed shard files differ"); + + let strip_timing = |s: String| { + s.lines() + .filter(|l| !l.trim_start().starts_with("timing:")) + .collect::>() + .join("\n") + }; + let fmt1 = strip_timing(format_curate_bars_1m_report(&r1)); + let fmt2 = strip_timing(format_curate_bars_1m_report(&r2)); + assert_eq!(fmt1, fmt2); + assert!(fmt1.contains(&format!("chunks={}", r1.chunks))); + assert!(fmt1.contains("cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)")); + assert!(fmt1.contains(&format!("rows_written={}", r1.rows_written))); + assert!(fmt1.contains("listings_out_per_chunk_sum=")); + + r1.elapsed_secs = 0.0; + r2.elapsed_secs = 0.0; + assert_eq!(r1, r2); + + // Shard bytes match the report and every row lives on its assigned shard. + let mut total_rows = 0usize; + for (idx, (name, bytes)) in f1.iter().enumerate() { + assert_eq!(name, &format!("bars_1m.shard-{idx:02}.ilp")); + let rows = decode_ilp_bars_1m(bytes); + assert_eq!(rows.len(), r1.ilp_stats.per_shard_rows[idx]); + for row in &rows { + assert_eq!(shard_for_listing_id(row.listing_id, 3), idx); + } + total_rows += rows.len(); + } + assert_eq!(total_rows, r1.rows_written); + assert_eq!(f1.iter().map(|(_, b)| b.len()).sum::(), r1.ilp_stats.bytes); +} + +/// A missing intraday input on the public file-mode entry fails before `out_dir` is created. +#[test] +fn qa_missing_intraday_input_fails_before_creating_out_dir() { + let dir = TempDirGuard::new("bars1m-qa-missing-intraday"); + let mapping_path = write_mapping_tsv(dir.path(), &["eod\tAAA.US\t2020-01-01\t\t11"]); + let splits_path = dir.path().join("qmSplits.bson"); + fs::write(&splits_path, b"").unwrap(); + let out_dir = dir.path().join("never-created"); + let args = make_args( + mapping_path, + splits_path, + dir.path().join("missing-eodIntraday1M.bson"), + out_dir.clone(), + 2, + 1, + BsonStreamOptions::default(), + ); + let err = run_curate_bars_1m(&args).unwrap_err(); + assert!( + matches!(err, RunCurateBars1mError::OpenInput { label: "eod-intraday", .. }), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); +} + +/// QA (T-179): a truncated `qmSplits` tail is a fatal reference-load error in file mode. The run +/// must return `LoadReference(BsonStream { label: "qm-splits" })` and publish nothing: no final +/// `bars_1m.shard-*.ilp` and no staging file, and a pre-existing unrelated file is untouched. +#[test] +fn qa_truncated_qm_splits_fails_closed_in_file_mode_without_outputs() { + let dir = TempDirGuard::new("bars1m-qa-trunc-splits"); + let mapping_path = write_mapping_tsv( + dir.path(), + &["eod\tAAA.US\t2020-01-01\t\t11", "qm\tAAA\t2020-01-01\t\t11"], + ); + let mut splits_bytes = concat_docs(&[ + make_split_doc("AAA", "2025-05-06", 1.0, 2.0), + make_split_doc("AAA", "2025-07-01", 1.0, 3.0), + ]); + splits_bytes.truncate(splits_bytes.len() - 5); + let splits_path = dir.path().join("qmSplits.bson"); + fs::write(&splits_path, &splits_bytes).unwrap(); + + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write( + &intraday_path, + concat_docs(&[make_intraday_doc( + "AAA.US", + et_ts_sec(2025, 5, 5, 10, 0), + 10.0, + 10.5, + 9.5, + 10.2, + 100.0, + )]), + ) + .unwrap(); + + let out_dir = dir.path().join("out"); + fs::create_dir_all(&out_dir).unwrap(); + fs::write(out_dir.join("keep.txt"), b"keep").unwrap(); + + let args = make_args( + mapping_path, + splits_path, + intraday_path, + out_dir.clone(), + 2, + 1, + BsonStreamOptions::default(), + ); + let err = run_curate_bars_1m(&args).unwrap_err(); + assert!( + matches!( + err, + RunCurateBars1mError::LoadReference(RunCurateBarsError::BsonStream { + label: "qm-splits", + .. + }) + ), + "{err:?}" + ); + assert!(err.source().is_some()); + assert_eq!(list_dir_names(&out_dir), vec!["keep.txt"]); + assert_eq!(fs::read(out_dir.join("keep.txt")).unwrap(), b"keep"); +} + +/// QA (T-179): listing-keyed splits apply to every `"eod"` alias of the same listing. Two EOD +/// tickers mapped to listing 77 over consecutive ranges both receive the 2:1 split (ex-date +/// 2025-06-02); an unrelated listing without splits is untouched. +#[test] +fn qa_listing_split_applies_to_all_eod_aliases_of_the_listing() { + let dir = TempDirGuard::new("bars1m-qa-aliases"); + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "eod\tOLD.US\t2020-01-01\t2025-05-15\t77", + "eod\tNEW.US\t2025-05-16\t\t77", + "qm\tNEWQ\t2020-01-01\t\t77", + "eod\tOTH.US\t2020-01-01\t\t88", + ], + ); + let splits_bytes = concat_docs(&[make_split_doc("NEWQ", "2025-06-02", 1.0, 2.0)]); + let intraday_bytes = concat_docs(&[ + make_intraday_doc("OLD.US", et_ts_sec(2025, 5, 14, 10, 0), 10.0, 11.0, 9.0, 10.5, 200.0), + make_intraday_doc("NEW.US", et_ts_sec(2025, 5, 20, 10, 0), 12.0, 13.0, 11.0, 12.5, 400.0), + make_intraday_doc("NEW.US", et_ts_sec(2025, 6, 2, 10, 0), 6.0, 6.5, 5.5, 6.25, 800.0), + make_intraday_doc("OTH.US", et_ts_sec(2025, 5, 20, 10, 0), 20.0, 21.0, 19.0, 20.5, 50.0), + // OLD.US after its mapping range closed: unmapped, never mis-attributed. + make_intraday_doc("OLD.US", et_ts_sec(2025, 5, 20, 10, 0), 1.0, 1.0, 1.0, 1.0, 1.0), + ]); + + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let args = make_args( + mapping_path, + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out"), + 1, + 42, + BsonStreamOptions::default(), + ); + let report = run_curate_bars_1m_with_readers( + &args, + Cursor::new(&intraday_bytes), + Cursor::new(&splits_bytes), + writer, + ) + .expect("alias run should succeed"); + assert_report_conservation(&report); + assert_eq!(report.split_rekey.splits_applied, 1); + assert_eq!(report.curate_stats.dropped_unmapped, 1); + assert_eq!(report.rows_written, 4); + + let rows = decode_ilp_bars_1m(&sink); + let get = |id: i32, ts: i64| { + rows.iter() + .find(|r| r.listing_id == id && r.ts == ts * 1_000_000) + .expect("row") + .clone() + }; + let old = get(77, et_ts_sec(2025, 5, 14, 10, 0)); + assert_eq!((old.close, old.volume), (21.0, 100.0)); + let new_pre = get(77, et_ts_sec(2025, 5, 20, 10, 0)); + assert_eq!((new_pre.close, new_pre.volume), (25.0, 200.0)); + let new_ex = get(77, et_ts_sec(2025, 6, 2, 10, 0)); + assert_eq!((new_ex.close, new_ex.volume), (6.25, 800.0)); + let oth = get(88, et_ts_sec(2025, 5, 20, 10, 0)); + assert_eq!((oth.close, oth.volume), (20.5, 50.0)); +} diff --git a/tools/curate-etl/src/run_curate_fx_1m.rs b/tools/curate-etl/src/run_curate_fx_1m.rs new file mode 100644 index 00000000..7c938c0b --- /dev/null +++ b/tools/curate-etl/src/run_curate_fx_1m.rs @@ -0,0 +1,555 @@ +//! File-to-file `fx_1m` runner (`M2.3l`). +//! +//! Streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files +//! (`/fx_1m.shard-.ilp`) via [`crate::curate_fx_1m::curate_and_write_fx_1m_from_bson`]. +//! +//! # Global Sort, Deduplication & Memory Bound +//! - Calls [`curate_and_write_fx_1m_from_bson`] **once** over the entire input stream so timestamp +//! sorting and `ts` deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop) +//! are global across all BSON stream chunks, then calls [`IlpShardedWriter::finish`] exactly +//! once after clean EOF. +//! - **Memory bound:** `Fx1mAccumulator::push` in `src/curate_fx_1m.rs` counts non-`CAD.FOREX` +//! rows in `dropped_wrong_code` and returns immediately without appending or allocating. Peak +//! memory is therefore bounded by: +//! - accepted `CAD.FOREX` rows (`Vec>`), +//! - the configured BSON stream chunk buffer (`BsonStreamOptions::chunk_capacity_bytes`, +//! growing only for a single document up to `max_doc_bytes`), and +//! - bounded ILP output batch buffers per shard (`IlpWriterOptions`) plus per-shard file +//! buffering in file mode. +//! +//! Non-`CAD.FOREX` rows from the full `eodIntraday1M` dump are never buffered. +//! - **Single-pair sharding:** every curated row carries `pair = "USDCAD"` and `source = "eod"`, +//! so [`IlpShardedWriter`] routes all rows deterministically to +//! `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files. +//! - **Timestamp provenance:** preserves EODHD's UTC microsecond bar-start `ts` and CAD-per-USD +//! OHLC bits verbatim; bar-start `ts` alone does not establish when the bar's close was +//! observable. +//! - **Omitted framing counters:** [`CurateFx1mRunReport`] omits `intraday_docs_framed` and +//! `intraday_bytes_read` because [`curate_and_write_fx_1m_from_bson`] owns the underlying +//! `RawBsonChunkReader` internally and returns [`BsonEodIntradayDecodeStats`] only. +//! +//! # File Publication & Fail-Closed Guarantees +//! - Preflight scans `out_dir` for **any** pre-existing `fx_1m.shard-.ilp` file +//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards +//! from a prior run cannot survive alongside a new export. +//! - Each shard writes into an exclusively created staging file in `out_dir` +//! (`.fx_1m.shard-..tmp`), flushes and `sync_all`s on `finish`, and publishes to +//! `fx_1m.shard-.ilp` via same-directory `hard_link` followed by removing the staged name +//! (preserving no-overwrite semantics even if a final file appears after preflight). +//! - Any error (validation, missing input, fatal BSON framing/I/O, ILP write/flush, or +//! publication collision) rolls back only final files created by this run, removes this run's +//! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors +//! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`]. + +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use crate::bson_eod_intraday::BsonEodIntradayDecodeStats; +use crate::bson_stream::{BsonStreamError, BsonStreamOptions}; +use crate::curate_fx_1m::{ + curate_and_write_fx_1m_from_bson, CurateFx1mBsonError, CurateFx1mStats, +}; +use crate::ilp::{ + IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_FX_1M, +}; +use crate::parquet_bars::RollbackFailure; +use crate::parquet_publish::{next_run_id, StagingFileGuard}; +use crate::run_curate_bars_1m::{ + create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir, + publish_staged_shards_for_table, ShardPublishError, SyncedBufFile, +}; + +/// Arguments for [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateFx1mArgs { + pub intraday_path: PathBuf, + pub out_dir: PathBuf, + pub shard_count: usize, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +/// Full run report produced by [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`]. +/// +/// `intraday_docs_framed` and `intraday_bytes_read` are intentionally omitted because +/// [`curate_and_write_fx_1m_from_bson`] owns the underlying `RawBsonChunkReader` and returns +/// [`BsonEodIntradayDecodeStats`] only. +/// +/// Conservation invariants: +/// - `decode.docs_seen == decode.rows_decoded + decode.rejected_total()` +/// - `decode.rows_decoded == curate_stats.bars_in` +/// - `curate_stats.bars_in == curate_stats.rows_out + curate_stats.dropped_wrong_code + curate_stats.dropped_negative_ts + curate_stats.dropped_invalid_ohlc + curate_stats.dropped_high_below_bound + curate_stats.dropped_low_above_bound + curate_stats.duplicate_collapsed + curate_stats.duplicate_conflict_dropped` +/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::()` +#[derive(Debug, Clone, PartialEq)] +pub struct CurateFx1mRunReport { + pub decode: BsonEodIntradayDecodeStats, + pub curate_stats: CurateFx1mStats, + pub rows_written: usize, + pub ilp_stats: IlpWriteStats, + pub shard_count: usize, + pub elapsed_secs: f64, +} + +/// Typed errors returned by [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`]. +#[derive(Debug)] +pub enum RunCurateFx1mError { + /// `shard_count` was `0`. + ZeroShardCount, + /// Caller-supplied `IlpShardedWriter` shard count did not match `args.shard_count`. + ShardCountMismatch { expected: usize, actual: usize }, + /// Caller-supplied `IlpShardedWriter` already had queued or flushed rows before the run. + NonEmptyWriter { + flushed_rows: usize, + pending_rows: usize, + }, + /// `out_dir` exists and is not a directory. + InvalidOutDir { path: PathBuf, detail: String }, + /// A final shard output file (`fx_1m.shard-.ilp`) already existed. + OutputFileExists { path: PathBuf }, + /// Failed to open the input `eodIntraday1M` dump file. + OpenInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + /// Fatal BSON framing, option validation, or I/O error while reading `eodIntraday1M`. + BsonStream { + label: &'static str, + path: PathBuf, + source: BsonStreamError, + }, + /// ILP writer initialization, per-row write, or final flush error. + Ilp(IlpWriterError), + /// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files. + Io { path: PathBuf, source: io::Error }, + /// Publication or failure cleanup failed and removing one or more final or staging files also failed. + RollbackFailed { + cause: Box, + failures: Vec, + }, +} + +impl From for RunCurateFx1mError { + fn from(err: ShardPublishError) -> Self { + match err { + ShardPublishError::InvalidOutDir { path, detail } => { + Self::InvalidOutDir { path, detail } + } + ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path }, + ShardPublishError::Io { path, source } => Self::Io { path, source }, + ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed { + cause: Box::new((*cause).into()), + failures, + }, + } + } +} + +impl fmt::Display for RunCurateFx1mError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ZeroShardCount => write!(f, "shard_count must be >= 1"), + Self::ShardCountMismatch { expected, actual } => write!( + f, + "ILP writer shard count mismatch: expected {expected}, got {actual}" + ), + Self::NonEmptyWriter { + flushed_rows, + pending_rows, + } => write!( + f, + "ILP writer must be fresh before running fx_1m (found {flushed_rows} flushed and {pending_rows} pending rows)" + ), + Self::InvalidOutDir { path, detail } => { + write!(f, "invalid out_dir '{}': {detail}", path.display()) + } + Self::OutputFileExists { path } => write!( + f, + "refusing to overwrite existing output file '{}'", + path.display() + ), + Self::OpenInput { + label, + path, + source, + } => write!(f, "failed to open {label} '{}': {source}", path.display()), + Self::BsonStream { + label, + path, + source, + } => write!(f, "failed reading {label} '{}': {source}", path.display()), + Self::Ilp(err) => write!(f, "fx_1m ILP writer failed: {err}"), + Self::Io { path, source } => { + write!(f, "I/O error on '{}': {source}", path.display()) + } + Self::RollbackFailed { cause, failures } => { + write!(f, "{cause}; rollback also failed for: ")?; + for (i, failure) in failures.iter().enumerate() { + if i > 0 { + write!(f, ", ")?; + } + write!(f, "{failure}")?; + } + Ok(()) + } + } + } +} + +impl Error for RunCurateFx1mError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source), + Self::BsonStream { source, .. } => Some(source), + Self::Ilp(err) => Some(err), + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::ZeroShardCount + | Self::ShardCountMismatch { .. } + | Self::NonEmptyWriter { .. } + | Self::InvalidOutDir { .. } + | Self::OutputFileExists { .. } => None, + } + } +} + +fn validate_common_args(args: &CurateFx1mArgs) -> Result<(), RunCurateFx1mError> { + if args.shard_count == 0 { + return Err(RunCurateFx1mError::ZeroShardCount); + } + args.stream_options + .validate() + .map_err(|source| RunCurateFx1mError::BsonStream { + label: "eod-intraday", + path: args.intraday_path.clone(), + source, + })?; + Ok(()) +} + +fn validate_file_mode_args(args: &CurateFx1mArgs) -> Result<(), RunCurateFx1mError> { + validate_common_args(args)?; + if args.ilp_options.max_batch_bytes == 0 { + return Err(RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes)); + } + if args.ilp_options.max_batch_rows == 0 { + return Err(RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchRows)); + } + preflight_shard_out_dir(&args.out_dir, TABLE_FX_1M)?; + Ok(()) +} + +fn run_curate_fx_1m_with_readers_inner( + args: &CurateFx1mArgs, + intraday: R, + mut writer: IlpShardedWriter, + start: Instant, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + let bson_report = + curate_and_write_fx_1m_from_bson(intraday, args.stream_options, &mut writer).map_err( + |err| match err { + CurateFx1mBsonError::Stream(source) => RunCurateFx1mError::BsonStream { + label: "eod-intraday", + path: args.intraday_path.clone(), + source, + }, + CurateFx1mBsonError::Write(err) => RunCurateFx1mError::Ilp(err), + }, + )?; + + let ilp_stats = writer.finish().map_err(RunCurateFx1mError::Ilp)?; + + Ok(CurateFx1mRunReport { + decode: bson_report.decode_stats, + curate_stats: bson_report.write_report.curate_stats, + rows_written: bson_report.write_report.rows_written, + ilp_stats, + shard_count: args.shard_count, + elapsed_secs: start.elapsed().as_secs_f64(), + }) +} + +/// Runs the `fx_1m` curation pipeline from an arbitrary [`io::Read`] stream into a caller-owned +/// [`IlpShardedWriter`]. +/// +/// Validates `args`, writer shard-count agreement, and that `writer` is fresh (zero queued or +/// flushed rows) before reading `intraday`. Calls [`curate_and_write_fx_1m_from_bson`] once over +/// the entire stream for global sort and `ts` deduplication, and calls [`IlpShardedWriter::finish`] +/// exactly once after clean EOF. +pub fn run_curate_fx_1m_with_readers( + args: &CurateFx1mArgs, + intraday: R, + writer: IlpShardedWriter, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + let start = Instant::now(); + validate_common_args(args)?; + if writer.shard_count() != args.shard_count { + return Err(RunCurateFx1mError::ShardCountMismatch { + expected: args.shard_count, + actual: writer.shard_count(), + }); + } + let (flushed_rows, pending_rows) = writer.row_counts(); + if flushed_rows > 0 || pending_rows > 0 { + return Err(RunCurateFx1mError::NonEmptyWriter { + flushed_rows, + pending_rows, + }); + } + + run_curate_fx_1m_with_readers_inner(args, intraday, writer, start) +} + +pub(crate) fn cleanup_armed_staged_shards( + staged: &mut [(PathBuf, StagingFileGuard)], + remove_file: &mut RF, +) -> Vec +where + RF: FnMut(&Path) -> io::Result<()>, +{ + let mut failures = Vec::new(); + for (tmp_path, guard) in staged.iter_mut() { + if !guard.is_armed() { + continue; + } + match remove_file(tmp_path) { + Ok(()) => guard.disarm(), + Err(err) if err.kind() == io::ErrorKind::NotFound => guard.disarm(), + Err(source) => { + guard.disarm(); + failures.push(RollbackFailure { + final_path: tmp_path.clone(), + backup_path: None, + source, + }); + } + } + } + failures +} + +fn fail_with_staging_cleanup( + cause: RunCurateFx1mError, + staged: &mut [(PathBuf, StagingFileGuard)], + remove_file: &mut RF, +) -> RunCurateFx1mError +where + RF: FnMut(&Path) -> io::Result<()>, +{ + let staging_failures = cleanup_armed_staged_shards(staged, remove_file); + if staging_failures.is_empty() { + return cause; + } + match cause { + RunCurateFx1mError::RollbackFailed { + cause: inner_cause, + mut failures, + } => { + failures.extend(staging_failures); + RunCurateFx1mError::RollbackFailed { + cause: inner_cause, + failures, + } + } + other => RunCurateFx1mError::RollbackFailed { + cause: Box::new(other), + failures: staging_failures, + }, + } +} + +/// Private file-mode seam accepting an injected reader, sink factory, pre-link hook, and staging +/// unlink hook so tests can exercise staging, writer failure, publication rollback, and staging +/// unlink failure reporting deterministically. +fn run_curate_fx_1m_to_dir_with_cleanup_hook( + args: &CurateFx1mArgs, + intraday: R, + mut make_sink: SF, + before_link: BL, + mut remove_staged_file: RF, +) -> Result +where + R: io::Read, + W: Write + Send, + SF: FnMut(usize, File) -> W, + BL: FnMut(usize, &Path), + RF: FnMut(&Path) -> io::Result<()>, +{ + let start = Instant::now(); + validate_file_mode_args(args)?; + + fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateFx1mError::Io { + path: args.out_dir.clone(), + source, + })?; + + let run_id = next_run_id(); + let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count); + let mut sinks: Vec = Vec::with_capacity(args.shard_count); + for shard_idx in 0..args.shard_count { + let (tmp_path, file) = match create_exclusive_shard_tmp_file_for_table( + &args.out_dir, + TABLE_FX_1M, + shard_idx, + &run_id, + ) { + Ok(pair) => pair, + Err(err) => { + drop(sinks); + return Err(fail_with_staging_cleanup( + err.into(), + &mut staged, + &mut remove_staged_file, + )); + } + }; + let guard = StagingFileGuard::new(tmp_path.clone()); + staged.push((tmp_path, guard)); + sinks.push(make_sink(shard_idx, file)); + } + + let writer = match IlpShardedWriter::new(sinks, args.ilp_options) { + Ok(writer) => writer, + Err(err) => { + return Err(fail_with_staging_cleanup( + RunCurateFx1mError::Ilp(err), + &mut staged, + &mut remove_staged_file, + )); + } + }; + let report = match run_curate_fx_1m_with_readers_inner(args, intraday, writer, start) { + Ok(report) => report, + Err(err) => { + return Err(fail_with_staging_cleanup( + err, + &mut staged, + &mut remove_staged_file, + )); + } + }; + + if let Err(err) = + publish_staged_shards_for_table(&args.out_dir, TABLE_FX_1M, &mut staged, before_link) + { + return Err(fail_with_staging_cleanup( + err.into(), + &mut staged, + &mut remove_staged_file, + )); + } + Ok(report) +} + +/// Private file-mode seam accepting an injected reader, sink factory, and pre-link hook so tests +/// can exercise staging, writer failure, and post-preflight publication rollback through the exact +/// file publication path. +fn run_curate_fx_1m_to_dir_with_hooks( + args: &CurateFx1mArgs, + intraday: R, + make_sink: SF, + before_link: BL, +) -> Result +where + R: io::Read, + W: Write + Send, + SF: FnMut(usize, File) -> W, + BL: FnMut(usize, &Path), +{ + run_curate_fx_1m_to_dir_with_cleanup_hook( + args, + intraday, + make_sink, + before_link, + |path| fs::remove_file(path), + ) +} + +/// Runs the file-to-file `fx_1m` curation pipeline, publishing exactly `args.shard_count` QuestDB +/// ILP v2 files (`/fx_1m.shard-.ilp`). +pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result { + validate_file_mode_args(args)?; + + let intraday_file = File::open(&args.intraday_path).map_err(|source| { + RunCurateFx1mError::OpenInput { + label: "eod-intraday", + path: args.intraday_path.clone(), + source, + } + })?; + + run_curate_fx_1m_to_dir_with_hooks( + args, + intraday_file, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + +/// Formats [`CurateFx1mRunReport`] into a deterministic machine-readable `key=value` summary. +/// +/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). +pub fn format_curate_fx_1m_report(report: &CurateFx1mRunReport) -> String { + let per_shard = if report.ilp_stats.per_shard_rows.is_empty() { + "none".to_string() + } else { + report + .ilp_stats + .per_shard_rows + .iter() + .enumerate() + .map(|(idx, count)| format!("{idx:02}={count}")) + .collect::>() + .join(",") + }; + + let d = &report.decode; + let c = &report.curate_stats; + + format!( + "curate-etl curate-fx-1m\n\ + \x20 intraday_bson: docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\ + \x20 curate: bars_in={} rows_out={} wrong_code={} negative_ts={} invalid_ohlc={} high_below_bound={} low_above_bound={} dup_collapsed={} dup_conflict_dropped={}\n\ + \x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\ + \x20 timing: elapsed_secs={:.6}", + d.docs_seen, + d.rows_decoded, + d.rejected_total(), + d.rejected_missing_field, + d.rejected_empty_field, + d.rejected_wrong_type, + d.rejected_invalid_timestamp, + d.rejected_invalid_number, + d.rejected_corrupt_document, + c.bars_in, + c.rows_out, + c.dropped_wrong_code, + c.dropped_negative_ts, + c.dropped_invalid_ohlc, + c.dropped_high_below_bound, + c.dropped_low_above_bound, + c.duplicate_collapsed, + c.duplicate_conflict_dropped, + report.shard_count, + report.rows_written, + report.ilp_stats.rows, + report.ilp_stats.bytes, + report.ilp_stats.flushes, + report.elapsed_secs, + ) +} + +#[cfg(test)] +#[path = "run_curate_fx_1m_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_curate_fx_1m_tests.rs b/tools/curate-etl/src/run_curate_fx_1m_tests.rs new file mode 100644 index 00000000..b35a7e34 --- /dev/null +++ b/tools/curate-etl/src/run_curate_fx_1m_tests.rs @@ -0,0 +1,1728 @@ +use std::error::Error; +use std::fs; +use std::io::{self, Cursor, Write}; +use std::path::{Path, PathBuf}; + +use bson::raw::{cstr, RawDocumentBuf}; + +use super::*; +use crate::bson_eod_intraday::decode_eod_intraday_buffer; +use crate::bson_stream::{RawBsonChunkReader, MIN_BSON_DOC_BYTES}; +use crate::curate_fx_1m::{curate_and_write_fx_1m, FX_1M_SOURCE_EOD}; +use crate::fx::FX_PAIR_USDCAD; +use crate::ilp::{shard_for_fx_pair, ILP_V2_DOUBLE_TYPE, TABLE_FX_1M}; +use crate::run_curate_bars_1m::tests::TempDirGuard; +use crate::run_curate_fx::EOD_CAD_FOREX_CODE; + +fn make_intraday_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_malformed_missing_open_doc(code: &str, timestamp_sec: i64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("timestamp"), timestamp_sec); + doc.append(cstr!("high"), 1.3755_f64); + doc.append(cstr!("low"), 1.3745_f64); + doc.append(cstr!("close"), 1.3752_f64); + doc.append(cstr!("volume"), 0.0_f64); + doc +} + +fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { + let mut out = Vec::new(); + for doc in docs { + out.extend_from_slice(doc.as_bytes()); + } + out +} + +fn make_args( + intraday_path: PathBuf, + out_dir: PathBuf, + shard_count: usize, + stream_options: BsonStreamOptions, +) -> CurateFx1mArgs { + CurateFx1mArgs { + intraday_path, + out_dir, + shard_count, + stream_options, + ilp_options: IlpWriterOptions::default(), + } +} + +fn list_dir_names(dir: &Path) -> Vec { + if !dir.exists() { + return Vec::new(); + } + let mut names: Vec = fs::read_dir(dir) + .expect("read_dir") + .map(|entry| { + entry + .expect("dir entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .collect(); + names.sort(); + names +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedIlpFx1m { + pair: String, + source: String, + open: f64, + high: f64, + low: f64, + close: f64, + ts: i64, +} + +/// Decodes QuestDB ILP v2 `fx_1m` records respecting fixed-width 8-byte binary `DOUBLE` payloads +/// (`==\x10<8 LE bytes>`) so embedded `0x0a` bytes inside doubles never split rows. +fn decode_ilp_fx_1m(data: &[u8]) -> Vec { + let mut rows = Vec::new(); + let mut i = 0usize; + let len = data.len(); + + while i < len { + let tag_start = i; + while i < len { + match data[i] { + b'\\' => { + assert!(i + 1 < len, "dangling backslash in ILP tag set"); + i += 2; + } + b' ' => break, + _ => i += 1, + } + } + assert!(i < len && data[i] == b' ', "missing space after ILP tag set"); + let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("valid UTF-8 tag set"); + i += 1; + + let mut tags = tag_str.split(','); + assert_eq!(tags.next(), Some(TABLE_FX_1M), "expected fx_1m table"); + let pair_tag = tags.next().expect("pair tag"); + let source_tag = tags.next().expect("source tag"); + assert!(tags.next().is_none(), "unexpected extra ILP tag"); + + let pair = pair_tag + .strip_prefix("pair=") + .expect("pair= prefix") + .to_string(); + let source = source_tag + .strip_prefix("source=") + .expect("source= prefix") + .to_string(); + + let read_bin_f64 = |pos: &mut usize, name: &str| -> f64 { + let prefix = format!("{name}=="); + assert!( + data[*pos..].starts_with(prefix.as_bytes()), + "expected field prefix '{prefix}' at offset {}", + *pos + ); + *pos += prefix.len(); + assert_eq!( + data[*pos], ILP_V2_DOUBLE_TYPE, + "expected binary DOUBLE type tag for '{name}'" + ); + *pos += 1; + let bytes: [u8; 8] = data[*pos..*pos + 8] + .try_into() + .expect("8 bytes for binary double"); + *pos += 8; + f64::from_le_bytes(bytes) + }; + + let open = read_bin_f64(&mut i, "open"); + assert_eq!(data[i], b','); + i += 1; + let high = read_bin_f64(&mut i, "high"); + assert_eq!(data[i], b','); + i += 1; + let low = read_bin_f64(&mut i, "low"); + assert_eq!(data[i], b','); + i += 1; + let close = read_bin_f64(&mut i, "close"); + assert_eq!(data[i], b' ', "missing space after close field"); + i += 1; + + let ts_start = i; + while i < len && data[i] != b'\n' { + i += 1; + } + assert!(i < len && data[i] == b'\n', "missing trailing LF"); + let ts_str = std::str::from_utf8(&data[ts_start..i]).expect("valid UTF-8 ts"); + let ts: i64 = ts_str + .strip_suffix('t') + .expect("ts trailing t") + .parse() + .expect("i64 ts"); + i += 1; + + rows.push(DecodedIlpFx1m { + pair, + source, + open, + high, + low, + close, + ts, + }); + } + + rows +} + +fn assert_report_conservation(report: &CurateFx1mRunReport) { + let d = &report.decode; + assert_eq!( + d.docs_seen, + d.rows_decoded + d.rejected_total(), + "decode conservation failed: {d:?}" + ); + + let c = &report.curate_stats; + assert_eq!( + d.rows_decoded, c.bars_in, + "rows_decoded != curate_stats.bars_in" + ); + assert_eq!( + c.bars_in, + c.rows_out + + c.dropped_wrong_code + + c.dropped_negative_ts + + c.dropped_invalid_ohlc + + c.dropped_high_below_bound + + c.dropped_low_above_bound + + c.duplicate_collapsed + + c.duplicate_conflict_dropped, + "curate_stats conservation failed: {c:?}" + ); + assert_eq!(report.rows_written, c.rows_out, "rows_written != rows_out"); + assert_eq!( + report.rows_written, report.ilp_stats.rows, + "rows_written != ilp_stats.rows" + ); + assert_eq!( + report.ilp_stats.per_shard_rows.iter().sum::(), + report.ilp_stats.rows, + "sum(per_shard_rows) != ilp_stats.rows" + ); + assert_eq!(report.ilp_stats.per_shard_rows.len(), report.shard_count); +} + +struct FailingWriteSink { + fail_on_write: bool, + fail_on_flush: bool, +} + +impl Write for FailingWriteSink { + fn write(&mut self, buf: &[u8]) -> io::Result { + if self.fail_on_write { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected write failure")) + } else { + Ok(buf.len()) + } + } + + fn flush(&mut self) -> io::Result<()> { + if self.fail_on_flush { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected flush failure")) + } else { + Ok(()) + } + } +} + +#[test] +fn happy_path_matches_curate_and_write_fx_1m_bytes_and_preserves_conservation() { + let dir = TempDirGuard::new("fx1m-happy"); + let ts1 = 1_717_971_300_i64; // 2024-06-09 22:15:00 UTC + let ts2 = 1_717_971_360_i64; + let ts3 = 1_717_988_400_i64; + + let docs = vec![ + // Out-of-order valid CAD.FOREX bars + make_intraday_doc(EOD_CAD_FOREX_CODE, ts3, 1.37654321, 1.37712345, 1.37611111, 1.37689012, 0.0), + make_intraday_doc("AAPL.US", ts1, 195.0, 196.0, 194.5, 195.5, 1000.0), + make_malformed_missing_open_doc(EOD_CAD_FOREX_CODE, ts1 + 10), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.3750, 1.3755, 1.3745, 1.3752, 5.0), + make_intraday_doc("cad.forex", ts2, 1.3750, 1.3755, 1.3745, 1.3752, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3752, 1.3760, 1.3750, 1.3758, 12.0), + // Valid BSON bar that fails FX builder high-below-bound rule + make_intraday_doc(EOD_CAD_FOREX_CODE, ts3 + 60, 1.3800, 1.3750, 1.3700, 1.3720, 0.0), + // Valid BSON bar that fails FX builder low-above-bound rule + make_intraday_doc(EOD_CAD_FOREX_CODE, ts3 + 120, 1.3700, 1.3800, 1.3750, 1.3780, 0.0), + ]; + let intraday_bytes = concat_docs(&docs); + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write(&intraday_path, &intraday_bytes).unwrap(); + + // Run file-mode runner with 4 shards. + let out_dir = dir.path().join("out"); + let args = make_args( + intraday_path, + out_dir.clone(), + 4, + BsonStreamOptions::default(), + ); + let report = run_curate_fx_1m(&args).expect("happy-path run should succeed"); + assert_report_conservation(&report); + + assert_eq!(report.decode.docs_seen, 8); + assert_eq!(report.decode.rows_decoded, 7); + assert_eq!(report.decode.rejected_missing_field, 1); + assert_eq!(report.curate_stats.bars_in, 7); + assert_eq!(report.curate_stats.rows_out, 3); + assert_eq!(report.curate_stats.dropped_wrong_code, 2); + assert_eq!(report.curate_stats.dropped_high_below_bound, 1); + assert_eq!(report.curate_stats.dropped_low_above_bound, 1); + assert_eq!(report.rows_written, 3); + + // Reference output from `curate_and_write_fx_1m` on the fixture's decoded bars. + let mut ref_sinks = [Vec::new(), Vec::new(), Vec::new(), Vec::new()]; + let mut ref_writer = IlpShardedWriter::new( + ref_sinks.iter_mut().collect(), + IlpWriterOptions::default(), + ) + .unwrap(); + let mut decoded_bars = Vec::new(); + let ref_decode = decode_eod_intraday_buffer( + &intraday_bytes, + |raw| decoded_bars.push(raw), + |_offset, _err| {}, + ); + assert_eq!(ref_decode, report.decode); + let ref_write = curate_and_write_fx_1m(decoded_bars, &mut ref_writer).unwrap(); + let ref_ilp = ref_writer.finish().unwrap(); + assert_eq!(ref_write.curate_stats, report.curate_stats); + assert_eq!(ref_write.rows_written, report.rows_written); + assert_eq!(ref_ilp, report.ilp_stats); + + let mut total_file_bytes = 0usize; + let mut all_decoded = Vec::new(); + for (shard_idx, expected_bytes) in ref_sinks.iter().enumerate() { + let path = out_dir.join(format!("fx_1m.shard-{shard_idx:02}.ilp")); + let file_bytes = fs::read(&path).expect("read shard file"); + assert_eq!( + &file_bytes, expected_bytes, + "shard {shard_idx:02} bytes differ from curate_and_write_fx_1m" + ); + total_file_bytes += file_bytes.len(); + all_decoded.extend(decode_ilp_fx_1m(&file_bytes)); + } + assert_eq!(total_file_bytes, report.ilp_stats.bytes); + + // Verify decoded fields, ascending ts, and exact OHLC bits. + assert_eq!(all_decoded.len(), 3); + let expected = [ + (ts1 * 1_000_000, 1.3750_f64, 1.3755_f64, 1.3745_f64, 1.3752_f64), + (ts2 * 1_000_000, 1.3752_f64, 1.3760_f64, 1.3750_f64, 1.3758_f64), + (ts3 * 1_000_000, 1.37654321_f64, 1.37712345_f64, 1.37611111_f64, 1.37689012_f64), + ]; + for (row, (ts, o, h, l, c)) in all_decoded.iter().zip(expected) { + assert_eq!(row.pair, FX_PAIR_USDCAD); + assert_eq!(row.source, FX_1M_SOURCE_EOD); + assert_eq!(row.ts, ts); + assert_eq!(row.open.to_bits(), o.to_bits()); + assert_eq!(row.high.to_bits(), h.to_bits()); + assert_eq!(row.low.to_bits(), l.to_bits()); + assert_eq!(row.close.to_bits(), c.to_bits()); + } + for pair in all_decoded.windows(2) { + assert!(pair[0].ts < pair[1].ts, "rows not strictly ascending by ts"); + } +} + +#[test] +fn cross_chunk_global_dedup_collapses_identical_and_drops_conflicts() { + let ts_collapse = 1_718_000_000_i64; + let ts_conflict = 1_718_000_060_i64; + let ts_unique = 1_718_000_120_i64; + + let docs = vec![ + // Chunk 1: first copy of collapse + first copy of conflict + make_intraday_doc(EOD_CAD_FOREX_CODE, ts_collapse, 1.3700, 1.3710, 1.3690, 1.3705, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts_conflict, 1.3705, 1.3715, 1.3700, 1.3710, 0.0), + // Intervening filler docs to push second copies into later chunks + make_intraday_doc("MSFT.US", ts_unique, 420.0, 421.0, 419.0, 420.5, 500.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts_unique, 1.3710, 1.3720, 1.3705, 1.3715, 0.0), + // Later chunks: identical duplicate of ts_collapse + conflicting duplicate of ts_conflict + make_intraday_doc(EOD_CAD_FOREX_CODE, ts_collapse, 1.3700, 1.3710, 1.3690, 1.3705, 99.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts_conflict, 1.3705, 1.3715, 1.3700, 1.3712, 0.0), + ]; + let intraday_bytes = concat_docs(&docs); + let doc_size = docs[0].as_bytes().len(); + + // Force at most 1 document per chunk so every document sits in its own BSON chunk. + let tiny_opts = BsonStreamOptions { + chunk_capacity_bytes: doc_size, + ..BsonStreamOptions::default() + }; + + // Explicitly verify that the duplicate pairs occupy distinct BSON chunks. + let mut chunk_reader = + RawBsonChunkReader::with_options(Cursor::new(&intraday_bytes), tiny_opts).unwrap(); + let mut chunk_idx = 0usize; + let mut collapse_chunks = Vec::new(); + let mut conflict_chunks = Vec::new(); + while let Some(chunk) = chunk_reader.next_chunk().unwrap() { + decode_eod_intraday_buffer( + chunk.bytes, + |raw| { + if raw.ts == ts_collapse * 1_000_000 { + collapse_chunks.push(chunk_idx); + } else if raw.ts == ts_conflict * 1_000_000 { + conflict_chunks.push(chunk_idx); + } + }, + |_offset, _err| {}, + ); + chunk_idx += 1; + } + assert!( + chunk_idx >= 5, + "expected >= 5 chunks for 6 docs with tiny chunk_capacity_bytes={doc_size}, got {chunk_idx}" + ); + assert_eq!(collapse_chunks.len(), 2); + assert_ne!( + collapse_chunks[0], collapse_chunks[1], + "identical duplicates must sit in distinct BSON chunks" + ); + assert_eq!(conflict_chunks.len(), 2); + assert_ne!( + conflict_chunks[0], conflict_chunks[1], + "conflicting duplicates must sit in distinct BSON chunks" + ); + + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let args = make_args( + PathBuf::from("in-memory-eodIntraday1M.bson"), + PathBuf::from("unused-out"), + 1, + tiny_opts, + ); + + let report = run_curate_fx_1m_with_readers(&args, Cursor::new(&intraday_bytes), writer) + .expect("cross-chunk dedup run should succeed"); + assert_report_conservation(&report); + assert_eq!(report.curate_stats.bars_in, 6); + assert_eq!(report.curate_stats.dropped_wrong_code, 1); + assert_eq!(report.curate_stats.duplicate_collapsed, 1); + assert_eq!(report.curate_stats.duplicate_conflict_dropped, 2); + assert_eq!(report.curate_stats.rows_out, 2); + assert_eq!(report.rows_written, 2); + + let decoded = decode_ilp_fx_1m(&sink); + assert_eq!(decoded.len(), 2); + assert_eq!(decoded[0].ts, ts_collapse * 1_000_000); + assert_eq!(decoded[0].close.to_bits(), 1.3705_f64.to_bits()); + assert_eq!(decoded[1].ts, ts_unique * 1_000_000); + assert_eq!(decoded[1].close.to_bits(), 1.3715_f64.to_bits()); +} + +#[test] +fn shuffled_input_produces_byte_identical_shards_and_identical_report() { + let dir = TempDirGuard::new("fx1m-shuffle"); + let ts1 = 1_718_100_000_i64; + let ts2 = 1_718_100_060_i64; + let ts3 = 1_718_100_120_i64; + let ts4 = 1_718_100_180_i64; + + let docs = vec![ + make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.3600, 1.3610, 1.3595, 1.3605, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.3600, 1.3610, 1.3595, 1.3605, 10.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3605, 1.3615, 1.3600, 1.3610, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3605, 1.3615, 1.3600, 1.3611, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts3, 1.3610, 1.3620, 1.3605, 1.3615, 0.0), + make_intraday_doc("NVDA.US", ts3, 120.0, 121.0, 119.0, 120.5, 1000.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts4, 1.3615, 1.3625, 1.3610, 1.3620, 0.0), + make_malformed_missing_open_doc(EOD_CAD_FOREX_CODE, ts4 + 60), + ]; + // Deterministic permutation. + let perm = [6, 3, 7, 1, 5, 0, 4, 2]; + let shuffled_docs: Vec = perm.iter().map(|&idx| docs[idx].clone()).collect(); + + let in_a = dir.path().join("in_a.bson"); + let in_b = dir.path().join("in_b.bson"); + fs::write(&in_a, concat_docs(&docs)).unwrap(); + fs::write(&in_b, concat_docs(&shuffled_docs)).unwrap(); + + let tiny_opts = BsonStreamOptions { + chunk_capacity_bytes: docs[0].as_bytes().len() * 2, + ..BsonStreamOptions::default() + }; + + let run = |input: PathBuf, out_name: &str| { + let out_dir = dir.path().join(out_name); + let args = make_args(input, out_dir.clone(), 4, tiny_opts); + let report = run_curate_fx_1m(&args).expect("run should succeed"); + let files: Vec<(String, Vec)> = list_dir_names(&out_dir) + .into_iter() + .map(|name| { + let bytes = fs::read(out_dir.join(&name)).unwrap(); + (name, bytes) + }) + .collect(); + (report, files) + }; + + let (mut r_a, f_a) = run(in_a, "out_a"); + let (mut r_b, f_b) = run(in_b, "out_b"); + assert_report_conservation(&r_a); + assert_eq!(f_a, f_b, "shuffled input produced different shard bytes"); + + r_a.elapsed_secs = 0.0; + r_b.elapsed_secs = 0.0; + assert_eq!(r_a, r_b, "shuffled input produced different report counters"); +} + +#[test] +fn shard_file_sets_for_one_and_four_shards_route_usdcad_deterministically() { + let dir = TempDirGuard::new("fx1m-shards"); + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write( + &intraday_path, + concat_docs(&[ + make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_200_000, 1.3700, 1.3710, 1.3690, 1.3705, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_200_060, 1.3705, 1.3715, 1.3700, 1.3710, 0.0), + ]), + ) + .unwrap(); + + // 1 shard: all USDCAD rows land in shard 00. + assert_eq!(shard_for_fx_pair(FX_PAIR_USDCAD, 1), 0); + let out1 = dir.path().join("out-1"); + let rep1 = run_curate_fx_1m(&make_args( + intraday_path.clone(), + out1.clone(), + 1, + BsonStreamOptions::default(), + )) + .unwrap(); + assert_report_conservation(&rep1); + assert_eq!(list_dir_names(&out1), vec!["fx_1m.shard-00.ilp"]); + assert_eq!(rep1.ilp_stats.per_shard_rows, vec![2]); + assert_eq!( + fs::read(out1.join("fx_1m.shard-00.ilp")).unwrap().len(), + rep1.ilp_stats.bytes + ); + + // 4 shards: all USDCAD rows land in shard 01; shards 00, 02, 03 exist and are empty. + assert_eq!(shard_for_fx_pair(FX_PAIR_USDCAD, 4), 1); + let out4 = dir.path().join("out-4"); + let rep4 = run_curate_fx_1m(&make_args( + intraday_path, + out4.clone(), + 4, + BsonStreamOptions::default(), + )) + .unwrap(); + assert_report_conservation(&rep4); + assert_eq!( + list_dir_names(&out4), + vec![ + "fx_1m.shard-00.ilp", + "fx_1m.shard-01.ilp", + "fx_1m.shard-02.ilp", + "fx_1m.shard-03.ilp", + ] + ); + assert_eq!(rep4.ilp_stats.per_shard_rows, vec![0, 2, 0, 0]); + for shard_idx in 0..4usize { + let bytes = fs::read(out4.join(format!("fx_1m.shard-{shard_idx:02}.ilp"))).unwrap(); + if shard_idx == 1 { + assert_eq!(bytes.len(), rep4.ilp_stats.bytes); + assert_eq!(decode_ilp_fx_1m(&bytes).len(), 2); + } else { + assert!(bytes.is_empty(), "shard {shard_idx:02} should be empty"); + } + } +} + +#[test] +fn empty_and_wrong_code_only_inputs_publish_empty_shard_files() { + let dir = TempDirGuard::new("fx1m-empty"); + + // 1. Empty BSON input + let empty_in = dir.path().join("empty.bson"); + fs::write(&empty_in, []).unwrap(); + let out_empty = dir.path().join("out-empty"); + let rep_empty = run_curate_fx_1m(&make_args( + empty_in, + out_empty.clone(), + 3, + BsonStreamOptions::default(), + )) + .expect("empty input should succeed"); + assert_report_conservation(&rep_empty); + assert_eq!(rep_empty.decode.docs_seen, 0); + assert_eq!(rep_empty.curate_stats.bars_in, 0); + assert_eq!(rep_empty.rows_written, 0); + assert_eq!(rep_empty.ilp_stats.bytes, 0); + assert_eq!(rep_empty.ilp_stats.per_shard_rows, vec![0, 0, 0]); + assert_eq!( + list_dir_names(&out_empty), + vec![ + "fx_1m.shard-00.ilp", + "fx_1m.shard-01.ilp", + "fx_1m.shard-02.ilp", + ] + ); + for idx in 0..3usize { + assert!( + fs::read(out_empty.join(format!("fx_1m.shard-{idx:02}.ilp"))) + .unwrap() + .is_empty() + ); + } + + // 2. Valid dump with zero CAD.FOREX rows + let other_in = dir.path().join("other_only.bson"); + fs::write( + &other_in, + concat_docs(&[ + make_intraday_doc("AAPL.US", 1_718_200_000, 195.0, 196.0, 194.5, 195.5, 100.0), + make_intraday_doc("EURUSD.FOREX", 1_718_200_060, 1.08, 1.09, 1.07, 1.085, 0.0), + ]), + ) + .unwrap(); + let out_other = dir.path().join("out-other"); + let rep_other = run_curate_fx_1m(&make_args( + other_in, + out_other.clone(), + 2, + BsonStreamOptions::default(), + )) + .expect("wrong-code-only input should succeed"); + assert_report_conservation(&rep_other); + assert_eq!(rep_other.decode.docs_seen, 2); + assert_eq!(rep_other.decode.rows_decoded, 2); + assert_eq!(rep_other.curate_stats.bars_in, 2); + assert_eq!(rep_other.curate_stats.dropped_wrong_code, 2); + assert_eq!(rep_other.rows_written, 0); + assert_eq!(rep_other.ilp_stats.bytes, 0); + assert_eq!( + list_dir_names(&out_other), + vec!["fx_1m.shard-00.ilp", "fx_1m.shard-01.ilp"] + ); + for idx in 0..2usize { + assert!( + fs::read(out_other.join(format!("fx_1m.shard-{idx:02}.ilp"))) + .unwrap() + .is_empty() + ); + } +} + +#[test] +fn fail_closed_validation_missing_input_truncated_bson_and_sink_errors() { + let dir = TempDirGuard::new("fx1m-fail-closed"); + let valid_doc = + make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_300_000, 1.3700, 1.3710, 1.3690, 1.3705, 0.0); + let valid_in = dir.path().join("valid.bson"); + fs::write(&valid_in, concat_docs(&[valid_doc.clone()])).unwrap(); + + // 1. shard_count == 0 + { + let out_dir = dir.path().join("out-zero-shards"); + let err = run_curate_fx_1m(&make_args( + valid_in.clone(), + out_dir.clone(), + 0, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!(matches!(err, RunCurateFx1mError::ZeroShardCount), "{err:?}"); + assert!(!out_dir.exists()); + } + + // 2. Invalid BsonStreamOptions (chunk_capacity_bytes == 0, max_doc_bytes < MIN_BSON_DOC_BYTES) + { + let out_dir = dir.path().join("out-zero-chunk-cap"); + let err = run_curate_fx_1m(&make_args( + valid_in.clone(), + out_dir.clone(), + 2, + BsonStreamOptions { + chunk_capacity_bytes: 0, + ..BsonStreamOptions::default() + }, + )) + .unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::BsonStream { + label: "eod-intraday", + source: BsonStreamError::InvalidChunkCapacity, + .. + } + ), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); + } + { + let out_dir = dir.path().join("out-small-max-doc"); + let err = run_curate_fx_1m(&make_args( + valid_in.clone(), + out_dir.clone(), + 2, + BsonStreamOptions { + max_doc_bytes: MIN_BSON_DOC_BYTES - 1, + ..BsonStreamOptions::default() + }, + )) + .unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::BsonStream { + label: "eod-intraday", + source: BsonStreamError::InvalidMaxDocBytes, + .. + } + ), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); + } + + // 3. Invalid IlpWriterOptions (max_batch_bytes == 0, max_batch_rows == 0) + { + let out_dir = dir.path().join("out-zero-batch-bytes"); + let mut args = make_args( + valid_in.clone(), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + ); + args.ilp_options.max_batch_bytes = 0; + let err = run_curate_fx_1m(&args).unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes)), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); + } + { + let out_dir = dir.path().join("out-zero-batch-rows"); + let mut args = make_args( + valid_in.clone(), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + ); + args.ilp_options.max_batch_rows = 0; + let err = run_curate_fx_1m(&args).unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchRows)), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); + } + + // 4. Writer shard_count mismatch in with_readers + { + let mut sink0 = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink0], IlpWriterOptions::default()).unwrap(); + let args = make_args( + valid_in.clone(), + dir.path().join("unused"), + 2, + BsonStreamOptions::default(), + ); + let err = run_curate_fx_1m_with_readers(&args, Cursor::new(b""), writer).unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::ShardCountMismatch { + expected: 2, + actual: 1 + } + ), + "{err:?}" + ); + } + + // 5. Missing input file fails before creating out_dir + { + let out_dir = dir.path().join("out-missing-input"); + let err = run_curate_fx_1m(&make_args( + dir.path().join("does-not-exist.bson"), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::OpenInput { label: "eod-intraday", .. }), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); + } + + // 6. out_dir exists as a regular file + { + let out_file = dir.path().join("out-is-file"); + fs::write(&out_file, b"not a dir").unwrap(); + let err = run_curate_fx_1m(&make_args( + valid_in.clone(), + out_file.clone(), + 2, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!(matches!(err, RunCurateFx1mError::InvalidOutDir { .. }), "{err:?}"); + assert_eq!(fs::read(&out_file).unwrap(), b"not a dir"); + } + + // 7. Truncated BSON mid-document after a valid CAD.FOREX bar + { + let doc2 = make_intraday_doc( + EOD_CAD_FOREX_CODE, + 1_718_300_060, + 1.3705, + 1.3715, + 1.3700, + 1.3710, + 0.0, + ); + let mut trunc_bytes = concat_docs(&[valid_doc.clone(), doc2]); + trunc_bytes.truncate(trunc_bytes.len() - 7); + let trunc_in = dir.path().join("truncated.bson"); + fs::write(&trunc_in, &trunc_bytes).unwrap(); + + let out_dir = dir.path().join("out-trunc"); + fs::create_dir_all(&out_dir).unwrap(); + let keep_path = out_dir.join("keep.txt"); + fs::write(&keep_path, b"keep-me").unwrap(); + + let err = run_curate_fx_1m(&make_args( + trunc_in, + out_dir.clone(), + 2, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::BsonStream { label: "eod-intraday", .. }), + "{err:?}" + ); + assert!(err.source().is_some()); + assert_eq!(list_dir_names(&out_dir), vec!["keep.txt"]); + assert_eq!(fs::read(&keep_path).unwrap(), b"keep-me"); + } + + // 8. Sink failure on write -> Ilp(Io), no final or temp files left + { + let out_dir = dir.path().join("out-write-fail"); + let mut args = make_args( + valid_in.clone(), + out_dir.clone(), + 1, + BsonStreamOptions::default(), + ); + args.ilp_options.max_batch_rows = 1; + let err = run_curate_fx_1m_to_dir_with_hooks( + &args, + Cursor::new(concat_docs(&[valid_doc.clone()])), + |_idx, _file| FailingWriteSink { + fail_on_write: true, + fail_on_flush: false, + }, + |_idx, _path| {}, + ) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::Io { .. })), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(list_dir_names(&out_dir).is_empty()); + } + + // 9. Sink failure on flush during finish() -> Ilp(Io), no final or temp files left + { + let out_dir = dir.path().join("out-flush-fail"); + let args = make_args( + valid_in, + out_dir.clone(), + 1, + BsonStreamOptions::default(), + ); + let err = run_curate_fx_1m_to_dir_with_hooks( + &args, + Cursor::new(concat_docs(&[valid_doc])), + |_idx, _file| FailingWriteSink { + fail_on_write: false, + fail_on_flush: true, + }, + |_idx, _path| {}, + ) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::Io { .. })), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(list_dir_names(&out_dir).is_empty()); + } +} + +#[test] +fn fail_closed_preexisting_shards_coexistence_and_post_preflight_rollback() { + let dir = TempDirGuard::new("fx1m-no-overwrite"); + let intraday_bytes = concat_docs(&[make_intraday_doc( + EOD_CAD_FOREX_CODE, + 1_718_400_000, + 1.3700, + 1.3710, + 1.3690, + 1.3705, + 0.0, + )]); + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write(&intraday_path, &intraday_bytes).unwrap(); + + // Case A: pre-existing fx_1m.shard-07.ilp with shard_count = 2 -> rejected, bytes preserved. + { + let out_dir = dir.path().join("out-stale-07"); + fs::create_dir_all(&out_dir).unwrap(); + let sentinel = b"stale-fx-shard-07"; + let stale_path = out_dir.join("fx_1m.shard-07.ilp"); + fs::write(&stale_path, sentinel).unwrap(); + + let err = run_curate_fx_1m(&make_args( + intraday_path.clone(), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &stale_path), + "{err:?}" + ); + assert_eq!(fs::read(&stale_path).unwrap(), sentinel); + assert_eq!(list_dir_names(&out_dir), vec!["fx_1m.shard-07.ilp"]); + } + + // Case B: pre-existing digit-only name of another width (fx_1m.shard-3.ilp) -> rejected. + { + let out_dir = dir.path().join("out-stale-width1"); + fs::create_dir_all(&out_dir).unwrap(); + let sentinel = b"stale-fx-shard-width1"; + let stale_path = out_dir.join("fx_1m.shard-3.ilp"); + fs::write(&stale_path, sentinel).unwrap(); + + let err = run_curate_fx_1m(&make_args( + intraday_path.clone(), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &stale_path), + "{err:?}" + ); + assert_eq!(fs::read(&stale_path).unwrap(), sentinel); + assert_eq!(list_dir_names(&out_dir), vec!["fx_1m.shard-3.ilp"]); + } + + // Case C: a pre-existing bars_1m shard in out_dir coexists untouched. + { + let out_dir = dir.path().join("out-coexist-bars"); + fs::create_dir_all(&out_dir).unwrap(); + let bars_sentinel = b"bars-1m-shard-00-untouched"; + let bars_path = out_dir.join("bars_1m.shard-00.ilp"); + fs::write(&bars_path, bars_sentinel).unwrap(); + + let rep = run_curate_fx_1m(&make_args( + intraday_path.clone(), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + )) + .expect("bars_1m shard should coexist untouched"); + assert_report_conservation(&rep); + assert_eq!(rep.rows_written, 1); + assert_eq!(fs::read(&bars_path).unwrap(), bars_sentinel); + assert_eq!( + list_dir_names(&out_dir), + vec![ + "bars_1m.shard-00.ilp", + "fx_1m.shard-00.ilp", + "fx_1m.shard-01.ilp", + ] + ); + } + + // Case D: post-preflight collision on shard 01 after shard 00 is linked. + // Shard 00 must be rolled back, staging files removed, external shard 01 untouched. + { + let out_dir = dir.path().join("out-race"); + let args = make_args( + intraday_path, + out_dir.clone(), + 3, + BsonStreamOptions::default(), + ); + let race_sentinel = b"concurrent-writer-fx-shard-01"; + let err = run_curate_fx_1m_to_dir_with_hooks( + &args, + Cursor::new(&intraday_bytes), + |_idx, file| SyncedBufFile::new(file), + |shard_idx, final_path| { + if shard_idx == 1 { + fs::write(final_path, race_sentinel).expect("inject concurrent final shard"); + } + }, + ) + .unwrap_err(); + let expected_race_path = out_dir.join("fx_1m.shard-01.ilp"); + assert!( + matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &expected_race_path), + "{err:?}" + ); + assert_eq!(fs::read(&expected_race_path).unwrap(), race_sentinel); + assert_eq!(list_dir_names(&out_dir), vec!["fx_1m.shard-01.ilp"]); + } +} + +#[test] +fn format_curate_fx_1m_report_includes_every_counter_and_isolates_timing() { + let report = CurateFx1mRunReport { + decode: BsonEodIntradayDecodeStats { + docs_seen: 100, + rows_decoded: 90, + rejected_missing_field: 1, + rejected_empty_field: 2, + rejected_wrong_type: 3, + rejected_invalid_timestamp: 1, + rejected_invalid_number: 2, + rejected_corrupt_document: 1, + }, + curate_stats: CurateFx1mStats { + bars_in: 90, + rows_out: 50, + dropped_wrong_code: 20, + dropped_negative_ts: 1, + dropped_invalid_ohlc: 2, + dropped_high_below_bound: 3, + dropped_low_above_bound: 4, + duplicate_collapsed: 5, + duplicate_conflict_dropped: 5, + }, + rows_written: 50, + ilp_stats: IlpWriteStats { + rows: 50, + bytes: 4096, + flushes: 2, + per_shard_rows: vec![0, 50, 0, 0], + }, + shard_count: 4, + elapsed_secs: 0.123456, + }; + assert_report_conservation(&report); + + let formatted = format_curate_fx_1m_report(&report); + let lines: Vec<&str> = formatted.lines().collect(); + assert_eq!(lines.len(), 5, "expected 5 report lines, got:\n{formatted}"); + assert_eq!(lines[0], "curate-etl curate-fx-1m"); + assert!( + lines[1].contains("docs_seen=100") + && lines[1].contains("rows_decoded=90") + && lines[1].contains("rejected=10") + && lines[1].contains("missing=1") + && lines[1].contains("empty=2") + && lines[1].contains("wrong_type=3") + && lines[1].contains("invalid_ts=1") + && lines[1].contains("invalid_num=2") + && lines[1].contains("corrupt=1"), + "missing decode counters in line 1: {}", + lines[1] + ); + assert!( + lines[2].contains("bars_in=90") + && lines[2].contains("rows_out=50") + && lines[2].contains("wrong_code=20") + && lines[2].contains("negative_ts=1") + && lines[2].contains("invalid_ohlc=2") + && lines[2].contains("high_below_bound=3") + && lines[2].contains("low_above_bound=4") + && lines[2].contains("dup_collapsed=5") + && lines[2].contains("dup_conflict_dropped=5"), + "missing curate counters in line 2: {}", + lines[2] + ); + assert!( + lines[3].contains("shards=4") + && lines[3].contains("rows_written=50") + && lines[3].contains("ilp_rows=50") + && lines[3].contains("bytes=4096") + && lines[3].contains("flushes=2") + && lines[3].contains("per_shard_rows=00=0,01=50,02=0,03=0"), + "missing ilp counters in line 3: {}", + lines[3] + ); + assert_eq!(lines[4].trim(), "timing: elapsed_secs=0.123456"); + // Ensure elapsed_secs appears only on the timing line. + for line in &lines[..4] { + assert!(!line.contains("elapsed_secs"), "timing leaked into: {line}"); + } +} + +struct PanicOnRead; + +impl io::Read for PanicOnRead { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + panic!("intraday reader must not be read when writer preflight fails"); + } +} + +#[test] +fn with_readers_rejects_preloaded_writer_with_queued_or_flushed_rows_before_reading() { + use crate::bson_eod_intraday::RawEodIntradayBar; + + let make_bar = |ts_sec: i64| RawEodIntradayBar { + eod_search_code: EOD_CAD_FOREX_CODE, + ts: ts_sec * 1_000_000, + open: 1.3700, + high: 1.3710, + low: 1.3690, + close: 1.3705, + volume: 0.0, + }; + + let args = make_args( + PathBuf::from("preloaded-check.bson"), + PathBuf::from("unused-out"), + 1, + BsonStreamOptions::default(), + ); + + // Case 1: queued-only row (buffered, not yet flushed). + { + let mut sink = Vec::new(); + let mut writer = + IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + curate_and_write_fx_1m([make_bar(1_718_500_000)], &mut writer).unwrap(); + + let err = run_curate_fx_1m_with_readers(&args, PanicOnRead, writer).unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::NonEmptyWriter { + flushed_rows: 0, + pending_rows: 1 + } + ), + "{err:?}" + ); + assert!(err.source().is_none()); + let msg = err.to_string(); + assert!(msg.contains("0 flushed") && msg.contains("1 pending"), "{msg}"); + } + + // Case 2: flushed-only row (max_batch_rows = 1 flushes immediately, pending == 0). + { + let mut sink = Vec::new(); + let mut writer = IlpShardedWriter::new( + vec![&mut sink], + IlpWriterOptions { + max_batch_rows: 1, + ..IlpWriterOptions::default() + }, + ) + .unwrap(); + curate_and_write_fx_1m([make_bar(1_718_500_000)], &mut writer).unwrap(); + + let err = run_curate_fx_1m_with_readers(&args, PanicOnRead, writer).unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::NonEmptyWriter { + flushed_rows: 1, + pending_rows: 0 + } + ), + "{err:?}" + ); + } + + // Case 3: both flushed and queued rows (max_batch_rows = 2 with 3 bars -> 2 flushed, 1 pending). + { + let mut sink = Vec::new(); + let mut writer = IlpShardedWriter::new( + vec![&mut sink], + IlpWriterOptions { + max_batch_rows: 2, + ..IlpWriterOptions::default() + }, + ) + .unwrap(); + curate_and_write_fx_1m( + [ + make_bar(1_718_500_000), + make_bar(1_718_500_060), + make_bar(1_718_500_120), + ], + &mut writer, + ) + .unwrap(); + + let err = run_curate_fx_1m_with_readers(&args, PanicOnRead, writer).unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::NonEmptyWriter { + flushed_rows: 2, + pending_rows: 1 + } + ), + "{err:?}" + ); + } +} + +#[test] +fn file_mode_reports_staging_unlink_failures_with_paths_on_flush_error() { + let dir = TempDirGuard::new("fx1m-staging-unlink-fail"); + let valid_doc = + make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_600_000, 1.3700, 1.3710, 1.3690, 1.3705, 0.0); + let out_dir = dir.path().join("out"); + let args = make_args( + dir.path().join("in-memory.bson"), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + ); + + let err = run_curate_fx_1m_to_dir_with_cleanup_hook( + &args, + Cursor::new(concat_docs(&[valid_doc])), + |shard_idx, file| { + if shard_idx == 0 { + Box::new(FailingWriteSink { + fail_on_write: false, + fail_on_flush: true, + }) as Box + } else { + Box::new(SyncedBufFile::new(file)) as Box + } + }, + |_shard_idx, _final_path| {}, + |tmp_path| { + let name = tmp_path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); + if name.starts_with(".fx_1m.shard-01.") { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "injected staging unlink failure", + )) + } else { + fs::remove_file(tmp_path) + } + }, + ) + .unwrap_err(); + + let rendered = err.to_string(); + assert!(err.source().is_some(), "RollbackFailed must expose original cause"); + + match err { + RunCurateFx1mError::RollbackFailed { cause, failures } => { + assert!( + matches!( + cause.as_ref(), + RunCurateFx1mError::Ilp(IlpWriterError::Io { shard: 0, .. }) + ), + "unexpected original cause: {cause:?}" + ); + assert_eq!(failures.len(), 1, "expected 1 staging unlink failure: {failures:?}"); + let failure = &failures[0]; + assert!(failure.backup_path.is_none()); + assert_eq!(failure.source.kind(), io::ErrorKind::PermissionDenied); + + let surviving_name = failure + .final_path + .file_name() + .and_then(|n| n.to_str()) + .expect("staging file name"); + assert!( + surviving_name.starts_with(".fx_1m.shard-01.") && surviving_name.ends_with(".tmp"), + "unexpected surviving staging name: {surviving_name}" + ); + assert!( + failure.final_path.exists(), + "surviving staging file should still exist on disk" + ); + // Shard 0's staging file was cleaned up and zero final shard files were created. + assert_eq!(list_dir_names(&out_dir), vec![surviving_name]); + + assert!( + rendered.contains("injected flush failure"), + "rendered error missing original flush cause: {rendered}" + ); + assert!( + rendered.contains(&failure.final_path.display().to_string()), + "rendered error missing surviving staging path: {rendered}" + ); + assert!( + rendered.contains("injected staging unlink failure"), + "rendered error missing unlink failure detail: {rendered}" + ); + } + other => panic!("expected RollbackFailed, got {other:?}"), + } +} + +// --------------------------------------------------------------------------------------------- +// QA edge cases (T-183) +// --------------------------------------------------------------------------------------------- + +fn snapshot_dir(dir: &Path) -> Vec<(String, Vec)> { + list_dir_names(dir) + .into_iter() + .map(|name| { + let bytes = fs::read(dir.join(&name)).unwrap(); + (name, bytes) + }) + .collect() +} + +#[test] +fn rerun_into_published_out_dir_fails_closed_and_preserves_first_run_bytes() { + let dir = TempDirGuard::new("fx1m-qa-rerun"); + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write( + &intraday_path, + concat_docs(&[ + make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_700_000, 1.37, 1.371, 1.369, 1.3705, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_700_060, 1.3705, 1.3715, 1.37, 1.371, 0.0), + ]), + ) + .unwrap(); + let out_dir = dir.path().join("out"); + let args = make_args(intraday_path, out_dir.clone(), 2, BsonStreamOptions::default()); + + let first = run_curate_fx_1m(&args).expect("first run succeeds"); + assert_eq!(first.rows_written, 2); + let before = snapshot_dir(&out_dir); + assert_eq!( + before.iter().map(|(n, _)| n.as_str()).collect::>(), + vec!["fx_1m.shard-00.ilp", "fx_1m.shard-01.ilp"] + ); + + let err = run_curate_fx_1m(&args).unwrap_err(); + let expected = out_dir.join("fx_1m.shard-00.ilp"); + assert!( + matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &expected), + "{err:?}" + ); + assert_eq!(snapshot_dir(&out_dir), before, "rerun must not touch published shards"); +} + +#[test] +fn preflight_is_table_scoped_and_ignores_non_shard_names() { + let dir = TempDirGuard::new("fx1m-qa-preflight-scope"); + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write( + &intraday_path, + concat_docs(&[make_intraday_doc( + EOD_CAD_FOREX_CODE, + 1_718_800_000, + 1.37, + 1.371, + 1.369, + 1.3705, + 0.0, + )]), + ) + .unwrap(); + let out_dir = dir.path().join("out"); + fs::create_dir_all(&out_dir).unwrap(); + // None of these are `fx_1m.shard-.ilp`, so they must not block the run. + let bystanders = [ + "fx_1m.shard-.ilp", + "fx_1m.shard-0a.ilp", + "fx_1m.shard-00.ilp.bak", + "xfx_1m.shard-00.ilp", + ".fx_1m.shard-00.stale.tmp", + "bars_1m.shard-00.ilp", + "bars_1m.shard-7.ilp", + ]; + for name in bystanders { + fs::write(out_dir.join(name), name.as_bytes()).unwrap(); + } + + let report = run_curate_fx_1m(&make_args( + intraday_path, + out_dir.clone(), + 1, + BsonStreamOptions::default(), + )) + .expect("non-shard names must not trip fx_1m preflight"); + assert_eq!(report.rows_written, 1); + for name in bystanders { + assert_eq!(fs::read(out_dir.join(name)).unwrap(), name.as_bytes(), "{name} touched"); + } + let mut expected: Vec = bystanders.iter().map(|s| s.to_string()).collect(); + expected.push("fx_1m.shard-00.ilp".to_string()); + expected.sort(); + assert_eq!(list_dir_names(&out_dir), expected); + + // The parameterised matcher must not leak across tables (bars_1m regression guard). + use crate::ilp::TABLE_BARS_1M; + use crate::run_curate_bars_1m::is_final_shard_file_name_for_table; + use std::ffi::OsStr; + assert!(is_final_shard_file_name_for_table(TABLE_FX_1M, OsStr::new("fx_1m.shard-123.ilp"))); + assert!(!is_final_shard_file_name_for_table(TABLE_BARS_1M, OsStr::new("fx_1m.shard-00.ilp"))); + assert!(!is_final_shard_file_name_for_table(TABLE_FX_1M, OsStr::new("bars_1m.shard-00.ilp"))); + assert!(preflight_shard_out_dir(&out_dir, TABLE_BARS_1M).is_err()); + let fx_only = dir.path().join("fx-only"); + fs::create_dir_all(&fx_only).unwrap(); + fs::write(fx_only.join("fx_1m.shard-00.ilp"), b"x").unwrap(); + assert!( + preflight_shard_out_dir(&fx_only, TABLE_BARS_1M).is_ok(), + "fx_1m shards must not block a bars_1m run" + ); +} + +#[test] +fn with_readers_truncated_dump_keeps_path_and_emits_nothing_to_sinks() { + let valid = make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_900_000, 1.37, 1.371, 1.369, 1.3705, 0.0); + let mut bytes = concat_docs(&[valid.clone(), valid]); + let first_len = bytes.len() / 2; + bytes.truncate(bytes.len() - 3); + + let mut sink0 = Vec::new(); + let mut sink1 = Vec::new(); + let writer = + IlpShardedWriter::new(vec![&mut sink0, &mut sink1], IlpWriterOptions::default()).unwrap(); + let path = PathBuf::from("/dumps/eodIntraday1M.bson"); + let args = make_args(path.clone(), PathBuf::from("unused"), 2, BsonStreamOptions::default()); + + let err = run_curate_fx_1m_with_readers(&args, Cursor::new(bytes), writer).unwrap_err(); + match &err { + RunCurateFx1mError::BsonStream { label, path: p, .. } => { + assert_eq!(*label, "eod-intraday"); + assert_eq!(p, &path); + } + other => panic!("expected BsonStream, got {other:?}"), + } + let rendered = err.to_string(); + assert!(rendered.contains("/dumps/eodIntraday1M.bson"), "{rendered}"); + assert!(rendered.contains(&first_len.to_string()), "offset missing: {rendered}"); + // The stage only writes after clean EOF, so a fatal stream error leaves sinks untouched. + assert!(sink0.is_empty() && sink1.is_empty()); +} + +#[test] +fn three_digit_shard_indices_keep_min_width_two_naming() { + let dir = TempDirGuard::new("fx1m-qa-wide"); + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write( + &intraday_path, + concat_docs(&[make_intraday_doc( + EOD_CAD_FOREX_CODE, + 1_719_000_000, + 1.37, + 1.371, + 1.369, + 1.3705, + 0.0, + )]), + ) + .unwrap(); + let out_dir = dir.path().join("out"); + let shard_count = 101usize; + let report = run_curate_fx_1m(&make_args( + intraday_path, + out_dir.clone(), + shard_count, + BsonStreamOptions::default(), + )) + .unwrap(); + assert_report_conservation(&report); + + let mut expected: Vec = + (0..shard_count).map(|i| format!("fx_1m.shard-{i:02}.ilp")).collect(); + expected.sort(); + assert_eq!(list_dir_names(&out_dir), expected); + assert!(list_dir_names(&out_dir).contains(&"fx_1m.shard-100.ilp".to_string())); + + let target = shard_for_fx_pair(FX_PAIR_USDCAD, shard_count); + for i in 0..shard_count { + let len = fs::metadata(out_dir.join(format!("fx_1m.shard-{i:02}.ilp"))).unwrap().len(); + assert_eq!(len > 0, i == target, "shard {i} non-empty mismatch (target {target})"); + assert_eq!(report.ilp_stats.per_shard_rows[i], usize::from(i == target)); + } +} + +/// Streams `n` generated non-FX docs followed by FX docs without materialising the dump. +struct GeneratedDump { + docs: std::vec::IntoIter>, + current: Vec, + pos: usize, +} + +impl io::Read for GeneratedDump { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + while self.pos == self.current.len() { + match self.docs.next() { + Some(next) => { + self.current = next; + self.pos = 0; + } + None => return Ok(0), + } + } + let n = buf.len().min(self.current.len() - self.pos); + buf[..n].copy_from_slice(&self.current[self.pos..self.pos + n]); + self.pos += n; + Ok(n) + } +} + +#[test] +fn many_wrong_code_docs_across_tiny_chunks_are_only_counted() { + let wrong = make_intraday_doc("AAPL.US", 1_719_100_000, 195.0, 196.0, 194.5, 195.5, 1.0); + let fx_a = make_intraday_doc(EOD_CAD_FOREX_CODE, 1_719_100_060, 1.37, 1.371, 1.369, 1.3705, 0.0); + let fx_b = make_intraday_doc(EOD_CAD_FOREX_CODE, 1_719_100_000, 1.36, 1.361, 1.359, 1.3605, 0.0); + let n_wrong = 20_000usize; + let mut docs: Vec> = vec![fx_a.as_bytes().to_vec()]; + docs.extend(std::iter::repeat_n(wrong.as_bytes().to_vec(), n_wrong)); + docs.push(fx_b.as_bytes().to_vec()); + let reader = GeneratedDump { + docs: docs.into_iter(), + current: Vec::new(), + pos: 0, + }; + + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let opts = BsonStreamOptions { + chunk_capacity_bytes: wrong.as_bytes().len() * 4, + ..BsonStreamOptions::default() + }; + let args = make_args(PathBuf::from("gen.bson"), PathBuf::from("unused"), 1, opts); + let report = run_curate_fx_1m_with_readers(&args, reader, writer).unwrap(); + assert_report_conservation(&report); + assert_eq!(report.decode.docs_seen, n_wrong + 2); + assert_eq!(report.curate_stats.dropped_wrong_code, n_wrong); + assert_eq!(report.rows_written, 2); + + // Rows separated by 20k wrong-code docs across many chunks are still globally sorted. + let rows = decode_ilp_fx_1m(&sink); + assert_eq!( + rows.iter().map(|r| r.ts).collect::>(), + vec![1_719_100_000_000_000, 1_719_100_060_000_000] + ); +} + +#[test] +fn error_display_is_single_line_and_names_paths() { + let errs = [ + RunCurateFx1mError::ZeroShardCount, + RunCurateFx1mError::ShardCountMismatch { expected: 2, actual: 1 }, + RunCurateFx1mError::NonEmptyWriter { flushed_rows: 3, pending_rows: 4 }, + RunCurateFx1mError::InvalidOutDir { + path: PathBuf::from("/o/d"), + detail: "not a dir".into(), + }, + RunCurateFx1mError::OutputFileExists { path: PathBuf::from("/o/fx_1m.shard-00.ilp") }, + RunCurateFx1mError::OpenInput { + label: "eod-intraday", + path: PathBuf::from("/i/x.bson"), + source: io::Error::new(io::ErrorKind::NotFound, "nf"), + }, + RunCurateFx1mError::Io { + path: PathBuf::from("/o/tmp"), + source: io::Error::other("boom"), + }, + ]; + for err in &errs { + let s = err.to_string(); + assert!(!s.is_empty() && !s.contains('\n'), "bad display: {s:?}"); + } + assert!(errs[2].to_string().contains("3 flushed") && errs[2].to_string().contains("4 pending")); + assert!(errs[3].to_string().contains("/o/d")); + assert!(errs[4].to_string().contains("/o/fx_1m.shard-00.ilp")); + assert!(errs[5].to_string().contains("/i/x.bson")); + assert!(errs[6].to_string().contains("/o/tmp")); +} + +// --------------------------------------------------------------------------------------------- +// QA: CLI wiring parity (T-187) +// --------------------------------------------------------------------------------------------- + +fn run_via_cli(argv: &[&str]) -> CurateFx1mRunReport { + let args: Vec = argv.iter().map(|s| (*s).to_string()).collect(); + match crate::cli::parse_args(&args).expect("curate-fx-1m argv should parse") { + crate::cli::CliAction::CurateFx1m(parsed) => { + run_curate_fx_1m(&parsed).expect("CLI-parsed run should succeed") + } + other => panic!("expected CliAction::CurateFx1m, got {other:?}"), + } +} + +fn assert_reports_equal_ignoring_elapsed(a: &CurateFx1mRunReport, b: &CurateFx1mRunReport) { + assert_eq!(a.decode, b.decode); + assert_eq!(a.curate_stats, b.curate_stats); + assert_eq!(a.rows_written, b.rows_written); + assert_eq!(a.ilp_stats, b.ilp_stats); + assert_eq!(a.shard_count, b.shard_count); +} + +#[test] +fn cli_parsed_curate_fx_1m_matches_direct_runner_bytes_and_counters() { + let dir = TempDirGuard::new("fx1m-qa-cli-parity"); + let ts1 = 1_718_700_000_i64; // 2024-06-18 08:40:00 UTC + let ts2 = ts1 + 60; + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write( + &intraday_path, + concat_docs(&[ + make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3705, 1.3715, 1.37, 1.371, 0.0), + make_intraday_doc("AAPL.US", ts1, 195.0, 196.0, 194.5, 195.5, 1000.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.37, 1.371, 1.369, 1.3705, 0.0), + // Bitwise-identical duplicate collapses. + make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.37, 1.371, 1.369, 1.3705, 0.0), + ]), + ) + .unwrap(); + let intraday = intraday_path.to_str().unwrap().to_string(); + + // Reference: runner with hand-built args and default options. + let direct_out = dir.path().join("direct"); + let direct = run_curate_fx_1m(&make_args( + intraday_path.clone(), + direct_out.clone(), + 4, + BsonStreamOptions::default(), + )) + .expect("direct run succeeds"); + assert_eq!(direct.rows_written, 2); + assert_eq!(direct.curate_stats.dropped_wrong_code, 1); + + // CLI space form. + let space_out = dir.path().join("cli-space"); + let space_out_s = space_out.to_str().unwrap().to_string(); + let via_space = run_via_cli(&[ + "curate-fx-1m", + "--eod-intraday", + &intraday, + "--out", + &space_out_s, + "--shards", + "4", + ]); + + // CLI equals form, flags reordered. + let eq_out = dir.path().join("cli-eq"); + let shards_tok = "--shards=4".to_string(); + let out_tok = format!("--out={}", eq_out.to_str().unwrap()); + let intraday_tok = format!("--eod-intraday={intraday}"); + let via_eq = run_via_cli(&["curate-fx-1m", &shards_tok, &out_tok, &intraday_tok]); + + assert_reports_equal_ignoring_elapsed(&via_space, &direct); + assert_reports_equal_ignoring_elapsed(&via_eq, &direct); + + let expected_names: Vec = (0..4).map(|i| format!("fx_1m.shard-{i:02}.ilp")).collect(); + let direct_snapshot = snapshot_dir(&direct_out); + assert_eq!( + direct_snapshot + .iter() + .map(|(n, _)| n.clone()) + .collect::>(), + expected_names + ); + assert_eq!(snapshot_dir(&space_out), direct_snapshot); + assert_eq!(snapshot_dir(&eq_out), direct_snapshot); + + // Exactly one populated shard carrying USDCAD/eod rows at UTC bar-start micros. + let rows: Vec = direct_snapshot + .iter() + .flat_map(|(_, bytes)| decode_ilp_fx_1m(bytes)) + .collect(); + let populated = direct_snapshot + .iter() + .filter(|(_, b)| !b.is_empty()) + .count(); + assert_eq!(populated, 1); + assert_eq!( + rows.iter().map(|r| r.ts).collect::>(), + vec![ts1 * 1_000_000, ts2 * 1_000_000] + ); + for row in &rows { + assert_eq!(row.pair, FX_PAIR_USDCAD); + assert_eq!(row.source, FX_1M_SOURCE_EOD); + } + assert_eq!(rows[0].close.to_bits(), 1.3705_f64.to_bits()); +} + +#[test] +fn cli_parsed_curate_fx_1m_missing_input_fails_without_publishing_shards() { + let dir = TempDirGuard::new("fx1m-qa-cli-missing"); + let missing = dir.path().join("does-not-exist.bson"); + let out_dir = dir.path().join("out"); + let args: Vec = [ + "curate-fx-1m", + "--eod-intraday", + missing.to_str().unwrap(), + "--out", + out_dir.to_str().unwrap(), + "--shards", + "2", + ] + .iter() + .map(|s| (*s).to_string()) + .collect(); + let crate::cli::CliAction::CurateFx1m(parsed) = crate::cli::parse_args(&args).unwrap() else { + panic!("expected CliAction::CurateFx1m"); + }; + let err = run_curate_fx_1m(&parsed).unwrap_err(); + assert!(err.to_string().contains("does-not-exist.bson"), "{err}"); + let leftover: Vec = list_dir_names(&out_dir) + .into_iter() + .filter(|n| n.starts_with("fx_1m.")) + .collect(); + assert!( + leftover.is_empty(), + "no shard output expected: {leftover:?}" + ); +} diff --git a/tools/curate-etl/src/run_curate_qm_bars_1m.rs b/tools/curate-etl/src/run_curate_qm_bars_1m.rs new file mode 100644 index 00000000..0d6ec861 --- /dev/null +++ b/tools/curate-etl/src/run_curate_qm_bars_1m.rs @@ -0,0 +1,643 @@ +//! Bounded-memory file-to-file `qmIntraday` -> `bars_1m` runner (`M2.3m`). +//! +//! Streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column +//! `provider_mapping.tsv` into per-shard QuestDB ILP v2 files +//! (`/bars_1m_qm.shard-.ilp`) via [`crate::curate_qm_bars_1m`]. +//! +//! # Bounded-Memory Chunking & Zero Split Un-Adjustment +//! - Drives [`RawBsonChunkReader::with_options`], [`RawBsonChunkReader::next_chunk`], and +//! [`decode_qm_intraday_buffer`] directly—the exact reader and buffer decoder wrapped by +//! `crate::bson_stream::decode_qm_intraday_chunks`, whose callback API hides chunk boundaries. +//! - Each framed chunk is decoded into a chunk-local `Vec>` borrowing +//! `qmSearchCode` directly from the chunk slice, then curated per chunk via +//! [`curate_and_write_qm_bars_1m`] against one shared [`IlpShardedWriter`]. Borrows are +//! consumed before advancing the chunk reader. +//! - Takes no splits input: `qmIntraday` raw fields (`open..close`, `sharevolume`) are already +//! un-adjusted (`design/DATA-CONTRACTS.md` §1) and pass through bit-identical (aside from +//! `-0.0 -> +0.0` volume normalization). +//! - [`IlpShardedWriter::finish`] is called exactly once after clean EOF. +//! - Peak memory is bounded by the `provider_mapping` table, the current BSON chunk +//! (`BsonStreamOptions::chunk_capacity_bytes`, growing only for a single document up to +//! `max_doc_bytes`), that chunk's curation buffers, and one ILP batch buffer per shard— +//! independent of the total `qmIntraday` input size. +//! +//! # Cross-Chunk Semantics, Output Naming & Reporting +//! - Collision collapse/drop in `curate_qm_bars_1m` and row ordering apply **per chunk**: output +//! is sorted by `(listing_id, ts)` within each chunk, and the same `(listing_id, ts)` appearing +//! in two different chunks is emitted twice (with zero within-chunk collapse between them) and +//! relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. +//! - `CurateQmBars1mRunReport::curate_stats` sums every field of [`CurateBars1mStats`] and its +//! nested [`crate::bars_1m::Bars1mStats`] across chunks. In particular, +//! `curate_stats.listings_out` and `curate_stats.builder.keys_out` are **sums of per-chunk +//! counts**, not global distinct counts. +//! - Output files use the distinct shard prefix `bars_1m_qm` (`bars_1m_qm.shard-.ilp`) so a +//! QM run can share `out_dir` with `run_curate_bars_1m` (`bars_1m.shard-.ilp`) without +//! tripping either preflight, while every emitted ILP v2 row still targets QuestDB table +//! `bars_1m` (`TABLE_BARS_1M`) with `source=qm_raw` (`BARS_1M_SOURCE_QM`). +//! - `mapping_source` is caller-supplied and forwarded verbatim to `curate_and_write_qm_bars_1m` +//! after rejecting empty or whitespace-only values (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`). +//! - `known_at_micros` is a caller-supplied run timestamp written verbatim to every ILP row's +//! `known_at` column; it supplies no evidence of earlier market availability. +//! +//! # File Publication & Fail-Closed Guarantees +//! - Preflight scans `out_dir` for **any** pre-existing `bars_1m_qm.shard-.ilp` file +//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards +//! from a prior larger-shard-count run cannot survive alongside a new export. +//! - Each shard writes into an exclusively created staging file in `out_dir` +//! (`.bars_1m_qm.shard-..tmp`), flushes and `sync_all`s on `finish`, and publishes +//! to `bars_1m_qm.shard-.ilp` via same-directory `hard_link` followed by removing the staged +//! name (preserving no-overwrite semantics even if a final file appears after preflight). +//! - Any error (validation, missing/malformed inputs, fatal BSON framing/I/O, ILP write/flush, or +//! publication collision) drops open sinks, rolls back only final files created by this run, +//! removes this run's staging files, and leaves pre-existing files untouched. Per-document +//! semantic decode errors stay counted-and-skipped in [`BsonQmIntradayDecodeStats`]. + +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use crate::bars_1m::EodIntradayBar; +use crate::bson_qm_intraday::{decode_qm_intraday_buffer, BsonQmIntradayDecodeStats}; +use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader}; +use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteError}; +use crate::curate_qm_bars_1m::curate_and_write_qm_bars_1m; +use crate::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions}; +use crate::parquet_bars::RollbackFailure; +use crate::parquet_publish::{next_run_id, StagingFileGuard}; +use crate::provider_mapping::ProviderMappingTable; +use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; +use crate::run_curate_bars_1m::{ + add_curate_bars_1m_stats, create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir, + publish_staged_shards_for_table, ShardPublishError, SyncedBufFile, +}; +use crate::run_curate_fx_1m::cleanup_armed_staged_shards; + +/// Default `provider_mapping` source namespace for `qmSearchCode` rows in `qmIntraday`. +pub const DEFAULT_QM_BARS_1M_MAPPING_SOURCE: &str = "qm"; + +/// Output filename prefix for QM intraday shard files (`bars_1m_qm.shard-.ilp`). +/// +/// Distinct from `TABLE_BARS_1M` (`bars_1m`) so QM and EOD intraday exports can share `out_dir` +/// without colliding in preflight or publication while both emit ILP v2 rows into `bars_1m`. +const QM_BARS_1M_SHARD_PREFIX: &str = "bars_1m_qm"; + +/// Arguments for [`run_curate_qm_bars_1m`] and [`run_curate_qm_bars_1m_with_readers`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateQmBars1mArgs { + pub intraday_path: PathBuf, + pub provider_mapping_path: PathBuf, + pub out_dir: PathBuf, + pub mapping_source: String, + pub shard_count: usize, + pub known_at_micros: i64, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +/// Full run report produced by [`run_curate_qm_bars_1m`] and +/// [`run_curate_qm_bars_1m_with_readers`]. +/// +/// Conservation invariants: +/// - `intraday_docs_framed as usize == intraday_decode.docs_seen` +/// - `intraday_decode.docs_seen == intraday_decode.rows_decoded + intraday_decode.rejected_total()` +/// - `intraday_decode.rows_decoded == curate_stats.builder.bars_in` +/// - `curate_stats.rows_in == curate_stats.builder.rows_out` +/// - `curate_stats.rows_in == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped` +/// - `curate_stats.pre_rows_out + curate_stats.rth_rows_out + curate_stats.post_rows_out == curate_stats.rows_out` +/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::()` +/// +/// Note: `curate_stats.listings_out` and `curate_stats.builder.keys_out` are summed across chunks +/// (not global distinct counts). +#[derive(Debug, Clone, PartialEq)] +pub struct CurateQmBars1mRunReport { + pub intraday_docs_framed: u64, + pub intraday_bytes_read: u64, + pub intraday_decode: BsonQmIntradayDecodeStats, + pub chunks: usize, + pub max_rows_per_chunk: usize, + pub curate_stats: CurateBars1mStats, + pub rows_written: usize, + pub ilp_stats: IlpWriteStats, + pub shard_count: usize, + pub elapsed_secs: f64, +} + +/// Typed errors returned by [`run_curate_qm_bars_1m`] and [`run_curate_qm_bars_1m_with_readers`]. +#[derive(Debug)] +pub enum RunCurateQmBars1mError { + /// `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, + /// `shard_count` was `0`. + ZeroShardCount, + /// `out_dir` exists and is not a directory. + InvalidOutDir { path: PathBuf, detail: String }, + /// A final shard output file (`bars_1m_qm.shard-.ilp`) already existed. + OutputFileExists { path: PathBuf }, + /// Failed to open the input `qmIntraday` dump file. + OpenInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + /// Failed to load `provider_mapping.tsv` via the shared reference loader. + LoadReference(RunCurateBarsError), + /// Fatal BSON framing, option validation, or I/O error while reading `qmIntraday`. + BsonStream { + label: &'static str, + path: PathBuf, + source: BsonStreamError, + }, + /// Curation or per-row ILP write error inside the per-chunk `qmIntraday` curation stage. + CurateWrite(CurateBars1mWriteError), + /// ILP writer initialization or final flush error. + Ilp(IlpWriterError), + /// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files. + Io { path: PathBuf, source: io::Error }, + /// Publication or failure cleanup failed and removing one or more final or staging files also + /// failed. + RollbackFailed { + cause: Box, + failures: Vec, + }, +} + +impl From for RunCurateQmBars1mError { + fn from(err: ShardPublishError) -> Self { + match err { + ShardPublishError::InvalidOutDir { path, detail } => { + Self::InvalidOutDir { path, detail } + } + ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path }, + ShardPublishError::Io { path, source } => Self::Io { path, source }, + ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed { + cause: Box::new((*cause).into()), + failures, + }, + } + } +} + +impl fmt::Display for RunCurateQmBars1mError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyMappingSource => write!(f, "mapping_source must not be empty or blank"), + Self::ZeroShardCount => write!(f, "shard_count must be >= 1"), + Self::InvalidOutDir { path, detail } => { + write!(f, "invalid out_dir '{}': {detail}", path.display()) + } + Self::OutputFileExists { path } => write!( + f, + "refusing to overwrite existing output file '{}'", + path.display() + ), + Self::OpenInput { + label, + path, + source, + } => write!(f, "failed to open {label} '{}': {source}", path.display()), + Self::LoadReference(err) => write!(f, "failed loading reference inputs: {err}"), + Self::BsonStream { + label, + path, + source, + } => write!(f, "failed reading {label} '{}': {source}", path.display()), + Self::CurateWrite(err) => write!(f, "{err}"), + Self::Ilp(err) => write!(f, "qm bars_1m ILP writer failed: {err}"), + Self::Io { path, source } => { + write!(f, "I/O error on '{}': {source}", path.display()) + } + Self::RollbackFailed { cause, failures } => { + write!(f, "{cause}; rollback also failed for: ")?; + for (i, failure) in failures.iter().enumerate() { + if i > 0 { + write!(f, ", ")?; + } + write!(f, "{failure}")?; + } + Ok(()) + } + } + } +} + +impl Error for RunCurateQmBars1mError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source), + Self::LoadReference(err) => Some(err), + Self::BsonStream { source, .. } => Some(source), + Self::CurateWrite(err) => Some(err), + Self::Ilp(err) => Some(err), + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::EmptyMappingSource + | Self::ZeroShardCount + | Self::InvalidOutDir { .. } + | Self::OutputFileExists { .. } => None, + } + } +} + +fn validate_common_args(args: &CurateQmBars1mArgs) -> Result<(), RunCurateQmBars1mError> { + if args.mapping_source.trim().is_empty() { + return Err(RunCurateQmBars1mError::EmptyMappingSource); + } + if args.shard_count == 0 { + return Err(RunCurateQmBars1mError::ZeroShardCount); + } + args.stream_options + .validate() + .map_err(|source| RunCurateQmBars1mError::BsonStream { + label: "qm-intraday", + path: args.intraday_path.clone(), + source, + })?; + if args.ilp_options.max_batch_bytes == 0 { + return Err(RunCurateQmBars1mError::Ilp( + IlpWriterError::ZeroMaxBatchBytes, + )); + } + if args.ilp_options.max_batch_rows == 0 { + return Err(RunCurateQmBars1mError::Ilp( + IlpWriterError::ZeroMaxBatchRows, + )); + } + Ok(()) +} + +fn validate_file_mode_args(args: &CurateQmBars1mArgs) -> Result<(), RunCurateQmBars1mError> { + validate_common_args(args)?; + preflight_shard_out_dir(&args.out_dir, QM_BARS_1M_SHARD_PREFIX)?; + Ok(()) +} + +fn load_provider_mapping_table( + provider_mapping_path: &Path, +) -> Result { + let mapping_rows = load_provider_mapping_tsv(provider_mapping_path) + .map_err(RunCurateQmBars1mError::LoadReference)?; + ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { + RunCurateQmBars1mError::LoadReference(RunCurateBarsError::ProviderMapping { + path: provider_mapping_path.to_path_buf(), + source, + }) + }) +} + +fn stream_qm_intraday_chunks_to_writer( + args: &CurateQmBars1mArgs, + mapping: &ProviderMappingTable, + intraday: R, + mut writer: IlpShardedWriter, + start: Instant, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err( + |source| RunCurateQmBars1mError::BsonStream { + label: "qm-intraday", + path: args.intraday_path.clone(), + source, + }, + )?; + + let mut intraday_decode = BsonQmIntradayDecodeStats::default(); + let mut curate_stats = CurateBars1mStats::default(); + let mut chunks: usize = 0; + let mut max_rows_per_chunk: usize = 0; + let mut rows_written: usize = 0; + + while let Some(chunk) = + reader + .next_chunk() + .map_err(|source| RunCurateQmBars1mError::BsonStream { + label: "qm-intraday", + path: args.intraday_path.clone(), + source, + })? + { + let mut chunk_bars: Vec> = Vec::new(); + let chunk_decode = decode_qm_intraday_buffer( + chunk.bytes, + |raw| { + chunk_bars.push(raw.into_eod_intraday_bar(|key, _| key)); + }, + |_local_offset, _err| {}, + ); + intraday_decode.merge(&chunk_decode); + + chunks += 1; + let chunk_len = chunk_bars.len(); + if chunk_len > max_rows_per_chunk { + max_rows_per_chunk = chunk_len; + } + + let write_report = curate_and_write_qm_bars_1m( + chunk_bars, + mapping, + &args.mapping_source, + &mut writer, + args.known_at_micros, + ) + .map_err(RunCurateQmBars1mError::CurateWrite)?; + + add_curate_bars_1m_stats(&mut curate_stats, &write_report.curate_stats); + rows_written += write_report.rows_written; + } + + let intraday_docs_framed = reader.docs_framed(); + let intraday_bytes_read = reader.bytes_read(); + let ilp_stats = writer.finish().map_err(RunCurateQmBars1mError::Ilp)?; + + Ok(CurateQmBars1mRunReport { + intraday_docs_framed, + intraday_bytes_read, + intraday_decode, + chunks, + max_rows_per_chunk, + curate_stats, + rows_written, + ilp_stats, + shard_count: args.shard_count, + elapsed_secs: start.elapsed().as_secs_f64(), + }) +} + +/// Runs the bounded-memory `qmIntraday` -> `bars_1m` curation pipeline from an arbitrary +/// [`io::Read`] stream into per-shard sinks created by `make_sink`. +/// +/// Validates `args` (rejecting blank `mapping_source` first, then `shard_count`, stream options, +/// and ILP options) and loads `provider_mapping.tsv` from `args.provider_mapping_path` before +/// calling `make_sink` once per shard (`0..args.shard_count`). Streams `intraday` through +/// [`RawBsonChunkReader::with_options`] + [`decode_qm_intraday_buffer`], curating and writing once +/// per chunk without split un-adjustment, and calls [`IlpShardedWriter::finish`] exactly once +/// after clean EOF. +pub fn run_curate_qm_bars_1m_with_readers( + args: &CurateQmBars1mArgs, + intraday: R, + mut make_sink: F, +) -> Result +where + R: io::Read, + W: Write + Send, + F: FnMut(usize) -> W, +{ + let start = Instant::now(); + validate_common_args(args)?; + + let mapping = load_provider_mapping_table(&args.provider_mapping_path)?; + + let mut sinks = Vec::with_capacity(args.shard_count); + for shard_idx in 0..args.shard_count { + sinks.push(make_sink(shard_idx)); + } + let writer = + IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateQmBars1mError::Ilp)?; + + stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start) +} + +fn fail_with_staging_cleanup( + cause: RunCurateQmBars1mError, + staged: &mut [(PathBuf, StagingFileGuard)], + remove_file: &mut RF, +) -> RunCurateQmBars1mError +where + RF: FnMut(&Path) -> io::Result<()>, +{ + let staging_failures = cleanup_armed_staged_shards(staged, remove_file); + if staging_failures.is_empty() { + return cause; + } + match cause { + RunCurateQmBars1mError::RollbackFailed { + cause: inner_cause, + mut failures, + } => { + failures.extend(staging_failures); + RunCurateQmBars1mError::RollbackFailed { + cause: inner_cause, + failures, + } + } + other => RunCurateQmBars1mError::RollbackFailed { + cause: Box::new(other), + failures: staging_failures, + }, + } +} + +/// Private file-mode seam accepting an injected reader, sink factory, pre-link hook, and staging +/// unlink hook so tests can exercise staging, writer failure, publication rollback, and staging +/// unlink failure reporting deterministically. +fn run_curate_qm_bars_1m_to_dir_with_cleanup_hook( + args: &CurateQmBars1mArgs, + intraday: R, + mut make_sink: SF, + before_link: BL, + mut remove_staged_file: RF, +) -> Result +where + R: io::Read, + W: Write + Send, + SF: FnMut(usize, File) -> W, + BL: FnMut(usize, &Path), + RF: FnMut(&Path) -> io::Result<()>, +{ + let start = Instant::now(); + validate_file_mode_args(args)?; + + let mapping = load_provider_mapping_table(&args.provider_mapping_path)?; + + fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateQmBars1mError::Io { + path: args.out_dir.clone(), + source, + })?; + + let run_id = next_run_id(); + let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count); + let mut sinks: Vec = Vec::with_capacity(args.shard_count); + for shard_idx in 0..args.shard_count { + let (tmp_path, file) = match create_exclusive_shard_tmp_file_for_table( + &args.out_dir, + QM_BARS_1M_SHARD_PREFIX, + shard_idx, + &run_id, + ) { + Ok(pair) => pair, + Err(err) => { + drop(sinks); + return Err(fail_with_staging_cleanup( + err.into(), + &mut staged, + &mut remove_staged_file, + )); + } + }; + let guard = StagingFileGuard::new(tmp_path.clone()); + staged.push((tmp_path, guard)); + sinks.push(make_sink(shard_idx, file)); + } + + let writer = match IlpShardedWriter::new(sinks, args.ilp_options) { + Ok(writer) => writer, + Err(err) => { + return Err(fail_with_staging_cleanup( + RunCurateQmBars1mError::Ilp(err), + &mut staged, + &mut remove_staged_file, + )); + } + }; + let report = match stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start) + { + Ok(report) => report, + Err(err) => { + return Err(fail_with_staging_cleanup( + err, + &mut staged, + &mut remove_staged_file, + )); + } + }; + + if let Err(err) = publish_staged_shards_for_table( + &args.out_dir, + QM_BARS_1M_SHARD_PREFIX, + &mut staged, + before_link, + ) { + return Err(fail_with_staging_cleanup( + err.into(), + &mut staged, + &mut remove_staged_file, + )); + } + Ok(report) +} + +/// Private file-mode seam accepting an injected reader, sink factory, and pre-link hook so tests +/// can exercise staging, writer failure, and post-preflight publication rollback through the exact +/// file publication path. +fn run_curate_qm_bars_1m_to_dir_with_hooks( + args: &CurateQmBars1mArgs, + intraday: R, + make_sink: SF, + before_link: BL, +) -> Result +where + R: io::Read, + W: Write + Send, + SF: FnMut(usize, File) -> W, + BL: FnMut(usize, &Path), +{ + run_curate_qm_bars_1m_to_dir_with_cleanup_hook( + args, + intraday, + make_sink, + before_link, + |path| fs::remove_file(path), + ) +} + +/// Runs the bounded-memory file-to-file `qmIntraday` -> `bars_1m` curation pipeline, publishing +/// exactly `args.shard_count` QuestDB ILP v2 files (`/bars_1m_qm.shard-.ilp`). +pub fn run_curate_qm_bars_1m( + args: &CurateQmBars1mArgs, +) -> Result { + validate_file_mode_args(args)?; + + let intraday_file = + File::open(&args.intraday_path).map_err(|source| RunCurateQmBars1mError::OpenInput { + label: "qm-intraday", + path: args.intraday_path.clone(), + source, + })?; + + run_curate_qm_bars_1m_to_dir_with_hooks( + args, + intraday_file, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + +/// Formats [`CurateQmBars1mRunReport`] into a deterministic machine-readable `key=value` summary. +/// +/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). +pub fn format_curate_qm_bars_1m_report(report: &CurateQmBars1mRunReport) -> String { + let per_shard = if report.ilp_stats.per_shard_rows.is_empty() { + "none".to_string() + } else { + report + .ilp_stats + .per_shard_rows + .iter() + .enumerate() + .map(|(idx, count)| format!("{idx:02}={count}")) + .collect::>() + .join(",") + }; + + let b = &report.curate_stats.builder; + let c = &report.curate_stats; + let d = &report.intraday_decode; + + format!( + "curate-etl curate-qm-bars-1m\n\ + \x20 intraday_bson: docs_framed={} bytes_read={} docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\ + \x20 chunking: chunks={} max_rows_per_chunk={} cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)\n\ + \x20 builder: bars_in={} rows_out={} keys_out_per_chunk_sum={} pre={} rth={} post={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_out_of_range={} dup_collapsed={} dup_conflict_dropped={}\n\ + \x20 curate: rows_in={} rows_out={} listings_out_per_chunk_sum={} pre={} rth={} post={} dropped_unmapped={} listing_collision_collapsed={} listing_collision_dropped={}\n\ + \x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\ + \x20 timing: elapsed_secs={:.6}", + report.intraday_docs_framed, + report.intraday_bytes_read, + d.docs_seen, + d.rows_decoded, + d.rejected_total(), + d.rejected_missing_field, + d.rejected_empty_field, + d.rejected_wrong_type, + d.rejected_invalid_timestamp, + d.rejected_invalid_number, + d.rejected_corrupt_document, + report.chunks, + report.max_rows_per_chunk, + b.bars_in, + b.rows_out, + b.keys_out, + b.pre_rows_out, + b.rth_rows_out, + b.post_rows_out, + b.dropped_invalid_ohlc, + b.dropped_inconsistent_ohlc, + b.dropped_invalid_volume, + b.dropped_ts_out_of_range, + b.duplicate_collapsed, + b.duplicate_conflict_dropped, + c.rows_in, + c.rows_out, + c.listings_out, + c.pre_rows_out, + c.rth_rows_out, + c.post_rows_out, + c.dropped_unmapped, + c.listing_collision_collapsed, + c.listing_collision_dropped, + report.shard_count, + report.rows_written, + report.ilp_stats.rows, + report.ilp_stats.bytes, + report.ilp_stats.flushes, + report.elapsed_secs, + ) +} + +#[cfg(test)] +#[path = "run_curate_qm_bars_1m_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs b/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs new file mode 100644 index 00000000..39245692 --- /dev/null +++ b/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs @@ -0,0 +1,1746 @@ +use std::error::Error; +use std::fs; +use std::io::{self, Cursor, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use bson::raw::{cstr, RawDocumentBuf}; +use bson::DateTime as BsonDateTime; + +use super::*; +use crate::bars_1m::{IntradaySession, BARS_1M_SOURCE_QM}; +use crate::bson_stream::MIN_BSON_DOC_BYTES; +use crate::ilp::{shard_for_listing_id, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M}; +use crate::run_curate_bars_1m::tests::TempDirGuard; +use crate::shorts::et_to_utc_micros; +use crate::split::ymd_to_epoch_days; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn et_ts_millis(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { + let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp"); + assert_eq!(micros % 1_000, 0); + micros / 1_000 +} + +fn make_qm_intraday_doc( + code: &str, + timestamp_ms: i64, + open: f64, + high: f64, + low: f64, + close: f64, + sharevolume: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), BsonDateTime::from_millis(timestamp_ms)); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("sharevolume"), sharevolume); + doc +} + +/// Builds a `qmIntraday` document that also carries distinct split-adjusted fields +/// (`adjustedopen..adjustedclose`, `avolume`) to prove the runner ignores them and preserves raw +/// OHLCV bit-identically. +#[allow(clippy::too_many_arguments)] +fn make_qm_intraday_doc_with_adjusted( + code: &str, + timestamp_ms: i64, + open: f64, + high: f64, + low: f64, + close: f64, + sharevolume: f64, + adj_scale: f64, +) -> RawDocumentBuf { + let mut doc = make_qm_intraday_doc(code, timestamp_ms, open, high, low, close, sharevolume); + doc.append(cstr!("adjustedopen"), open / adj_scale); + doc.append(cstr!("adjustedhigh"), high / adj_scale); + doc.append(cstr!("adjustedlow"), low / adj_scale); + doc.append(cstr!("adjustedclose"), close / adj_scale); + doc.append(cstr!("avolume"), sharevolume * adj_scale); + doc +} + +fn make_malformed_missing_open_doc(code: &str, timestamp_ms: i64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), BsonDateTime::from_millis(timestamp_ms)); + doc.append(cstr!("high"), 102.0_f64); + doc.append(cstr!("low"), 99.0_f64); + doc.append(cstr!("close"), 101.0_f64); + doc.append(cstr!("sharevolume"), 500.0_f64); + doc +} + +fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { + let mut out = Vec::new(); + for doc in docs { + out.extend_from_slice(doc.as_bytes()); + } + out +} + +fn write_mapping_tsv(dir: &Path, lines: &[&str]) -> PathBuf { + let path = dir.join("provider_mapping.tsv"); + let mut body = lines.join("\n"); + if !body.is_empty() { + body.push('\n'); + } + fs::write(&path, body).expect("write provider_mapping.tsv"); + path +} + +fn list_dir_names(dir: &Path) -> Vec { + if !dir.exists() { + return Vec::new(); + } + let mut names: Vec = fs::read_dir(dir) + .expect("read_dir") + .map(|entry| { + entry + .expect("dir entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .collect(); + names.sort(); + names +} + +fn make_args( + intraday_path: PathBuf, + provider_mapping_path: PathBuf, + out_dir: PathBuf, + mapping_source: &str, + shard_count: usize, + known_at_micros: i64, + stream_options: BsonStreamOptions, +) -> CurateQmBars1mArgs { + CurateQmBars1mArgs { + intraday_path, + provider_mapping_path, + out_dir, + mapping_source: mapping_source.to_string(), + shard_count, + known_at_micros, + stream_options, + ilp_options: IlpWriterOptions::default(), + } +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedIlpBar1m { + listing_id: i32, + session: IntradaySession, + source: String, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, + known_at: i64, + ts: i64, +} + +impl DecodedIlpBar1m { + fn sort_key(&self) -> (i32, i64, u64, u64, u64, u64, u64, i64) { + ( + self.listing_id, + self.ts, + self.open.to_bits(), + self.high.to_bits(), + self.low.to_bits(), + self.close.to_bits(), + self.volume.to_bits(), + self.known_at, + ) + } +} + +/// Decodes QuestDB ILP v2 `bars_1m` records respecting fixed-width 8-byte binary `DOUBLE` +/// payloads (`==\x10<8 LE bytes>`) so embedded `0x0a` bytes inside doubles never split rows. +fn decode_ilp_bars_1m(data: &[u8]) -> Vec { + let mut rows = Vec::new(); + let mut i = 0usize; + let len = data.len(); + + while i < len { + let tag_start = i; + while i < len { + match data[i] { + b'\\' => { + assert!(i + 1 < len, "dangling backslash in ILP tag set"); + i += 2; + } + b' ' => break, + _ => i += 1, + } + } + assert!( + i < len && data[i] == b' ', + "missing space after ILP tag set" + ); + let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("valid UTF-8 tag set"); + i += 1; + + let mut tags = tag_str.split(','); + assert_eq!(tags.next(), Some(TABLE_BARS_1M), "expected bars_1m table"); + let listing_tag = tags.next().expect("listing_id tag"); + let session_tag = tags.next().expect("session tag"); + let source_tag = tags.next().expect("source tag"); + assert!(tags.next().is_none(), "unexpected extra ILP tag"); + + let listing_id: i32 = listing_tag + .strip_prefix("listing_id=") + .expect("listing_id= prefix") + .parse() + .expect("i32 listing_id"); + let session = match session_tag + .strip_prefix("session=") + .expect("session= prefix") + { + "PRE" => IntradaySession::Pre, + "RTH" => IntradaySession::Rth, + "POST" => IntradaySession::Post, + other => panic!("unexpected session '{other}'"), + }; + let source = source_tag + .strip_prefix("source=") + .expect("source= prefix") + .to_string(); + + let read_bin_f64 = |pos: &mut usize, name: &str| -> f64 { + let prefix = format!("{name}=="); + assert!( + data[*pos..].starts_with(prefix.as_bytes()), + "expected field prefix '{prefix}' at offset {}", + *pos + ); + *pos += prefix.len(); + assert_eq!( + data[*pos], ILP_V2_DOUBLE_TYPE, + "expected binary DOUBLE type tag for '{name}'" + ); + *pos += 1; + let bytes: [u8; 8] = data[*pos..*pos + 8] + .try_into() + .expect("8 bytes for binary double"); + *pos += 8; + f64::from_le_bytes(bytes) + }; + + let open = read_bin_f64(&mut i, "open"); + assert_eq!(data[i], b','); + i += 1; + let high = read_bin_f64(&mut i, "high"); + assert_eq!(data[i], b','); + i += 1; + let low = read_bin_f64(&mut i, "low"); + assert_eq!(data[i], b','); + i += 1; + let close = read_bin_f64(&mut i, "close"); + assert_eq!(data[i], b','); + i += 1; + let volume = read_bin_f64(&mut i, "volume"); + assert_eq!(data[i], b','); + i += 1; + + let ka_prefix = b"known_at="; + assert!( + data[i..].starts_with(ka_prefix), + "expected known_at= at offset {i}" + ); + i += ka_prefix.len(); + let ka_start = i; + while i < len && data[i] != b' ' { + i += 1; + } + assert!(i < len && data[i] == b' ', "missing space after known_at"); + let ka_str = std::str::from_utf8(&data[ka_start..i]).expect("valid UTF-8 known_at"); + let known_at: i64 = ka_str + .strip_suffix('t') + .expect("known_at trailing t") + .parse() + .expect("i64 known_at"); + i += 1; + + let ts_start = i; + while i < len && data[i] != b'\n' { + i += 1; + } + assert!(i < len && data[i] == b'\n', "missing trailing LF"); + let ts_str = std::str::from_utf8(&data[ts_start..i]).expect("valid UTF-8 ts"); + let ts: i64 = ts_str + .strip_suffix('t') + .expect("ts trailing t") + .parse() + .expect("i64 ts"); + i += 1; + + rows.push(DecodedIlpBar1m { + listing_id, + session, + source, + open, + high, + low, + close, + volume, + known_at, + ts, + }); + } + + rows +} + +fn assert_report_conservation(report: &CurateQmBars1mRunReport) { + let d = &report.intraday_decode; + assert_eq!( + report.intraday_docs_framed as usize, d.docs_seen, + "docs_framed != docs_seen" + ); + assert_eq!( + d.docs_seen, + d.rows_decoded + d.rejected_total(), + "decode conservation failed: {d:?}" + ); + + let c = &report.curate_stats; + let b = &c.builder; + assert_eq!(d.rows_decoded, b.bars_in, "rows_decoded != builder.bars_in"); + assert_eq!(c.rows_in, b.rows_out, "curate.rows_in != builder.rows_out"); + assert_eq!( + c.rows_in, + c.rows_out + + c.dropped_unmapped + + c.listing_collision_collapsed + + c.listing_collision_dropped, + "curate_stats conservation failed: {c:?}" + ); + assert_eq!( + c.pre_rows_out + c.rth_rows_out + c.post_rows_out, + c.rows_out, + "session breakdown != rows_out" + ); + assert_eq!(report.rows_written, c.rows_out, "rows_written != rows_out"); + assert_eq!( + report.rows_written, report.ilp_stats.rows, + "rows_written != ilp_stats.rows" + ); + assert_eq!( + report.ilp_stats.per_shard_rows.iter().sum::(), + report.ilp_stats.rows, + "sum(per_shard_rows) != ilp_stats.rows" + ); + assert_eq!(report.ilp_stats.per_shard_rows.len(), report.shard_count); +} + +#[derive(Clone)] +struct RecordingSink { + bytes: Arc>>, + flushes: Arc, +} + +impl RecordingSink { + fn new() -> Self { + Self { + bytes: Arc::new(Mutex::new(Vec::new())), + flushes: Arc::new(AtomicUsize::new(0)), + } + } +} + +impl Write for RecordingSink { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.bytes.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.flushes.fetch_add(1, Ordering::SeqCst); + Ok(()) + } +} + +struct FailingWriteSink { + fail_on_write: bool, + fail_on_flush: bool, +} + +impl Write for FailingWriteSink { + fn write(&mut self, buf: &[u8]) -> io::Result { + if self.fail_on_write { + Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "injected write failure", + )) + } else { + Ok(buf.len()) + } + } + + fn flush(&mut self) -> io::Result<()> { + if self.fail_on_flush { + Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "injected flush failure", + )) + } else { + Ok(()) + } + } +} + +struct PanicReader; + +impl Read for PanicReader { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + panic!("reader must not be called when validation fails"); + } +} + +struct PrefixThenIoErrorReader { + prefix: Vec, + pos: usize, + failed: bool, +} + +impl PrefixThenIoErrorReader { + fn new(prefix: Vec) -> Self { + Self { + prefix, + pos: 0, + failed: false, + } + } +} + +impl Read for PrefixThenIoErrorReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.pos < self.prefix.len() { + let n = (self.prefix.len() - self.pos).min(buf.len()); + buf[..n].copy_from_slice(&self.prefix[self.pos..self.pos + n]); + self.pos += n; + return Ok(n); + } + if !self.failed { + self.failed = true; + return Err(io::Error::new( + io::ErrorKind::ConnectionReset, + "injected reader failure after prefix", + )); + } + Ok(0) + } +} + +#[test] +fn happy_path_file_mode_decodes_bit_identical_raw_ohlcv_date_boundary_and_deterministic_replay() { + let dir = TempDirGuard::new("qm-bars1m-happy"); + + // Date-effective mapping boundary for QM code "REUSE": + // 2024-06-01..=2024-06-10 -> listing 101 + // 2024-06-11.. -> listing 202 + // Plus a second symbol "AAPL" -> listing 303. + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "qm\tREUSE\t2024-06-01\t2024-06-10\t101", + "qm\tREUSE\t2024-06-11\t\t202", + "qm\tAAPL\t2024-01-01\t\t303", + ], + ); + + // Choose a raw close whose LE IEEE-754 bytes include 0x0a to prove binary ILP decoding does + // not split on embedded newlines. + let raw_close_with_lf = f64::from_le_bytes([0x0a, 0x11, 0x22, 0x33, 0x44, 0x55, 0x59, 0x40]); + assert!( + raw_close_with_lf.is_finite() && raw_close_with_lf > 100.0 && raw_close_with_lf < 102.0 + ); + + let ts_pre = et_ts_millis(2024, 6, 10, 8, 15); + let ts_rth_old = et_ts_millis(2024, 6, 10, 10, 30); + let ts_rth_new = et_ts_millis(2024, 6, 11, 9, 30); + let ts_post = et_ts_millis(2024, 6, 11, 17, 5); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + + // Include distinct adjusted fields (scale 10.0) to verify raw fields pass through bit-identical + // with no split un-adjustment, and include -0.0 sharevolume to verify +0.0 normalization. + let docs = vec![ + make_qm_intraday_doc_with_adjusted( + "REUSE", + ts_rth_old, + 100.125, + 102.5, + 99.75, + raw_close_with_lf, + 12_345.0, + 10.0, + ), + make_qm_intraday_doc_with_adjusted("REUSE", ts_pre, 99.5, 100.0, 99.0, 99.8, -0.0, 10.0), + make_qm_intraday_doc_with_adjusted( + "REUSE", ts_rth_new, 15.25, 15.75, 15.0, 15.5, 8_000.0, 4.0, + ), + make_qm_intraday_doc_with_adjusted( + "AAPL", ts_post, 210.0, 211.25, 209.5, 210.75, 4_200.0, 2.0, + ), + ]; + let intraday_bytes = concat_docs(&docs); + let intraday_path = dir.path().join("qmIntraday.bson"); + fs::write(&intraday_path, &intraday_bytes).unwrap(); + + let shard_count = 4; + let out_dir_1 = dir.path().join("out-1"); + let args_1 = make_args( + intraday_path.clone(), + mapping_path.clone(), + out_dir_1.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + shard_count, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report_1 = run_curate_qm_bars_1m(&args_1).expect("happy-path run should succeed"); + assert_report_conservation(&report_1); + assert_eq!(report_1.intraday_docs_framed, 4); + assert_eq!(report_1.intraday_bytes_read, intraday_bytes.len() as u64); + assert_eq!(report_1.chunks, 1); + assert_eq!(report_1.max_rows_per_chunk, 4); + assert_eq!(report_1.rows_written, 4); + + // Output directory contains exactly bars_1m_qm.shard-00..03.ilp and no staging .tmp files. + assert_eq!( + list_dir_names(&out_dir_1), + vec![ + "bars_1m_qm.shard-00.ilp", + "bars_1m_qm.shard-01.ilp", + "bars_1m_qm.shard-02.ilp", + "bars_1m_qm.shard-03.ilp", + ] + ); + + // Decode every shard and assert shard routing, table, source, timestamps, known_at, and raw OHLCV bits. + let mut decoded_all = Vec::new(); + for shard_idx in 0..shard_count { + let path = out_dir_1.join(format!("bars_1m_qm.shard-{shard_idx:02}.ilp")); + let bytes = fs::read(&path).expect("read shard file"); + let shard_rows = decode_ilp_bars_1m(&bytes); + assert_eq!( + shard_rows.len(), + report_1.ilp_stats.per_shard_rows[shard_idx] + ); + for row in &shard_rows { + assert_eq!(row.source, BARS_1M_SOURCE_QM); + assert_eq!(row.known_at, known_at_micros); + assert_eq!(shard_for_listing_id(row.listing_id, shard_count), shard_idx); + } + decoded_all.extend(shard_rows); + } + decoded_all.sort_by_key(DecodedIlpBar1m::sort_key); + + assert_eq!(decoded_all.len(), 4); + // Listing 101 PRE bar (2024-06-10, -0.0 volume normalized to +0.0) + assert_eq!(decoded_all[0].listing_id, 101); + assert_eq!(decoded_all[0].ts, ts_pre * 1_000); + assert_eq!(decoded_all[0].session, IntradaySession::Pre); + assert_eq!(decoded_all[0].open.to_bits(), 99.5_f64.to_bits()); + assert_eq!(decoded_all[0].high.to_bits(), 100.0_f64.to_bits()); + assert_eq!(decoded_all[0].low.to_bits(), 99.0_f64.to_bits()); + assert_eq!(decoded_all[0].close.to_bits(), 99.8_f64.to_bits()); + assert_eq!(decoded_all[0].volume.to_bits(), 0.0_f64.to_bits()); + + // Listing 101 RTH bar (2024-06-10, raw close with embedded 0x0a byte) + assert_eq!(decoded_all[1].listing_id, 101); + assert_eq!(decoded_all[1].ts, ts_rth_old * 1_000); + assert_eq!(decoded_all[1].session, IntradaySession::Rth); + assert_eq!(decoded_all[1].open.to_bits(), 100.125_f64.to_bits()); + assert_eq!(decoded_all[1].high.to_bits(), 102.5_f64.to_bits()); + assert_eq!(decoded_all[1].low.to_bits(), 99.75_f64.to_bits()); + assert_eq!(decoded_all[1].close.to_bits(), raw_close_with_lf.to_bits()); + assert_eq!(decoded_all[1].volume.to_bits(), 12_345.0_f64.to_bits()); + + // Listing 202 RTH bar (2024-06-11, after mapping boundary) + assert_eq!(decoded_all[2].listing_id, 202); + assert_eq!(decoded_all[2].ts, ts_rth_new * 1_000); + assert_eq!(decoded_all[2].session, IntradaySession::Rth); + assert_eq!(decoded_all[2].open.to_bits(), 15.25_f64.to_bits()); + assert_eq!(decoded_all[2].high.to_bits(), 15.75_f64.to_bits()); + assert_eq!(decoded_all[2].low.to_bits(), 15.0_f64.to_bits()); + assert_eq!(decoded_all[2].close.to_bits(), 15.5_f64.to_bits()); + assert_eq!(decoded_all[2].volume.to_bits(), 8_000.0_f64.to_bits()); + + // Listing 303 POST bar + assert_eq!(decoded_all[3].listing_id, 303); + assert_eq!(decoded_all[3].ts, ts_post * 1_000); + assert_eq!(decoded_all[3].session, IntradaySession::Post); + assert_eq!(decoded_all[3].open.to_bits(), 210.0_f64.to_bits()); + assert_eq!(decoded_all[3].high.to_bits(), 211.25_f64.to_bits()); + assert_eq!(decoded_all[3].low.to_bits(), 209.5_f64.to_bits()); + assert_eq!(decoded_all[3].close.to_bits(), 210.75_f64.to_bits()); + assert_eq!(decoded_all[3].volume.to_bits(), 4_200.0_f64.to_bits()); + + // Compare against pure single-chunk baseline `curate_and_write_qm_bars_1m`. + let mapping = load_provider_mapping_table(&mapping_path).unwrap(); + let baseline_sinks: Vec> = (0..shard_count).map(|_| Vec::new()).collect(); + let mut baseline_writer = + IlpShardedWriter::new(baseline_sinks, IlpWriterOptions::default()).unwrap(); + let mut baseline_bars = Vec::new(); + decode_qm_intraday_buffer( + &intraday_bytes, + |raw| baseline_bars.push(raw.into_eod_intraday_bar(|k, _| k)), + |_, _| {}, + ); + curate_and_write_qm_bars_1m( + baseline_bars, + &mapping, + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + &mut baseline_writer, + known_at_micros, + ) + .unwrap(); + let baseline_stats = baseline_writer.finish().unwrap(); + assert_eq!(report_1.ilp_stats, baseline_stats); + + // Deterministic replay: identical settings into a second out_dir yield byte-identical shards + // and identical report fields (excluding elapsed_secs). + let out_dir_2 = dir.path().join("out-2"); + let args_2 = make_args( + intraday_path, + mapping_path, + out_dir_2.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + shard_count, + known_at_micros, + BsonStreamOptions::default(), + ); + let report_2 = run_curate_qm_bars_1m(&args_2).expect("replay run should succeed"); + for shard_idx in 0..shard_count { + let b1 = fs::read(out_dir_1.join(format!("bars_1m_qm.shard-{shard_idx:02}.ilp"))).unwrap(); + let b2 = fs::read(out_dir_2.join(format!("bars_1m_qm.shard-{shard_idx:02}.ilp"))).unwrap(); + assert_eq!(b1, b2, "shard {shard_idx} bytes differed across replay"); + } + let mut r1 = report_1; + let mut r2 = report_2; + r1.elapsed_secs = 0.0; + r2.elapsed_secs = 0.0; + assert_eq!(r1, r2); +} + +#[test] +fn bounded_chunk_streaming_matches_single_chunk_and_calls_finish_flush_once_per_shard() { + let dir = TempDirGuard::new("qm-bars1m-chunked"); + let mapping_path = write_mapping_tsv( + dir.path(), + &["qm\tAAA\t2024-01-01\t\t11", "qm\tBBB\t2024-01-01\t\t22"], + ); + + let known_at_micros = et_to_utc_micros(day(2024, 7, 2), 18, 0, 0).unwrap(); + let mut docs = Vec::new(); + for minute in 0..12u8 { + let code = if minute % 2 == 0 { "AAA" } else { "BBB" }; + let base = 50.0 + f64::from(minute); + docs.push(make_qm_intraday_doc( + code, + et_ts_millis(2024, 7, 1, 9, 30 + minute), + base, + base + 0.5, + base - 0.25, + base + 0.25, + 100.0 + f64::from(minute), + )); + } + let single_doc_len = docs[0].as_bytes().len(); + let intraday_bytes = concat_docs(&docs); + + // Use 4 shards so at least 2 shards are empty (only 2 listings), verifying finish() flushes + // empty shards once too. + let shard_count = 4; + + let run_with_capacity = |chunk_capacity_bytes: usize| { + let sinks: Vec = (0..shard_count).map(|_| RecordingSink::new()).collect(); + let sinks_ref = sinks.clone(); + let args = make_args( + dir.path().join("in-memory.bson"), + mapping_path.clone(), + dir.path().join("unused-out"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + shard_count, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes, + max_doc_bytes: 1024 * 1024, + }, + ); + let report = run_curate_qm_bars_1m_with_readers( + &args, + Cursor::new(intraday_bytes.as_slice()), + |shard_idx| sinks_ref[shard_idx].clone(), + ) + .expect("stream run should succeed"); + assert_report_conservation(&report); + + let mut rows = Vec::new(); + for (idx, sink) in sinks.iter().enumerate() { + assert_eq!( + sink.flushes.load(Ordering::SeqCst), + 1, + "shard {idx} must observe exactly one finish() flush" + ); + rows.extend(decode_ilp_bars_1m(&sink.bytes.lock().unwrap())); + } + rows.sort_by_key(DecodedIlpBar1m::sort_key); + (report, rows) + }; + + let (single_report, single_rows) = run_with_capacity(64 * 1024); + let (tiny_report, tiny_rows) = run_with_capacity(single_doc_len * 2 + 4); + + assert_eq!(single_report.chunks, 1); + assert_eq!(single_report.max_rows_per_chunk, 12); + assert!( + tiny_report.chunks > 1, + "expected multiple chunks, got {}", + tiny_report.chunks + ); + assert!( + tiny_report.max_rows_per_chunk < single_report.max_rows_per_chunk, + "expected lower high-water mark: tiny={} vs single={}", + tiny_report.max_rows_per_chunk, + single_report.max_rows_per_chunk + ); + assert_eq!(single_rows, tiny_rows); + assert_eq!(single_report.rows_written, tiny_report.rows_written); + assert_eq!(single_report.ilp_stats.rows, tiny_report.ilp_stats.rows); + assert_eq!( + single_report.ilp_stats.per_shard_rows, + tiny_report.ilp_stats.per_shard_rows + ); +} + +#[test] +fn conservation_counts_unmapped_semantic_decode_errors_collisions_and_cross_chunk_duplicates() { + let dir = TempDirGuard::new("qm-bars1m-conservation"); + // ALIAS_A and ALIAS_B both map to listing 500 to test identical collapse and conflict drop. + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "qm\tALIAS_A\t2024-01-01\t\t500", + "qm\tALIAS_B\t2024-01-01\t\t500", + ], + ); + + let known_at_micros = et_to_utc_micros(day(2024, 8, 2), 18, 0, 0).unwrap(); + let ts_pre = et_ts_millis(2024, 8, 1, 8, 0); + let ts_rth_same = et_ts_millis(2024, 8, 1, 10, 0); + let ts_rth_conflict = et_ts_millis(2024, 8, 1, 10, 1); + let ts_post = et_ts_millis(2024, 8, 1, 16, 30); + let ts_bad_ohlc = et_ts_millis(2024, 8, 1, 10, 2); + + let docs = vec![ + // 1. Valid PRE bar + make_qm_intraday_doc("ALIAS_A", ts_pre, 10.0, 10.5, 9.8, 10.2, 100.0), + // 2. Semantically invalid BSON doc (missing `open`) -> counted and skipped + make_malformed_missing_open_doc("ALIAS_A", ts_pre + 60_000), + // 3. Unmapped qmSearchCode -> dropped_unmapped + make_qm_intraday_doc("UNKNOWN_CODE", ts_rth_same, 20.0, 21.0, 19.5, 20.5, 50.0), + // 4 & 5. Identical alias collision -> 1 row emitted, 1 listing_collision_collapsed + make_qm_intraday_doc("ALIAS_A", ts_rth_same, 11.0, 11.5, 10.8, 11.2, 200.0), + make_qm_intraday_doc("ALIAS_B", ts_rth_same, 11.0, 11.5, 10.8, 11.2, 200.0), + // 6 & 7. Conflicting alias collision -> both dropped (2 listing_collision_dropped) + make_qm_intraday_doc("ALIAS_A", ts_rth_conflict, 12.0, 12.5, 11.8, 12.2, 300.0), + make_qm_intraday_doc("ALIAS_B", ts_rth_conflict, 12.0, 12.6, 11.8, 12.2, 300.0), + // 8. Builder-inconsistent OHLC (high < low) -> dropped_inconsistent_ohlc + make_qm_intraday_doc("ALIAS_A", ts_bad_ohlc, 10.0, 9.0, 11.0, 10.0, 10.0), + // 9. Valid POST bar + make_qm_intraday_doc("ALIAS_A", ts_post, 13.0, 13.4, 12.9, 13.1, 400.0), + ]; + let intraday_bytes = concat_docs(&docs); + let args = make_args( + dir.path().join("conservation.bson"), + mapping_path.clone(), + dir.path().join("unused-out"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report = run_curate_qm_bars_1m_with_readers( + &args, + Cursor::new(intraday_bytes.as_slice()), + |_shard_idx| Vec::::new(), + ) + .expect("conservation run should succeed"); + assert_report_conservation(&report); + + assert_eq!(report.intraday_docs_framed, 9); + assert_eq!(report.intraday_decode.docs_seen, 9); + assert_eq!(report.intraday_decode.rows_decoded, 8); + assert_eq!(report.intraday_decode.rejected_missing_field, 1); + assert_eq!(report.curate_stats.builder.bars_in, 8); + assert_eq!(report.curate_stats.builder.dropped_inconsistent_ohlc, 1); + assert_eq!(report.curate_stats.rows_in, 7); + assert_eq!(report.curate_stats.dropped_unmapped, 1); + assert_eq!(report.curate_stats.listing_collision_collapsed, 1); + assert_eq!(report.curate_stats.listing_collision_dropped, 2); + assert_eq!(report.curate_stats.rows_out, 3); + assert_eq!(report.curate_stats.pre_rows_out, 1); + assert_eq!(report.curate_stats.rth_rows_out, 1); + assert_eq!(report.curate_stats.post_rows_out, 1); + assert_eq!(report.rows_written, 3); + + // Cross-chunk duplicate semantics: the same (listing_id, ts) in two separate chunks emits both + // rows (relying on QuestDB DEDUP UPSERT KEYS(ts, listing_id)) and sums listings_out/keys_out. + let dup_doc = make_qm_intraday_doc("ALIAS_A", ts_rth_same, 11.0, 11.5, 10.8, 11.2, 200.0); + let doc_len = dup_doc.as_bytes().len(); + let cross_chunk_bytes = concat_docs(&[dup_doc.clone(), dup_doc]); + let sinks = vec![RecordingSink::new()]; + let sinks_ref = sinks.clone(); + let cross_args = make_args( + dir.path().join("cross-chunk.bson"), + mapping_path, + dir.path().join("unused-out-2"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 1, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: doc_len, + max_doc_bytes: 1024 * 1024, + }, + ); + let cross_report = run_curate_qm_bars_1m_with_readers( + &cross_args, + Cursor::new(cross_chunk_bytes.as_slice()), + |idx| sinks_ref[idx].clone(), + ) + .expect("cross-chunk duplicate run should succeed"); + assert_report_conservation(&cross_report); + assert_eq!(cross_report.chunks, 2); + assert_eq!(cross_report.rows_written, 2); + assert_eq!(cross_report.curate_stats.listings_out, 2); + assert_eq!(cross_report.curate_stats.builder.keys_out, 2); + let emitted = decode_ilp_bars_1m(&sinks[0].bytes.lock().unwrap()); + assert_eq!(emitted.len(), 2); + assert_eq!(emitted[0], emitted[1]); +} + +#[test] +fn blank_mapping_source_rejected_before_opening_inputs_or_creating_out_dir_and_custom_namespace_works( +) { + let dir = TempDirGuard::new("qm-bars1m-source"); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + + for blank in ["", " ", "\t\n "] { + let out_dir = dir.path().join(format!("should-not-exist-{}", blank.len())); + let args = make_args( + dir.path().join("nonexistent-intraday.bson"), + dir.path().join("nonexistent-mapping.tsv"), + out_dir.clone(), + blank, + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + + let file_err = run_curate_qm_bars_1m(&args).expect_err("blank source must fail file mode"); + assert!( + matches!(file_err, RunCurateQmBars1mError::EmptyMappingSource), + "expected EmptyMappingSource, got {file_err:?}" + ); + assert!( + !out_dir.exists(), + "out_dir must not be created on blank mapping_source" + ); + + let reader_err = + run_curate_qm_bars_1m_with_readers(&args, PanicReader, |_idx| -> Vec { + panic!("sink factory must not be called on blank mapping_source"); + }) + .expect_err("blank source must fail reader mode"); + assert!(matches!( + reader_err, + RunCurateQmBars1mError::EmptyMappingSource + )); + } + + // Custom nonblank namespace forwarded verbatim alongside "qm" in the same TSV. + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "qm\tSYM\t2024-01-01\t\t10", + "qm_custom\tSYM\t2024-01-01\t\t99", + ], + ); + let docs = vec![make_qm_intraday_doc( + "SYM", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.9, + 10.2, + 100.0, + )]; + let intraday_bytes = concat_docs(&docs); + let sinks = vec![RecordingSink::new()]; + let sinks_ref = sinks.clone(); + let custom_args = make_args( + dir.path().join("custom.bson"), + mapping_path, + dir.path().join("unused"), + "qm_custom", + 1, + known_at_micros, + BsonStreamOptions::default(), + ); + let report = run_curate_qm_bars_1m_with_readers( + &custom_args, + Cursor::new(intraday_bytes.as_slice()), + |idx| sinks_ref[idx].clone(), + ) + .expect("custom mapping_source should succeed"); + assert_report_conservation(&report); + let decoded = decode_ilp_bars_1m(&sinks[0].bytes.lock().unwrap()); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded[0].listing_id, 99); +} + +#[test] +fn missing_inputs_and_invalid_options_fail_closed_without_creating_out_dir() { + let dir = TempDirGuard::new("qm-bars1m-missing"); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + let valid_mapping = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t1"]); + let valid_bson = dir.path().join("valid.bson"); + fs::write(&valid_bson, b"").unwrap(); + + // Missing BSON input + let out_missing_bson = dir.path().join("out-missing-bson"); + let err = run_curate_qm_bars_1m(&make_args( + dir.path().join("does-not-exist.bson"), + valid_mapping.clone(), + out_missing_bson.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect_err("missing BSON must fail"); + assert!(matches!( + err, + RunCurateQmBars1mError::OpenInput { + label: "qm-intraday", + .. + } + )); + assert!(err.source().is_some()); + assert!(!out_missing_bson.exists()); + + // Missing provider_mapping.tsv + let out_missing_map = dir.path().join("out-missing-map"); + let err = run_curate_qm_bars_1m(&make_args( + valid_bson.clone(), + dir.path().join("does-not-exist.tsv"), + out_missing_map.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect_err("missing mapping must fail"); + assert!(matches!(err, RunCurateQmBars1mError::LoadReference(_))); + assert!(!out_missing_map.exists()); + + // Zero shard_count + let err = run_curate_qm_bars_1m(&make_args( + valid_bson.clone(), + valid_mapping.clone(), + dir.path().join("out-zero-shard"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 0, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect_err("zero shard_count must fail"); + assert!(matches!(err, RunCurateQmBars1mError::ZeroShardCount)); + + // Invalid stream_options + let err = run_curate_qm_bars_1m(&make_args( + valid_bson.clone(), + valid_mapping.clone(), + dir.path().join("out-bad-stream"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: 0, + max_doc_bytes: MIN_BSON_DOC_BYTES, + }, + )) + .expect_err("zero chunk_capacity_bytes must fail"); + assert!(matches!(err, RunCurateQmBars1mError::BsonStream { .. })); + + // out_dir exists as a regular file + let file_as_dir = dir.path().join("not-a-dir"); + fs::write(&file_as_dir, b"file").unwrap(); + let err = run_curate_qm_bars_1m(&make_args( + valid_bson, + valid_mapping, + file_as_dir, + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect_err("file out_dir must fail"); + assert!(matches!(err, RunCurateQmBars1mError::InvalidOutDir { .. })); +} + +#[test] +fn preflight_rejects_high_numbered_qm_shard_and_allows_eod_bars_1m_shard_coexistence() { + let dir = TempDirGuard::new("qm-bars1m-preflight"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + let intraday_bytes = concat_docs(&[make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.8, + 10.2, + 100.0, + )]); + let intraday_path = dir.path().join("qmIntraday.bson"); + fs::write(&intraday_path, &intraday_bytes).unwrap(); + + // (a) Pre-existing bars_1m_qm.shard-07.ilp (index >= requested shard_count=2) fails preflight + // and stays byte-identical. + let out_conflict = dir.path().join("out-conflict"); + fs::create_dir_all(&out_conflict).unwrap(); + let stale_qm_shard = out_conflict.join("bars_1m_qm.shard-07.ilp"); + let stale_bytes = b"pre-existing-stale-qm-shard\n"; + fs::write(&stale_qm_shard, stale_bytes).unwrap(); + + let err = run_curate_qm_bars_1m(&make_args( + intraday_path.clone(), + mapping_path.clone(), + out_conflict.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect_err("pre-existing high-numbered QM shard must fail preflight"); + assert!(matches!( + err, + RunCurateQmBars1mError::OutputFileExists { ref path } if path == &stale_qm_shard + )); + assert_eq!(fs::read(&stale_qm_shard).unwrap(), stale_bytes); + assert_eq!( + list_dir_names(&out_conflict), + vec!["bars_1m_qm.shard-07.ilp"] + ); + + // (b) Pre-existing bars_1m.shard-00.ilp (EOD runner output) does NOT block the QM run and is + // left byte-identical. + let out_shared = dir.path().join("out-shared"); + fs::create_dir_all(&out_shared).unwrap(); + let eod_shard = out_shared.join("bars_1m.shard-00.ilp"); + let eod_bytes = b"pre-existing-eod-bars-1m-shard-bytes\n"; + fs::write(&eod_shard, eod_bytes).unwrap(); + + let report = run_curate_qm_bars_1m(&make_args( + intraday_path, + mapping_path, + out_shared.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect("QM run should coexist with EOD bars_1m.shard-00.ilp"); + assert_report_conservation(&report); + assert_eq!(report.rows_written, 1); + assert_eq!(fs::read(&eod_shard).unwrap(), eod_bytes); + assert_eq!( + list_dir_names(&out_shared), + vec![ + "bars_1m.shard-00.ilp", + "bars_1m_qm.shard-00.ilp", + "bars_1m_qm.shard-01.ilp", + ] + ); +} + +#[test] +fn fatal_bson_framing_and_reader_io_errors_report_absolute_offset_and_leave_out_dir_clean() { + let dir = TempDirGuard::new("qm-bars1m-bson-errors"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + + let valid_prefix = make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.8, + 10.2, + 100.0, + ); + let prefix_len = valid_prefix.as_bytes().len() as u64; + + // 1. Truncated document after valid prefix. + let mut truncated_bytes = valid_prefix.as_bytes().to_vec(); + truncated_bytes.extend_from_slice(&20_i32.to_le_bytes()); + truncated_bytes.extend_from_slice(&[0u8; 4]); + let trunc_path = dir.path().join("truncated.bson"); + fs::write(&trunc_path, &truncated_bytes).unwrap(); + let out_trunc = dir.path().join("out-trunc"); + let err = run_curate_qm_bars_1m(&make_args( + trunc_path, + mapping_path.clone(), + out_trunc.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: prefix_len as usize, + max_doc_bytes: 1024 * 1024, + }, + )) + .expect_err("truncated BSON must fail"); + assert!( + matches!( + err, + RunCurateQmBars1mError::BsonStream { + source: BsonStreamError::TruncatedDocument { offset, .. }, + .. + } if offset == prefix_len + ), + "expected TruncatedDocument at offset {prefix_len}, got {err:?}" + ); + assert!( + list_dir_names(&out_trunc).is_empty(), + "staging/final files leaked on truncated BSON: {:?}", + list_dir_names(&out_trunc) + ); + + // 2. Corrupt declared document length (< 5) after valid prefix. + let mut corrupt_bytes = valid_prefix.as_bytes().to_vec(); + corrupt_bytes.extend_from_slice(&3_i32.to_le_bytes()); + corrupt_bytes.push(0); + let corrupt_path = dir.path().join("corrupt.bson"); + fs::write(&corrupt_path, &corrupt_bytes).unwrap(); + let out_corrupt = dir.path().join("out-corrupt"); + let err = run_curate_qm_bars_1m(&make_args( + corrupt_path, + mapping_path.clone(), + out_corrupt.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: prefix_len as usize, + max_doc_bytes: 1024 * 1024, + }, + )) + .expect_err("corrupt document length must fail"); + assert!( + matches!( + err, + RunCurateQmBars1mError::BsonStream { + source: BsonStreamError::CorruptDocumentLength { offset, declared_len: 3, .. }, + .. + } if offset == prefix_len + ), + "expected CorruptDocumentLength at offset {prefix_len}, got {err:?}" + ); + assert!(list_dir_names(&out_corrupt).is_empty()); + + // 3. Reader I/O failure after valid prefix. + let out_io = dir.path().join("out-io"); + let err = run_curate_qm_bars_1m_to_dir_with_hooks( + &make_args( + dir.path().join("io-fail.bson"), + mapping_path, + out_io.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: prefix_len as usize, + max_doc_bytes: 1024 * 1024, + }, + ), + PrefixThenIoErrorReader::new(valid_prefix.as_bytes().to_vec()), + |_idx, file| SyncedBufFile::new(file), + |_idx, _path| {}, + ) + .expect_err("reader I/O error must fail"); + assert!( + matches!( + err, + RunCurateQmBars1mError::BsonStream { + source: BsonStreamError::Io { offset, .. }, + .. + } if offset == prefix_len + ), + "expected BsonStreamError::Io at offset {prefix_len}, got {err:?}" + ); + assert!(list_dir_names(&out_io).is_empty()); +} + +#[test] +fn injected_sink_write_flush_and_post_preflight_hard_link_collision_roll_back_cleanly() { + let dir = TempDirGuard::new("qm-bars1m-rollback"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + let intraday_bytes = concat_docs(&[make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.8, + 10.2, + 100.0, + )]); + + // 1. Injected sink write failure (tiny batch triggers write during chunk curation). + let out_write_fail = dir.path().join("out-write-fail"); + let mut write_fail_args = make_args( + dir.path().join("in.bson"), + mapping_path.clone(), + out_write_fail.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + write_fail_args.ilp_options.max_batch_rows = 1; + let err = run_curate_qm_bars_1m_to_dir_with_hooks( + &write_fail_args, + Cursor::new(intraday_bytes.as_slice()), + |_idx, _file| FailingWriteSink { + fail_on_write: true, + fail_on_flush: false, + }, + |_idx, _path| {}, + ) + .expect_err("injected write failure must abort"); + assert!(matches!(err, RunCurateQmBars1mError::CurateWrite(_))); + assert!(list_dir_names(&out_write_fail).is_empty()); + + // 2. Injected final flush failure during IlpShardedWriter::finish(). + let out_flush_fail = dir.path().join("out-flush-fail"); + let flush_fail_args = make_args( + dir.path().join("in.bson"), + mapping_path.clone(), + out_flush_fail.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + let err = run_curate_qm_bars_1m_to_dir_with_hooks( + &flush_fail_args, + Cursor::new(intraday_bytes.as_slice()), + |_idx, _file| FailingWriteSink { + fail_on_write: false, + fail_on_flush: true, + }, + |_idx, _path| {}, + ) + .expect_err("injected flush failure must abort"); + assert!(matches!(err, RunCurateQmBars1mError::Ilp(_))); + assert!(list_dir_names(&out_flush_fail).is_empty()); + + // 3. Post-preflight hard-link collision on shard 1 after shard 0 already published. + // Verify shard 0 is rolled back, competing shard 1 and unrelated bars_1m.shard-00.ilp stay + // byte-identical, and no .tmp files remain. + let out_link_collision = dir.path().join("out-link-collision"); + fs::create_dir_all(&out_link_collision).unwrap(); + let eod_existing = out_link_collision.join("bars_1m.shard-00.ilp"); + fs::write(&eod_existing, b"keep-eod-shard").unwrap(); + let competing_shard_1 = out_link_collision.join("bars_1m_qm.shard-01.ilp"); + let competing_bytes = b"competing-writer-shard-1"; + + let err = run_curate_qm_bars_1m_to_dir_with_hooks( + &make_args( + dir.path().join("in.bson"), + mapping_path.clone(), + out_link_collision.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 3, + known_at_micros, + BsonStreamOptions::default(), + ), + Cursor::new(intraday_bytes.as_slice()), + |_idx, file| SyncedBufFile::new(file), + |shard_idx, final_path| { + if shard_idx == 1 { + fs::write(final_path, competing_bytes).expect("create competing shard 1"); + } + }, + ) + .expect_err("post-preflight collision must fail"); + assert!(matches!( + err, + RunCurateQmBars1mError::OutputFileExists { ref path } if path == &competing_shard_1 + )); + assert_eq!(fs::read(&competing_shard_1).unwrap(), competing_bytes); + assert_eq!(fs::read(&eod_existing).unwrap(), b"keep-eod-shard"); + assert_eq!( + list_dir_names(&out_link_collision), + vec!["bars_1m.shard-00.ilp", "bars_1m_qm.shard-01.ilp"] + ); + + // 4. Staging unlink failure preserves original cause and reports failed staging paths. + let out_cleanup_fail = dir.path().join("out-cleanup-fail"); + let err = run_curate_qm_bars_1m_to_dir_with_cleanup_hook( + &make_args( + dir.path().join("in.bson"), + mapping_path, + out_cleanup_fail.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + ), + Cursor::new(intraday_bytes.as_slice()), + |_idx, _file| FailingWriteSink { + fail_on_write: false, + fail_on_flush: true, + }, + |_idx, _path| {}, + |path| { + // Simulate permission denied on cleanup while still cleaning up in TempDirGuard drop. + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("injected unlink failure for {}", path.display()), + )) + }, + ) + .expect_err("cleanup failure must surface RollbackFailed"); + match err { + RunCurateQmBars1mError::RollbackFailed { cause, failures } => { + assert!(matches!(*cause, RunCurateQmBars1mError::Ilp(_))); + assert_eq!(failures.len(), 2); + for failure in &failures { + assert!(failure.final_path.starts_with(&out_cleanup_fail)); + } + } + other => panic!("expected RollbackFailed, got {other:?}"), + } +} + +#[test] +fn report_formatter_exposes_every_counter_and_isolates_elapsed_secs_on_timing_line() { + let dir = TempDirGuard::new("qm-bars1m-format"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + let intraday_bytes = concat_docs(&[make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.8, + 10.2, + 100.0, + )]); + let args = make_args( + dir.path().join("fmt.bson"), + mapping_path, + dir.path().join("unused"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report = + run_curate_qm_bars_1m_with_readers(&args, Cursor::new(intraday_bytes.as_slice()), |_idx| { + Vec::::new() + }) + .expect("format run should succeed"); + + let text = format_curate_qm_bars_1m_report(&report); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 7, "unexpected report line count:\n{text}"); + assert_eq!(lines[0], "curate-etl curate-qm-bars-1m"); + + for token in [ + "docs_framed=1", + &format!("bytes_read={}", intraday_bytes.len()), + "docs_seen=1", + "rows_decoded=1", + "rejected=0", + "missing=0", + "empty=0", + "wrong_type=0", + "invalid_ts=0", + "invalid_num=0", + "corrupt=0", + "chunks=1", + "max_rows_per_chunk=1", + "cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)", + "bars_in=1", + "keys_out_per_chunk_sum=1", + "invalid_ohlc=0", + "inconsistent_ohlc=0", + "invalid_vol=0", + "ts_out_of_range=0", + "dup_collapsed=0", + "dup_conflict_dropped=0", + "rows_in=1", + "rows_out=1", + "listings_out_per_chunk_sum=1", + "dropped_unmapped=0", + "listing_collision_collapsed=0", + "listing_collision_dropped=0", + "shards=2", + "rows_written=1", + "ilp_rows=1", + &format!("bytes={}", report.ilp_stats.bytes), + "flushes=1", + "per_shard_rows=", + ] { + assert!(text.contains(token), "report missing '{token}':\n{text}"); + } + + // Only the final timing: line carries elapsed_secs. + for line in &lines[..lines.len() - 1] { + assert!( + !line.contains("elapsed_secs"), + "non-timing line must not contain elapsed_secs: {line}" + ); + } + assert!(lines.last().unwrap().trim_start().starts_with("timing:")); + assert!(lines.last().unwrap().contains("elapsed_secs=")); +} + +// --------------------------------------------------------------------------------------------- +// QA additions (T-185): byte-level baselines, empty input, verbatim namespace, oversized docs. +// --------------------------------------------------------------------------------------------- + +/// Runs the pure `curate_and_write_qm_bars_1m` stage once per given byte slice (each slice treated +/// as one chunk) against one shared writer, returning per-shard bytes. +fn pure_stage_shard_bytes( + chunks: &[&[u8]], + mapping: &ProviderMappingTable, + mapping_source: &str, + shard_count: usize, + known_at_micros: i64, +) -> Vec> { + let sinks: Vec = (0..shard_count).map(|_| RecordingSink::new()).collect(); + let mut writer = IlpShardedWriter::new(sinks.clone(), IlpWriterOptions::default()).unwrap(); + for chunk in chunks { + let mut bars = Vec::new(); + decode_qm_intraday_buffer( + chunk, + |raw| bars.push(raw.into_eod_intraday_bar(|k, _| k)), + |_, _| {}, + ); + curate_and_write_qm_bars_1m(bars, mapping, mapping_source, &mut writer, known_at_micros) + .unwrap(); + } + writer.finish().unwrap(); + sinks + .iter() + .map(|sink| sink.bytes.lock().unwrap().clone()) + .collect() +} + +fn read_qm_shards(out_dir: &Path, shard_count: usize) -> Vec> { + (0..shard_count) + .map(|idx| fs::read(out_dir.join(format!("bars_1m_qm.shard-{idx:02}.ilp"))).unwrap()) + .collect() +} + +#[test] +fn file_mode_single_chunk_shards_match_pure_stage_byte_for_byte() { + let dir = TempDirGuard::new("qm-bars1m-qa-bytes"); + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "qm\tAAA\t2024-01-01\t\t11", + "qm\tBBB\t2024-01-01\t\t22", + "qm\tCCC\t2024-01-01\t\t33", + "qm\tDDD\t2024-01-01\t\t44", + ], + ); + let known_at_micros = et_to_utc_micros(day(2025, 3, 4), 18, 0, 0).unwrap(); + // Unsorted input across several listings/sessions with irregular (non-round) doubles so a wrong + // fixed-width encoding of any single OHLCV field would change bytes even if aggregates match. + let mut docs = Vec::new(); + for (i, code) in ["DDD", "AAA", "CCC", "BBB", "AAA", "DDD", "CCC", "BBB"] + .iter() + .enumerate() + { + let i = i as u8; + let base = 17.0 + f64::from(i) * 1.337; + docs.push(make_qm_intraday_doc_with_adjusted( + code, + et_ts_millis(2025, 3, 3, 7 + i, 3 * i), + base, + base + 0.123_456_789, + base - 0.987_654_321, + base + 0.000_001, + 1_000.5 + f64::from(i), + 3.0, + )); + } + let bytes = concat_docs(&docs); + let intraday_path = dir.path().join("qm.bson"); + fs::write(&intraday_path, &bytes).unwrap(); + + let shard_count = 3; + let out_dir = dir.path().join("out"); + let report = run_curate_qm_bars_1m(&make_args( + intraday_path, + mapping_path.clone(), + out_dir.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + shard_count, + known_at_micros, + BsonStreamOptions::default(), + )) + .unwrap(); + assert_report_conservation(&report); + assert_eq!(report.chunks, 1); + assert_eq!(report.rows_written, 8); + + let mapping = load_provider_mapping_table(&mapping_path).unwrap(); + let expected = pure_stage_shard_bytes( + &[bytes.as_slice()], + &mapping, + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + shard_count, + known_at_micros, + ); + let actual = read_qm_shards(&out_dir, shard_count); + for idx in 0..shard_count { + assert_eq!( + actual[idx], expected[idx], + "shard {idx} bytes differ from pure stage" + ); + } + assert!(expected.iter().filter(|b| !b.is_empty()).count() >= 2); +} + +#[test] +fn file_mode_multi_chunk_shards_match_pure_stage_applied_per_document_chunk() { + let dir = TempDirGuard::new("qm-bars1m-qa-chunk-bytes"); + let mapping_path = write_mapping_tsv( + dir.path(), + &["qm\tAAA\t2024-01-01\t\t11", "qm\tBBB\t2024-01-01\t\t22"], + ); + let known_at_micros = et_to_utc_micros(day(2024, 9, 4), 18, 0, 0).unwrap(); + // Equal-size docs (same code length) so chunk_capacity == doc_len yields one doc per chunk. + let docs: Vec = (0..6u8) + .map(|m| { + let code = if m % 2 == 0 { "AAA" } else { "BBB" }; + let base = 30.0 + f64::from(m) * 0.25; + make_qm_intraday_doc( + code, + et_ts_millis(2024, 9, 3, 15, 59 - m), + base, + base + 1.0, + base - 1.0, + base, + 10.0, + ) + }) + .collect(); + let doc_len = docs[0].as_bytes().len(); + assert!(docs.iter().all(|d| d.as_bytes().len() == doc_len)); + let bytes = concat_docs(&docs); + let intraday_path = dir.path().join("qm.bson"); + fs::write(&intraday_path, &bytes).unwrap(); + + let out_dir = dir.path().join("out"); + let report = run_curate_qm_bars_1m(&make_args( + intraday_path, + mapping_path.clone(), + out_dir.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: doc_len, + max_doc_bytes: 1024 * 1024, + }, + )) + .unwrap(); + assert_report_conservation(&report); + assert_eq!(report.chunks, 6); + assert_eq!(report.max_rows_per_chunk, 1); + assert_eq!( + report.curate_stats.listings_out, 6, + "per-chunk sum, not distinct" + ); + + let mapping = load_provider_mapping_table(&mapping_path).unwrap(); + let chunks: Vec<&[u8]> = bytes.chunks(doc_len).collect(); + let expected = pure_stage_shard_bytes( + &chunks, + &mapping, + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + ); + assert_eq!(read_qm_shards(&out_dir, 2), expected); +} + +#[test] +fn empty_input_publishes_all_empty_shards_with_zero_counters() { + let dir = TempDirGuard::new("qm-bars1m-qa-empty"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t1"]); + let intraday_path = dir.path().join("empty.bson"); + fs::write(&intraday_path, b"").unwrap(); + let out_dir = dir.path().join("out"); + + let report = run_curate_qm_bars_1m(&make_args( + intraday_path, + mapping_path, + out_dir.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 3, + 123, + BsonStreamOptions::default(), + )) + .expect("empty input should succeed"); + assert_report_conservation(&report); + assert_eq!(report.intraday_docs_framed, 0); + assert_eq!(report.intraday_bytes_read, 0); + assert_eq!(report.chunks, 0); + assert_eq!(report.max_rows_per_chunk, 0); + assert_eq!(report.rows_written, 0); + assert_eq!(report.ilp_stats.per_shard_rows, vec![0, 0, 0]); + assert_eq!( + list_dir_names(&out_dir), + vec![ + "bars_1m_qm.shard-00.ilp", + "bars_1m_qm.shard-01.ilp", + "bars_1m_qm.shard-02.ilp", + ] + ); + assert!(read_qm_shards(&out_dir, 3).iter().all(Vec::is_empty)); +} + +#[test] +fn nonblank_mapping_source_is_forwarded_verbatim_without_trimming() { + let dir = TempDirGuard::new("qm-bars1m-qa-verbatim"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t1"]); + let bytes = concat_docs(&[make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.8, + 10.2, + 100.0, + )]); + let args = make_args( + dir.path().join("in.bson"), + mapping_path, + dir.path().join("unused"), + " qm ", + 1, + 0, + BsonStreamOptions::default(), + ); + let report = run_curate_qm_bars_1m_with_readers(&args, Cursor::new(bytes.as_slice()), |_| { + Vec::::new() + }) + .expect("padded nonblank namespace is accepted"); + assert_report_conservation(&report); + // " qm " is not "qm": the row must be unmapped, proving the value was not trimmed. + assert_eq!(report.curate_stats.dropped_unmapped, 1); + assert_eq!(report.rows_written, 0); +} + +#[test] +fn doc_larger_than_chunk_capacity_succeeds_and_doc_over_max_doc_bytes_fails_clean() { + let dir = TempDirGuard::new("qm-bars1m-qa-oversize"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); + let docs = vec![ + make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.8, + 10.2, + 1.0, + ), + make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 1), + 10.0, + 10.5, + 9.8, + 10.2, + 2.0, + ), + ]; + let doc_len = docs[0].as_bytes().len(); + let bytes = concat_docs(&docs); + let intraday_path = dir.path().join("in.bson"); + fs::write(&intraday_path, &bytes).unwrap(); + + // Chunk capacity smaller than one document: reader grows for a single doc up to max_doc_bytes. + let out_ok = dir.path().join("out-ok"); + let report = run_curate_qm_bars_1m(&make_args( + intraday_path.clone(), + mapping_path.clone(), + out_ok.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 1, + 0, + BsonStreamOptions { + chunk_capacity_bytes: 8, + max_doc_bytes: 1024 * 1024, + }, + )) + .expect("doc larger than chunk capacity must still stream"); + assert_report_conservation(&report); + assert_eq!(report.rows_written, 2); + assert!(report.chunks >= 2); + assert_eq!(report.max_rows_per_chunk, 1); + + // max_doc_bytes below the doc length: fatal at offset 0, nothing left behind. + let out_bad = dir.path().join("out-bad"); + let err = run_curate_qm_bars_1m(&make_args( + intraday_path, + mapping_path, + out_bad.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + 0, + BsonStreamOptions { + chunk_capacity_bytes: 64 * 1024, + max_doc_bytes: doc_len - 1, + }, + )) + .expect_err("doc over max_doc_bytes must fail"); + assert!( + matches!( + err, + RunCurateQmBars1mError::BsonStream { + source: BsonStreamError::CorruptDocumentLength { offset: 0, .. }, + .. + } + ), + "got {err:?}" + ); + assert!(list_dir_names(&out_bad).is_empty()); +} diff --git a/tools/curate-etl/tests/curate_bars_1m.rs b/tools/curate-etl/tests/curate_bars_1m.rs new file mode 100644 index 00000000..f1b43972 --- /dev/null +++ b/tools/curate-etl/tests/curate_bars_1m.rs @@ -0,0 +1,635 @@ +//! End-to-end binary integration tests for `curate-etl curate-bars-1m` (`M2.3n`). + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use bson::raw::{cstr, RawDocumentBuf}; +use curate_etl::{ + et_to_utc_micros, format_curate_bars_1m_report, run_curate_bars_1m, ymd_to_epoch_days, + BsonStreamOptions, CurateBars1mArgs, IlpWriterOptions, DEFAULT_BARS_1M_MAPPING_SOURCE, +}; + +static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(tag: &str) -> Self { + let pid = std::process::id(); + let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); + let path = + std::env::temp_dir().join(format!("curate-etl-it-bars-1m-{tag}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create integration test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn run_bin(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(args) + .output() + .expect("spawn curate-etl binary") +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn et_ts_sec(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { + let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp"); + assert_eq!(micros % 1_000_000, 0); + micros / 1_000_000 +} + +fn make_intraday_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_split_doc( + qm_search_code: &str, + ex_date: &str, + for_factor: f64, + to_factor: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), qm_search_code); + doc.append(cstr!("date"), ex_date); + doc.append(cstr!("forfactor"), for_factor); + doc.append(cstr!("tofactor"), to_factor); + doc.append(cstr!("splitratio"), for_factor / to_factor); + doc +} + +fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { + let mut out = Vec::new(); + for doc in docs { + out.extend_from_slice(doc.as_bytes()); + } + out +} + +fn read_dir_files(dir: &Path) -> BTreeMap> { + let mut out = BTreeMap::new(); + for entry in fs::read_dir(dir).expect("read output dir") { + let entry = entry.expect("dir entry"); + let name = entry + .file_name() + .into_string() + .expect("UTF-8 file name in output dir"); + let bytes = fs::read(entry.path()).expect("read output file"); + out.insert(name, bytes); + } + out +} + +fn strip_timing_line(report: &str) -> Vec<&str> { + report + .lines() + .filter(|line| !line.trim_start().starts_with("timing:")) + .collect() +} + +#[test] +fn curate_bars_1m_binary_matches_direct_runner_bytes_and_report() { + let tmp = TempDir::new("parity"); + + // Pin NVDA 10:1 forward split (2024-06-10) and NEXM 1:20 reverse split (2025-06-20) + // fixtures in the style of src/run_curate_bars_1m_tests.rs. + let intraday_path = tmp.path().join("eodIntraday1M.bson"); + let intraday_bytes = concat_docs(&[ + // NVDA pre-split (2024-06-07): 10:1 split un-adjusts prices x10 and volume /10. + make_intraday_doc( + "NVDA.US", + et_ts_sec(2024, 6, 7, 15, 59), + 120.50, + 121.00, + 120.40, + 120.888, + 412_390.0, + ), + // NVDA ex-date (2024-06-10): already post-split (factor = 1.0). + make_intraday_doc( + "NVDA.US", + et_ts_sec(2024, 6, 10, 15, 59), + 121.50, + 122.00, + 121.20, + 121.79, + 350_000.0, + ), + // NEXM pre-split (2025-06-18): 1:20 reverse split un-adjusts prices x0.05 and volume x20. + make_intraday_doc( + "NEXM.V", + et_ts_sec(2025, 6, 18, 15, 59), + 24.20, + 24.40, + 24.10, + 24.29, + 5_000.0, + ), + // NEXM ex-date (2025-06-20): already post-split (factor = 1.0). + make_intraday_doc( + "NEXM.V", + et_ts_sec(2025, 6, 20, 15, 59), + 24.10, + 24.35, + 24.00, + 24.28, + 12_500.0, + ), + ]); + fs::write(&intraday_path, &intraday_bytes).expect("write intraday bson"); + + let splits_path = tmp.path().join("qmSplits.bson"); + let splits_bytes = concat_docs(&[ + make_split_doc("NVDA", "2024-06-10", 1.0, 10.0), + make_split_doc("NEXM:CA", "2025-06-20", 20.0, 1.0), + ]); + fs::write(&splits_path, &splits_bytes).expect("write splits bson"); + + let mapping_path = tmp.path().join("provider_mapping.tsv"); + fs::write( + &mapping_path, + "eod\tNVDA.US\t2000-01-01\t\t1001\n\ + qm\tNVDA\t2000-01-01\t\t1001\n\ + eod\tNEXM.V\t2000-01-01\t\t2002\n\ + qm\tNEXM:CA\t2000-01-01\t\t2002\n", + ) + .expect("write provider_mapping.tsv"); + + let known_at_micros: i64 = 1_750_000_000_000_000; + let shard_count: usize = 2; + + let bin_out = tmp.path().join("out-bin"); + let direct_out = tmp.path().join("out-direct"); + + let output = run_bin(&[ + "curate-bars-1m", + "--eod-intraday", + intraday_path.to_str().unwrap(), + "--qm-splits", + splits_path.to_str().unwrap(), + "--provider-mapping", + mapping_path.to_str().unwrap(), + "--out", + bin_out.to_str().unwrap(), + "--shards", + "2", + "--known-at-micros", + "1750000000000000", + ]); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success(), + "expected exit 0, got {:?}; stderr:\n{stderr}\nstdout:\n{stdout}", + output.status.code() + ); + assert!( + stderr.is_empty(), + "expected empty stderr on success, got:\n{stderr}" + ); + + let direct_args = CurateBars1mArgs { + intraday_path, + splits_path, + provider_mapping_path: mapping_path, + out_dir: direct_out.clone(), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count, + known_at_micros, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }; + let direct_report = run_curate_bars_1m(&direct_args).expect("direct run_curate_bars_1m"); + assert_eq!( + direct_report.rows_written, 4, + "expected 4 emitted bars_1m rows" + ); + + let direct_formatted = format_curate_bars_1m_report(&direct_report); + assert_eq!( + strip_timing_line(&stdout), + strip_timing_line(&direct_formatted), + "binary stdout report should match direct runner report excluding timing line" + ); + assert!( + stdout + .lines() + .any(|line| line.trim_start().starts_with("timing: elapsed_secs=")), + "expected timing line in stdout:\n{stdout}" + ); + + let bin_files = read_dir_files(&bin_out); + let direct_files = read_dir_files(&direct_out); + + let expected_names: Vec = vec![ + "bars_1m.shard-00.ilp".to_string(), + "bars_1m.shard-01.ilp".to_string(), + ]; + assert_eq!( + bin_files.keys().cloned().collect::>(), + expected_names, + "unexpected files in binary output dir" + ); + assert_eq!( + bin_files, direct_files, + "binary shard files must be byte-identical to direct runner output" + ); + assert!( + bin_files.values().map(Vec::len).sum::() > 0, + "expected non-empty ILP output across shards" + ); +} + +#[test] +fn curate_bars_1m_binary_missing_input_exits_nonzero_and_leaves_out_clean() { + let tmp = TempDir::new("missing-input"); + + let missing_intraday = tmp.path().join("does-not-exist.bson"); + let splits_path = tmp.path().join("qmSplits.bson"); + fs::write(&splits_path, concat_docs(&[])).expect("write empty splits bson"); + + let mapping_path = tmp.path().join("provider_mapping.tsv"); + fs::write(&mapping_path, "eod\tNVDA.US\t2000-01-01\t\t1001\n") + .expect("write provider_mapping.tsv"); + + let out_dir = tmp.path().join("out-empty"); + fs::create_dir_all(&out_dir).expect("create empty out dir"); + + let output = run_bin(&[ + "curate-bars-1m", + "--eod-intraday", + missing_intraday.to_str().unwrap(), + "--qm-splits", + splits_path.to_str().unwrap(), + "--provider-mapping", + mapping_path.to_str().unwrap(), + "--out", + out_dir.to_str().unwrap(), + "--shards", + "2", + "--known-at-micros", + "1750000000000000", + ]); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + !output.status.success(), + "expected non-zero exit when intraday file is missing" + ); + assert!( + stdout.is_empty(), + "expected no success report on stdout, got:\n{stdout}" + ); + assert!( + stderr.contains("error:") && stderr.contains("failed to open eod-intraday"), + "expected input-open error on stderr, got:\n{stderr}" + ); + + let remaining = read_dir_files(&out_dir); + assert!( + remaining.is_empty(), + "expected no shard or staging files in output dir, found: {:?}", + remaining.keys().collect::>() + ); +} + +// --------------------------------------------------------------------------- +// QA edge cases (T-186): binary-level behaviour not covered by the parity tests. +// --------------------------------------------------------------------------- + +struct Fixture { + intraday: PathBuf, + splits: PathBuf, + mapping: PathBuf, +} + +/// NVDA 10:1 split fixture: one pre-split bar (2024-06-07) and one ex-date bar (2024-06-10). +fn write_nvda_fixture(dir: &Path) -> Fixture { + let intraday = dir.join("eodIntraday1M.bson"); + fs::write( + &intraday, + concat_docs(&[ + make_intraday_doc( + "NVDA.US", + et_ts_sec(2024, 6, 7, 15, 59), + 120.50, + 121.00, + 120.40, + 120.75, + 412_390.0, + ), + make_intraday_doc( + "NVDA.US", + et_ts_sec(2024, 6, 10, 15, 59), + 121.50, + 122.00, + 121.20, + 121.75, + 350_000.0, + ), + ]), + ) + .expect("write intraday bson"); + let splits = dir.join("qmSplits.bson"); + fs::write(&splits, concat_docs(&[make_split_doc("NVDA", "2024-06-10", 1.0, 10.0)])) + .expect("write splits bson"); + let mapping = dir.join("provider_mapping.tsv"); + fs::write( + &mapping, + "eod\tNVDA.US\t2000-01-01\t\t1001\nqm\tNVDA\t2000-01-01\t\t1001\n", + ) + .expect("write provider_mapping.tsv"); + Fixture { + intraday, + splits, + mapping, + } +} + +fn bin_args<'a>( + fx: &'a Fixture, + out: &'a Path, + known_at: &'a str, + extra: &[&'a str], +) -> Vec<&'a str> { + let mut argv = vec![ + "curate-bars-1m", + "--eod-intraday", + fx.intraday.to_str().unwrap(), + "--qm-splits", + fx.splits.to_str().unwrap(), + "--provider-mapping", + fx.mapping.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + "--shards", + "2", + "--known-at-micros", + known_at, + ]; + argv.extend_from_slice(extra); + argv +} + +#[derive(Debug)] +struct IlpRow { + listing_id: i32, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, + known_at: i64, + ts: i64, +} + +/// Minimal ILP v2 `bars_1m` decoder (binary DOUBLE fields, `known_at=t`, `t\n`). +fn decode_rows(data: &[u8]) -> Vec { + let mut rows = Vec::new(); + let mut i = 0usize; + while i < data.len() { + let tag_start = i; + while data[i] != b' ' { + i += 1; + } + let tags = std::str::from_utf8(&data[tag_start..i]).unwrap(); + i += 1; + let listing_id: i32 = tags + .split(',') + .find_map(|t| t.strip_prefix("listing_id=")) + .expect("listing_id tag") + .parse() + .unwrap(); + let mut read_f64 = |name: &str| -> f64 { + let prefix = format!("{name}=="); + assert!(data[i..].starts_with(prefix.as_bytes()), "expected {prefix}"); + i += prefix.len() + 1; // skip binary DOUBLE type tag + let v = f64::from_le_bytes(data[i..i + 8].try_into().unwrap()); + i += 8; + if data[i] == b',' { + i += 1; + } + v + }; + let open = read_f64("open"); + let high = read_f64("high"); + let low = read_f64("low"); + let close = read_f64("close"); + let volume = read_f64("volume"); + assert!(data[i..].starts_with(b"known_at="), "expected known_at="); + i += b"known_at=".len(); + let ks = i; + while data[i] != b' ' { + i += 1; + } + let known_at: i64 = std::str::from_utf8(&data[ks..i]) + .unwrap() + .strip_suffix('t') + .unwrap() + .parse() + .unwrap(); + i += 1; + let ts_start = i; + while data[i] != b'\n' { + i += 1; + } + let ts: i64 = std::str::from_utf8(&data[ts_start..i]) + .unwrap() + .strip_suffix('t') + .unwrap() + .parse() + .unwrap(); + i += 1; + rows.push(IlpRow { + listing_id, + open, + high, + low, + close, + volume, + known_at, + ts, + }); + } + rows +} + +fn assert_close(actual: f64, expected: f64, what: &str) { + assert!( + (actual - expected).abs() <= 1e-9 * expected.abs().max(1.0), + "{what}: expected {expected}, got {actual}" + ); +} + +fn shard_and_staging_files(dir: &Path) -> Vec { + if !dir.exists() { + return Vec::new(); + } + read_dir_files(dir).into_keys().collect() +} + +#[test] +fn curate_bars_1m_binary_writes_known_at_verbatim_and_unadjusts_nvda_split() { + let tmp = TempDir::new("values"); + let fx = write_nvda_fixture(tmp.path()); + let out = tmp.path().join("out"); + + let output = run_bin(&bin_args(&fx, &out, "1700000000123456", &[])); + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let mut rows: Vec = read_dir_files(&out) + .values() + .flat_map(|bytes| decode_rows(bytes)) + .collect(); + rows.sort_by_key(|r| r.ts); + assert_eq!(rows.len(), 2, "rows: {rows:?}"); + + for row in &rows { + assert_eq!(row.listing_id, 1001); + assert_eq!(row.known_at, 1_700_000_000_123_456, "known_at must be verbatim"); + } + + let pre = &rows[0]; + assert_eq!(pre.ts, et_ts_sec(2024, 6, 7, 15, 59) * 1_000_000); + assert_close(pre.open, 1205.0, "pre-split open x10"); + assert_close(pre.high, 1210.0, "pre-split high x10"); + assert_close(pre.low, 1204.0, "pre-split low x10"); + assert_close(pre.close, 1207.5, "pre-split close x10"); + assert_close(pre.volume, 41_239.0, "pre-split volume /10"); + + let ex = &rows[1]; + assert_eq!(ex.ts, et_ts_sec(2024, 6, 10, 15, 59) * 1_000_000); + assert_close(ex.close, 121.75, "ex-date close unchanged"); + assert_close(ex.volume, 350_000.0, "ex-date volume unchanged"); +} + +#[test] +fn curate_bars_1m_binary_is_deterministic_across_runs() { + let tmp = TempDir::new("determinism"); + let fx = write_nvda_fixture(tmp.path()); + let out_a = tmp.path().join("out-a"); + let out_b = tmp.path().join("out-b"); + + let a = run_bin(&bin_args(&fx, &out_a, "1750000000000000", &[])); + let b = run_bin(&bin_args(&fx, &out_b, "1750000000000000", &[])); + assert!(a.status.success() && b.status.success()); + + let files_a = read_dir_files(&out_a); + assert!(!files_a.is_empty()); + assert_eq!(files_a, read_dir_files(&out_b), "repeat runs must be byte-identical"); + assert_eq!( + strip_timing_line(&String::from_utf8_lossy(&a.stdout)), + strip_timing_line(&String::from_utf8_lossy(&b.stdout)), + ); +} + +#[test] +fn curate_bars_1m_binary_refuses_to_overwrite_existing_shards() { + let tmp = TempDir::new("overwrite"); + let fx = write_nvda_fixture(tmp.path()); + let out = tmp.path().join("out"); + + let first = run_bin(&bin_args(&fx, &out, "1750000000000000", &[])); + assert!(first.status.success()); + let before = read_dir_files(&out); + + // Different known_at so any overwrite would change bytes. + let second = run_bin(&bin_args(&fx, &out, "1760000000000000", &[])); + assert!(!second.status.success(), "second run into populated --out must fail"); + assert!(second.stdout.is_empty(), "no success report expected"); + assert!(String::from_utf8_lossy(&second.stderr).starts_with("error:")); + assert_eq!( + read_dir_files(&out), + before, + "existing shards must be untouched and no staging files left" + ); +} + +#[test] +fn curate_bars_1m_binary_rejects_non_eod_mapping_source_without_output() { + let tmp = TempDir::new("mapping-source"); + let fx = write_nvda_fixture(tmp.path()); + let out = tmp.path().join("out"); + + let output = run_bin(&bin_args( + &fx, + &out, + "1750000000000000", + &["--mapping-source", "qm"], + )); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("error:") && stderr.contains("qm"), "stderr: {stderr}"); + assert!( + shard_and_staging_files(&out).is_empty(), + "no files expected in --out: {:?}", + shard_and_staging_files(&out) + ); +} + +#[test] +fn curate_bars_1m_binary_parse_error_prints_usage_hides_secret_and_writes_nothing() { + let tmp = TempDir::new("parse-error"); + let fx = write_nvda_fixture(tmp.path()); + let out = tmp.path().join("out"); + + let secret = "--mongo-uri=mongodb://user:s3cr3t_pw@localhost:27017/stock"; + let output = run_bin(&bin_args(&fx, &out, "1750000000000000", &[secret])); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("file mode only"), "stderr: {stderr}"); + assert!(stderr.contains("curate-bars-1m --eod-intraday"), "usage expected: {stderr}"); + assert!(!stderr.contains("s3cr3t_pw"), "secret leaked: {stderr}"); + assert!(!out.exists(), "parse failure must not create --out"); + + // Missing --known-at-micros: no clock fallback, nothing written. + let mut argv = bin_args(&fx, &out, "1", &[]); + argv.truncate(argv.len() - 2); + let output = run_bin(&argv); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr) + .contains("missing required flag '--known-at-micros'")); + assert!(!out.exists()); +}