From 0c33d8ae198a6d8b279319638ef7967893f05b1c Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 4 Dec 2026 15:06:51 -0500 Subject: [PATCH] =?UTF-8?q?T-210:=20M2.3s=20=E2=80=94=20Implement=20Market?= =?UTF-8?q?DataStore.macroAsOf,=20crossSection,=20QuestDB=20fx('1m'),=20an?= =?UTF-8?q?d=20copilot=201m=20routing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/data/duckdb/package.json | 1 + .../data/duckdb/src/research-copilot-store.ts | 93 ++++- .../test/duckdb-market-data-store.test.ts | 209 +++++++++++ .../test/research-copilot-store.test.ts | 154 ++++++++ libs/data/duckdb/tsconfig.json | 3 + libs/data/questdb/src/index.ts | 10 + libs/data/questdb/src/pg-executor.ts | 80 +++++ libs/data/questdb/src/schema.ts | 70 ++++ libs/data/questdb/test/questdb.test.ts | 42 ++- libs/research/src/feature-library.ts | 19 +- libs/research/src/market-data-store-duckdb.ts | 339 +++++++++++++++++- .../research/src/market-data-store-questdb.ts | 220 ++++++++++++ libs/research/src/market-data-store-routed.ts | 18 +- libs/research/src/mcp/host/stdio-host.ts | 191 +++++++++- libs/research/src/mcp/tools/analyze-signal.ts | 229 ++++++++++-- .../src/mcp/tools/vault-fenced-input.ts | 4 + libs/research/test/feature-library.test.ts | 52 ++- .../test/market-data-store-duckdb.test.ts | 224 +++++++++++- .../test/market-data-store-questdb.test.ts | 113 ++++++ .../test/market-data-store-routed.test.ts | 93 +++++ libs/research/test/mcp-analyze-signal.test.ts | 179 ++++++++- libs/research/test/mcp-stdio-host.test.ts | 92 +++++ scripts/questdb-init-m2.ts | 87 +++++ 23 files changed, 2440 insertions(+), 82 deletions(-) create mode 100644 libs/data/questdb/src/pg-executor.ts create mode 100644 scripts/questdb-init-m2.ts diff --git a/libs/data/duckdb/package.json b/libs/data/duckdb/package.json index 7636fd30..c509a91f 100644 --- a/libs/data/duckdb/package.json +++ b/libs/data/duckdb/package.json @@ -15,6 +15,7 @@ }, "dependencies": { "@duckdb/node-api": "^1.4.4-r.1", + "@stock-bot/questdb": "workspace:*", "@stock-bot/research": "workspace:*" }, "devDependencies": { diff --git a/libs/data/duckdb/src/research-copilot-store.ts b/libs/data/duckdb/src/research-copilot-store.ts index 941c2c53..c44d4802 100644 --- a/libs/data/duckdb/src/research-copilot-store.ts +++ b/libs/data/duckdb/src/research-copilot-store.ts @@ -3,15 +3,23 @@ * (`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'`. + * between the host, the underlying DuckDB store, and (when configured) the + * QuestDB intraday reader, hardcoding `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. + * `close()` idempotently releases all acquired DuckDB and QuestDB resources. + * - Any failure during open (native connection creation, store validation, or + * optional QuestDB executor startup) releases already-acquired resources + * before rejecting. */ +import { + openQuestDbPgExecutor, + type QuestDbPgExecutorConfig, + type QuestDbPgExecutorHandle, +} from '@stock-bot/questdb'; +import { createQuestDbIntradayReader } from '@stock-bot/research/market-data-store-questdb'; +import { createRoutedMarketDataStore } from '@stock-bot/research/market-data-store-routed'; import type { ManagedMarketDataStore, ResearchCopilotHostConfig, @@ -19,16 +27,23 @@ import type { } from '@stock-bot/research/mcp'; import { openDuckDbMarketDataStore } from './index'; +export type QuestDbExecutorOpener = ( + config: QuestDbPgExecutorConfig +) => Promise; + 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>; + /** Optional override for opening the QuestDB intraday executor (defaults to `openQuestDbPgExecutor`). */ + readonly openQuestDbExecutor?: QuestDbExecutorOpener; } /** - * Opens a Vault-fenced DuckDB-backed {@link ManagedMarketDataStore} from a - * validated {@link ResearchCopilotHostConfig} for `ResearchCopilotStdioHostDeps.openStore`. + * Opens a Vault-fenced DuckDB-backed (and optionally QuestDB-routed for 1m + * intraday `bars` and `fx`) {@link ManagedMarketDataStore} from a validated + * {@link ResearchCopilotHostConfig} for `ResearchCopilotStdioHostDeps.openStore`. */ export const openResearchCopilotStore = (async ( config: ResearchCopilotHostConfig, @@ -42,8 +57,66 @@ export const openResearchCopilotStore = (async ( ...(options?.env !== undefined ? { env: options.env } : {}), }); + if (config.questdb === undefined) { + return { + store: opened.store, + close: opened.close, + }; + } + + const opener = options?.openQuestDbExecutor ?? openQuestDbPgExecutor; + let questHandle: QuestDbPgExecutorHandle; + try { + questHandle = await opener(config.questdb); + } catch (err: unknown) { + await opened.close().catch(() => undefined); + throw err; + } + + let routedStore: ManagedMarketDataStore['store']; + try { + const intraday = createQuestDbIntradayReader({ + executor: questHandle.executor, + vaultCutoffTs: config.vaultCutoffTs, + vaultOperatorAuthorized: false, + }); + routedStore = createRoutedMarketDataStore({ + daily: opened.store, + intraday, + }); + } catch (err: unknown) { + await questHandle.close().catch(() => undefined); + await opened.close().catch(() => undefined); + throw err; + } + + let closePromise: Promise | null = null; + const close = (): Promise => { + if (closePromise === null) { + closePromise = (async () => { + let firstError: unknown; + try { + await questHandle.close(); + } catch (err: unknown) { + firstError = err; + } + try { + await opened.close(); + } catch (err: unknown) { + if (firstError === undefined) { + firstError = err; + } + } + if (firstError !== undefined) { + throw firstError; + } + })(); + } + return closePromise; + }; + return { - store: opened.store, - close: opened.close, + store: routedStore, + close, }; }) satisfies ResearchCopilotStdioHostDeps['openStore']; diff --git a/libs/data/duckdb/test/duckdb-market-data-store.test.ts b/libs/data/duckdb/test/duckdb-market-data-store.test.ts index 4ff5bccb..f10c9b2b 100644 --- a/libs/data/duckdb/test/duckdb-market-data-store.test.ts +++ b/libs/data/duckdb/test/duckdb-market-data-store.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { computeVaultCutoffTs, + MarketDataStoreValidationError, VaultHoldoutFenceError, type BarRecord, } from '@stock-bot/research/market-data-store'; @@ -1331,3 +1332,211 @@ describe('co-published ceo_post Vault boundary via real DuckDB (store.events + M } }); }); + +describe('macroAsOf and crossSection via real DuckDB', () => { + test('macroAsOf enforces country/indicator/date filtering, known_at <= asOf lag, Vault fence, and fail-closed provenance', async () => { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-macro-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(join(curatedRoot, 'macro'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + const vaultCutoffTs = Date.UTC(2025, 4, 1, 0, 0, 0, 0); // 2025-05-01T00:00:00Z + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES + ('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-02-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.50::DOUBLE), + ('US'::VARCHAR, 'cpi_yoy'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-03-07 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 3.00::DOUBLE), + ('CA'::VARCHAR, 'gdp_qoq'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-04-06 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 1.80::DOUBLE), + ('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-04-30', TIMESTAMPTZ '2025-05-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.25::DOUBLE) + ) AS t(country_iso, indicator, period_date, known_at, known_at_source, value) + ) TO '${join(curatedRoot, 'macro', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + try { + // Early asOf sees +1d policy_rate, hides +35d cpi_yoy and +65d gdp_qoq. + const feb = await opened.store.macroAsOf({ + countries: ['US', 'CA'], + indicators: ['policy_rate', 'cpi_yoy', 'gdp_qoq'], + from: '2025-01-01', + to: '2025-06-01', + asOf: '2025-02-15', + }); + expect(feb.rows.map(r => `${r.country_iso}:${r.indicator}`)).toEqual(['US:policy_rate']); + + // Post-cutoff to/asOf clamps strictly below 2025-05-01T00:00:00Z, hiding the at-cutoff row. + const clamped = await opened.store.macroAsOf({ + countries: ['US', 'CA'], + indicators: ['policy_rate', 'cpi_yoy', 'gdp_qoq'], + from: '2025-01-01', + to: '2025-06-01', + asOf: '2025-06-01', + }); + expect(clamped.rows.map(r => `${r.country_iso}:${r.indicator}:${r.period_date}`)).toEqual([ + 'CA:gdp_qoq:2025-01-31', + 'US:cpi_yoy:2025-01-31', + 'US:policy_rate:2025-01-31', + ]); + + // from >= vaultCutoffTs throws VaultHoldoutFenceError. + await expect( + opened.store.macroAsOf({ + countries: ['US'], + indicators: ['policy_rate'], + from: '2025-05-01', + to: '2025-05-15', + }) + ).rejects.toBeInstanceOf(VaultHoldoutFenceError); + } finally { + await opened.close(); + } + + // Corrupt provenance row fails closed with MarketDataStoreValidationError. + const corruptRoot = join(root, 'corrupt-curated'); + await mkdir(join(corruptRoot, 'macro'), { recursive: true }); + const corruptWriter = await createNodeDuckDbExecutor(); + try { + await corruptWriter.run(` + COPY ( + SELECT * FROM (VALUES + ('US'::VARCHAR, 'cpi_yoy'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-03-07 00:00:00+00', 'bad_source'::VARCHAR, 3.00::DOUBLE) + ) AS t(country_iso, indicator, period_date, known_at, known_at_source, value) + ) TO '${join(corruptRoot, 'macro', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await corruptWriter.close(); + } + const corruptOpened = await openDuckDbMarketDataStore({ + curatedRoot: corruptRoot, + vaultCutoffTs, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + try { + await expect( + corruptOpened.store.macroAsOf({ + countries: ['US'], + indicators: ['cpi_yoy'], + from: '2025-01-01', + to: '2025-04-01', + }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + } finally { + await corruptOpened.close(); + } + }); + + test('crossSection joins versioned features to survivorship-free universe, null-fills missing/delayed rows, and enforces Vault fence', async () => { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-xsec-')); + 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(join(curatedRoot, 'features', 'ret_1d', 'v1', 'year=2025'), { recursive: true }); + await mkdir(join(curatedRoot, 'features', 'rsi_14', 'v1', 'year=2025'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + const vaultCutoffTs = Date.UTC(2025, 4, 15, 0, 0, 0, 0); // 2025-05-15T00:00:00Z + const writer = await createNodeDuckDbExecutor(); + try { + // Active on 2025-05-10: 101 (USD), 102 (USD), 201 (CAD). Delisted earlier: 103 (USD, 2025-04-01). + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (101::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 10.0::DOUBLE, 11.0::DOUBLE, 9.5::DOUBLE, 10.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00'), + (102::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 20.0::DOUBLE, 21.0::DOUBLE, 19.5::DOUBLE, 20.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00'), + (103::INTEGER, DATE '2025-04-01', TIMESTAMPTZ '2025-04-01 20:00:00+00', 5.0::DOUBLE, 5.5::DOUBLE, 4.5::DOUBLE, 5.0::DOUBLE, 500.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-04-01 20:00:00+00'), + (201::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 30.0::DOUBLE, 31.0::DOUBLE, 29.5::DOUBLE, 30.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '2025-05-09 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) + `); + + // ret_1d@v1: 101 known on 2025-05-09; 102 delayed until 2025-05-12; 201 known on 2025-05-09. + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (101::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', 0.02::DOUBLE), + (102::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-12 20:00:00+00', 0.05::DOUBLE), + (201::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', -0.01::DOUBLE) + ) AS t(listing_id, ts, known_at, value) + ) TO '${join(curatedRoot, 'features', 'ret_1d', 'v1', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + + // rsi_14@v1: only listing 101 present. + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (101::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', 62.5::DOUBLE) + ) AS t(listing_id, ts, known_at, value) + ) TO '${join(curatedRoot, 'features', 'rsi_14', 'v1', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + try { + // Omitted asOf defaults to q.date (2025-05-09) so 102's delayed ret_1d (known 2025-05-12) is NULL. + const usSameDay = await opened.store.crossSection({ + features: ['ret_1d@v1', 'rsi_14@v1'], + date: '2025-05-09', + universe: 'US_EQ', + }); + expect(usSameDay.columns).toEqual(['listing_id', 'ret_1d@v1', 'rsi_14@v1']); + expect(usSameDay.rows).toEqual([ + { listing_id: 101, 'ret_1d@v1': 0.02, 'rsi_14@v1': 62.5 }, + { listing_id: 102, 'ret_1d@v1': null, 'rsi_14@v1': null }, + ]); + + // Explicit later asOf (2025-05-13) reveals 102's delayed ret_1d@v1 while US_CA_EQ includes 201. + const usCaLater = await opened.store.crossSection({ + features: ['ret_1d@v1', 'rsi_14@v1'], + date: '2025-05-09', + universe: 'US_CA_EQ', + asOf: '2025-05-13', + }); + expect(usCaLater.rows).toEqual([ + { listing_id: 101, 'ret_1d@v1': 0.02, 'rsi_14@v1': 62.5 }, + { listing_id: 102, 'ret_1d@v1': 0.05, 'rsi_14@v1': null }, + { listing_id: 201, 'ret_1d@v1': -0.01, 'rsi_14@v1': null }, + ]); + + // Post-cutoff date throws VaultHoldoutFenceError. + await expect( + opened.store.crossSection({ + features: ['ret_1d@v1'], + date: '2025-05-15', + universe: 'US_EQ', + }) + ).rejects.toBeInstanceOf(VaultHoldoutFenceError); + } finally { + await opened.close(); + } + }); +}); diff --git a/libs/data/duckdb/test/research-copilot-store.test.ts b/libs/data/duckdb/test/research-copilot-store.test.ts index 2c1acc40..5b15c8ba 100644 --- a/libs/data/duckdb/test/research-copilot-store.test.ts +++ b/libs/data/duckdb/test/research-copilot-store.test.ts @@ -527,4 +527,158 @@ describe('openResearchCopilotStore (@duckdb/node-api)', () => { expect(connCloseSpy).toHaveBeenCalledTimes(0); expect(instCloseSpy).toHaveBeenCalledTimes(1); }); + + test('composes QuestDB intraday bars(1m) and fx(1m) routing when config.questdb is set, enforces vaultOperatorAuthorized: false, and closes both handles idempotently', async () => { + const { curatedRoot, duckTempDir } = await buildBarsFixture(); + const questQueries: Array<{ readonly sql: string; readonly params: readonly unknown[] | undefined }> = + []; + let questCloses = 0; + + const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); + + const config = buildHostConfig(curatedRoot, { + questdb: { + host: '127.0.0.1', + port: 8812, + database: 'qdb', + }, + }); + + const handle = await openResearchCopilotStore(config, { + env: buildDuckDbBudgetEnv(duckTempDir), + openQuestDbExecutor: async qCfg => { + expect(qCfg).toEqual(config.questdb); + return { + executor: { + async query(sql, params) { + questQueries.push({ sql, params }); + if (sql.includes('FROM fx_1m')) { + return { + rows: [ + { + pair: 'USDCAD', + ts_us: (BigInt(Date.UTC(2025, 4, 30, 14, 30, 0)) * 1000n).toString(), + open: 1.36, + high: 1.362, + low: 1.359, + close: 1.361, + source: 'polygon', + }, + ], + }; + } + return { + rows: [ + { + listing_id: String(LISTING_ID), + ts_us: (BigInt(Date.UTC(2025, 4, 30, 14, 30, 0)) * 1000n).toString(), + open: 100.5, + high: 101.0, + low: 100.0, + close: 100.8, + volume: 5000, + vwap: 100.7, + known_at_us: (BigInt(Date.UTC(2025, 4, 30, 14, 31, 0)) * 1000n).toString(), + }, + ], + }; + }, + }, + async close() { + questCloses += 1; + }, + }; + }, + }); + + try { + expect(Object.keys(handle).sort()).toEqual(['close', 'store']); + + // Daily 1d bars route to DuckDB. + const bars1d = await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-05-28', + to: '2025-06-05', + adjustment: 'raw', + }) + ); + expect(bars1d).toEqual([EXPECTED_VISIBLE_BAR]); + expect(questQueries).toHaveLength(0); + + // Intraday 1m bars route to QuestDB. + const bars1m = await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-05-30T14:30:00Z', + to: '2025-05-30T14:35:00Z', + adjustment: 'raw', + }) + ); + expect(bars1m).toHaveLength(1); + expect(questQueries).toHaveLength(1); + + // Intraday 1m fx routes to QuestDB. + const fx1m = await handle.store.fx({ + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-05-30T14:30:00Z', + to: '2025-05-30T14:35:00Z', + }); + expect(fx1m.rows).toHaveLength(1); + expect(questQueries).toHaveLength(2); + + // Vault evaluation scope remains blocked on 1m bars. + await expect( + collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-01T14:30:00Z', + to: '2025-06-01T14:35:00Z', + adjustment: 'raw', + scope: 'vault_evaluation_only', + }) + ) + ).rejects.toBeInstanceOf(VaultScopeNotAuthorizedError); + } finally { + await handle.close(); + await handle.close(); // idempotent + } + + expect(questCloses).toBe(1); + expect(connCloseSpy).toHaveBeenCalledTimes(1); + expect(instCloseSpy).toHaveBeenCalledTimes(1); + }); + + test('fail-closed: closes DuckDB connection and instance when QuestDB executor open fails', async () => { + const { curatedRoot, duckTempDir } = await buildBarsFixture(); + const questFailure = new Error('QuestDB PGWire unreachable'); + const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); + + let openErr: unknown; + try { + await openResearchCopilotStore( + buildHostConfig(curatedRoot, { + questdb: { host: '127.0.0.1', port: 8812, database: 'qdb' }, + }), + { + env: buildDuckDbBudgetEnv(duckTempDir), + openQuestDbExecutor: async () => { + throw questFailure; + }, + } + ); + } catch (err) { + openErr = err; + } + + expect(openErr).toBe(questFailure); + expect(connCloseSpy).toHaveBeenCalledTimes(1); + expect(instCloseSpy).toHaveBeenCalledTimes(1); + }); }); diff --git a/libs/data/duckdb/tsconfig.json b/libs/data/duckdb/tsconfig.json index 49cb7b59..ca6e0320 100644 --- a/libs/data/duckdb/tsconfig.json +++ b/libs/data/duckdb/tsconfig.json @@ -9,6 +9,9 @@ "references": [ { "path": "../../research" + }, + { + "path": "../questdb" } ] } diff --git a/libs/data/questdb/src/index.ts b/libs/data/questdb/src/index.ts index 6036ae94..90102ae0 100644 --- a/libs/data/questdb/src/index.ts +++ b/libs/data/questdb/src/index.ts @@ -27,12 +27,22 @@ export { type IlpV2EncodeErrorKind, } from './ilp-v2-writer'; export { + applyM2IntradayDDL, formatCreateTableSQL, getM2IntradayDDL, M2_INTRADAY_SCHEMAS, + M2_INTRADAY_TABLE_NAMES, QuestDBSchemaManager, + type ApplyM2IntradayDDLOptions, + type ApplyM2IntradayDDLResult, type M2IntradayTableName, } from './schema'; +export { + openQuestDbPgExecutor, + type QuestDbPgExecutorConfig, + type QuestDbPgExecutorHandle, + type QuestDbPgQueryExecutor, +} from './pg-executor'; // Types export type { diff --git a/libs/data/questdb/src/pg-executor.ts b/libs/data/questdb/src/pg-executor.ts new file mode 100644 index 00000000..c89da4f4 --- /dev/null +++ b/libs/data/questdb/src/pg-executor.ts @@ -0,0 +1,80 @@ +import { Pool, type PoolConfig } from 'pg'; + +export interface QuestDbPgExecutorConfig { + readonly url?: string; + readonly host?: string; + readonly port?: number; + readonly database?: string; + readonly user?: string; + readonly password?: string; + readonly ssl?: boolean; + readonly max?: number; + readonly connectionTimeoutMillis?: number; + readonly idleTimeoutMillis?: number; +} + +export interface QuestDbPgQueryExecutor { + query( + sql: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Record[] }>; +} + +export interface QuestDbPgExecutorHandle { + readonly executor: QuestDbPgQueryExecutor; + close(): Promise; +} + +/** + * Opens a lightweight PGWire `pg.Pool` executor for QuestDB read queries or + * opt-in DDL without creating legacy tables or starting background health timers. + */ +export async function openQuestDbPgExecutor( + config: QuestDbPgExecutorConfig +): Promise { + const poolConfig: PoolConfig = { + max: config.max ?? 4, + connectionTimeoutMillis: config.connectionTimeoutMillis ?? 5_000, + idleTimeoutMillis: config.idleTimeoutMillis ?? 30_000, + ...(config.url !== undefined + ? { connectionString: config.url } + : { + host: config.host ?? 'localhost', + port: config.port ?? 8812, + database: config.database ?? 'qdb', + ...(config.user !== undefined ? { user: config.user } : {}), + ...(config.password !== undefined ? { password: config.password } : {}), + }), + ...(config.ssl !== undefined ? { ssl: config.ssl } : {}), + }; + + const pool = new Pool(poolConfig); + try { + await pool.query('SELECT 1'); + } catch (err: unknown) { + await pool.end().catch(() => undefined); + throw err; + } + + let closePromise: Promise | null = null; + const close = (): Promise => { + if (closePromise === null) { + closePromise = pool.end(); + } + return closePromise; + }; + + const executor: QuestDbPgQueryExecutor = { + async query(sql: string, params?: readonly unknown[]) { + const result = + params !== undefined && params.length > 0 + ? await pool.query(sql, [...params]) + : await pool.query(sql); + return { + rows: result.rows as readonly Record[], + }; + }, + }; + + return { executor, close }; +} diff --git a/libs/data/questdb/src/schema.ts b/libs/data/questdb/src/schema.ts index 6e8458d2..65462776 100644 --- a/libs/data/questdb/src/schema.ts +++ b/libs/data/questdb/src/schema.ts @@ -6,6 +6,14 @@ import type { ColumnSchema, QuestDBQueryable, TableSchema } from './types'; export type M2IntradayTableName = 'bars_1m' | 'fx_1m' | 'bar_revisions'; +export const M2_INTRADAY_TABLE_NAMES = [ + 'bars_1m', + 'fx_1m', + 'bar_revisions', +] as const satisfies readonly M2IntradayTableName[]; + +const M2_INTRADAY_TABLE_NAME_SET: ReadonlySet = new Set(M2_INTRADAY_TABLE_NAMES); + /** * Contract schemas for M2 QuestDB 10.2.0 intraday tables (`design/DATA-CONTRACTS.md` §3.B). * Kept opt-in (outside `QuestDBSchemaManager.initializeDatabase()`). @@ -144,6 +152,68 @@ export function getM2IntradayDDL(): Record { }; } +export interface ApplyM2IntradayDDLOptions { + /** Subset of M2 intraday tables to initialize. Defaults to all three (`bars_1m`, `fx_1m`, `bar_revisions`). */ + readonly tables?: readonly M2IntradayTableName[]; +} + +export interface ApplyM2IntradayDDLResult { + readonly appliedTables: readonly M2IntradayTableName[]; + readonly statements: readonly string[]; +} + +/** + * Opt-in initializer that executes `CREATE TABLE IF NOT EXISTS` DDL from + * {@link getM2IntradayDDL} for `bars_1m`, `fx_1m`, and `bar_revisions`. + * + * Kept strictly opt-in and never invoked by `QuestDBSchemaManager.initializeDatabase()` + * or `QuestDBClient.connect()`. + */ +export async function applyM2IntradayDDL( + client: { query(sql: string, params?: readonly unknown[]): Promise }, + options?: ApplyM2IntradayDDLOptions +): Promise { + if (typeof client !== 'object' || client === null || typeof client.query !== 'function') { + throw new Error('Expected a QuestDB queryable client with a query(sql) method.'); + } + + let tables: M2IntradayTableName[]; + if (options?.tables === undefined) { + tables = [...M2_INTRADAY_TABLE_NAMES]; + } else { + if (!Array.isArray(options.tables) || options.tables.length === 0) { + throw new Error('Expected a non-empty array of M2 intraday table names.'); + } + const seen = new Set(); + tables = []; + for (const rawName of options.tables) { + if (typeof rawName !== 'string' || !M2_INTRADAY_TABLE_NAME_SET.has(rawName)) { + throw new Error( + `Unknown M2 intraday table "${String(rawName)}". Expected one of: ${M2_INTRADAY_TABLE_NAMES.join(', ')}.` + ); + } + const name = rawName as M2IntradayTableName; + if (!seen.has(name)) { + seen.add(name); + tables.push(name); + } + } + } + + const ddl = getM2IntradayDDL(); + const statements: string[] = []; + for (const table of tables) { + const sql = ddl[table]; + await client.query(sql); + statements.push(sql); + } + + return { + appliedTables: tables, + statements, + }; +} + /** * QuestDB Schema Manager * diff --git a/libs/data/questdb/test/questdb.test.ts b/libs/data/questdb/test/questdb.test.ts index 80a682f3..6cd925dd 100644 --- a/libs/data/questdb/test/questdb.test.ts +++ b/libs/data/questdb/test/questdb.test.ts @@ -2,7 +2,12 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test'; import { QuestDBHealthMonitor } from '../src/health'; import { QuestDBInfluxWriter } from '../src/influx-writer'; import { QuestDBQueryBuilder } from '../src/query-builder'; -import { QuestDBSchemaManager } from '../src/schema'; +import { + applyM2IntradayDDL, + getM2IntradayDDL, + M2_INTRADAY_TABLE_NAMES, + QuestDBSchemaManager, +} from '../src/schema'; import type { OHLCVData, QuestDBClientConfig, TradeData } from '../src/types'; // Simple in-memory QuestDB client for testing @@ -474,6 +479,41 @@ describe('QuestDB', () => { expect(stats.min_timestamp).toBeDefined(); expect(stats.max_timestamp).toBeDefined(); }); + + it('applyM2IntradayDDL executes getM2IntradayDDL() for bars_1m, fx_1m, and bar_revisions without altering initializeDatabase()', async () => { + const executed: string[] = []; + const mockQueryable = { + query: mock(async (sql: string) => { + executed.push(sql); + return { rows: [], count: 0 }; + }), + }; + + const expectedDdl = getM2IntradayDDL(); + const result = await applyM2IntradayDDL(mockQueryable); + expect(result.appliedTables).toEqual([...M2_INTRADAY_TABLE_NAMES]); + expect(executed).toEqual([ + expectedDdl.bars_1m, + expectedDdl.fx_1m, + expectedDdl.bar_revisions, + ]); + + // Subset option executes only requested tables in deduplicated order. + executed.length = 0; + const subset = await applyM2IntradayDDL(mockQueryable, { + tables: ['fx_1m', 'bars_1m', 'fx_1m'], + }); + expect(subset.appliedTables).toEqual(['fx_1m', 'bars_1m']); + expect(executed).toEqual([expectedDdl.fx_1m, expectedDdl.bars_1m]); + + // Rejects unknown or empty table lists. + await expect(applyM2IntradayDDL(mockQueryable, { tables: [] })).rejects.toThrow(); + await expect( + applyM2IntradayDDL(mockQueryable, { + tables: ['unknown_table' as unknown as 'bars_1m'], + }) + ).rejects.toThrow(); + }); }); describe('QuestDBHealthMonitor', () => { diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts index 680a3bf1..9cdacf43 100644 --- a/libs/research/src/feature-library.ts +++ b/libs/research/src/feature-library.ts @@ -61,10 +61,12 @@ export type FeatureKind = (typeof FEATURE_KINDS)[number]; export const FEATURE_INPUT_DATASETS = [ 'bars_1d', 'adj_factors', + 'corporate_actions', 'events', 'shorts', 'fx_1d', 'fundamentals_pit', + 'macro', ] as const; export type FeatureInputDataset = (typeof FEATURE_INPUT_DATASETS)[number]; @@ -553,7 +555,7 @@ type SqlToken = interface DatasetScanSpec { readonly relativePath: string; readonly hivePartitioning: boolean; - readonly predicateKind: 'ts_and_known_at' | 'known_at' | 'effective_known_at'; + readonly predicateKind: 'ts_and_known_at' | 'known_at' | 'effective_known_at' | 'macro_known_at'; } const DATASET_SCAN_SPECS: Readonly> = { @@ -567,6 +569,11 @@ const DATASET_SCAN_SPECS: Readonly> hivePartitioning: false, predicateKind: 'known_at', }, + corporate_actions: { + relativePath: 'corporate_actions/part.parquet', + hivePartitioning: false, + predicateKind: 'known_at', + }, events: { relativePath: 'events/year=*/part.parquet', hivePartitioning: true, @@ -587,6 +594,11 @@ const DATASET_SCAN_SPECS: Readonly> hivePartitioning: true, predicateKind: 'effective_known_at', }, + macro: { + relativePath: 'macro/part.parquet', + hivePartitioning: false, + predicateKind: 'macro_known_at', + }, }; function isPlainRecord(value: unknown): value is Record { @@ -1959,6 +1971,11 @@ function expandSqlForYear( } else if (spec.predicateKind === 'effective_known_at') { parts.push(`(SELECT * FROM ${readCall} WHERE effective_known_at <= ?)`); scanParams.push(knownAtUpperIso); + } else if (spec.predicateKind === 'macro_known_at') { + parts.push( + `(SELECT * FROM ${readCall} WHERE known_at <= ? AND known_at_source = 'publication_lag_estimate')` + ); + scanParams.push(knownAtUpperIso); } else { parts.push(`(SELECT * FROM ${readCall} WHERE known_at <= ?)`); scanParams.push(knownAtUpperIso); diff --git a/libs/research/src/market-data-store-duckdb.ts b/libs/research/src/market-data-store-duckdb.ts index 02a95cde..55cd3c61 100644 --- a/libs/research/src/market-data-store-duckdb.ts +++ b/libs/research/src/market-data-store-duckdb.ts @@ -94,6 +94,8 @@ const STRICT_INT_RE = /^-?\d+$/; const STRICT_UINT_RE = /^\d+$/; const SNAPSHOT_CHECKSUM_RE = /^0x[0-9a-f]{16}$/; const FD_HANDLE_PATH_RE = /^\/(?:proc\/self|dev)\/fd\/[1-9]\d*$/; +const CROSS_SECTION_FEATURE_REF_RE = /^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$/; +const MACRO_REQUIRED_KNOWN_AT_SOURCE = 'publication_lag_estimate'; export const ADJ_SNAPSHOT_FORMAT_VERSION = 1; export const ADJ_SNAPSHOT_KV_PREFIX = 'stock_bot.adj_factors.'; @@ -157,6 +159,15 @@ export const FX_1D_COLUMNS = [ 'known_at', ] as const; +export const MACRO_COLUMNS = [ + 'country_iso', + 'indicator', + 'period_date', + 'known_at', + 'known_at_source', + 'value', +] as const; + export const FUNDAMENTALS_PIT_VALUE_FIELDS = [ 'revenue', 'net_income', @@ -219,6 +230,15 @@ const FX_1D_SCHEMA: readonly TableColumnSpec[] = [ { name: 'known_at', kind: 'safe_int', nullable: false }, ]; +const MACRO_SCHEMA: readonly TableColumnSpec[] = [ + { name: 'country_iso', kind: 'string', nullable: false }, + { name: 'indicator', kind: 'string', nullable: false }, + { name: 'period_date', kind: 'string', nullable: false }, + { name: 'known_at', kind: 'safe_int', nullable: false }, + { name: 'known_at_source', kind: 'string', nullable: false }, + { name: 'value', kind: 'number', nullable: false }, +]; + const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [ { name: 'listing_id', kind: 'int32', nullable: false }, { name: 'effective_known_at', kind: 'safe_int', nullable: false }, @@ -399,6 +419,8 @@ export type ShortsAsOfQuery = Parameters[0]; export type FxQuery = Parameters[0]; export type UniverseQuery = Parameters[0]; export type FundamentalsAsOfQuery = Parameters[0]; +export type MacroAsOfQuery = Parameters[0]; +export type CrossSectionQuery = Parameters[0]; /** * Thrown when a `MarketDataStore` method or timeframe is outside the curated @@ -683,16 +705,89 @@ function validateFxPair(raw: unknown): (typeof FX_PAIR_MAP)[keyof typeof FX_PAIR ); } -function validateUniverseRef(raw: unknown): readonly string[] { +function validateUniverseRef(raw: unknown, field = 'ref'): readonly string[] { if (typeof raw === 'string' && Object.prototype.hasOwnProperty.call(UNIVERSE_CURRENCY_MAP, raw)) { return UNIVERSE_CURRENCY_MAP[raw as SupportedUniverseRef]; } throw new MarketDataStoreValidationError( `Unsupported universe ref "${String(raw)}". Expected one of: ${UNIVERSE_REFS.join(', ')}.`, - 'ref' + field ); } +function validateNonEmptyStringArray(raw: unknown, field: 'countries' | 'indicators'): string[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + `Expected a non-empty array of non-empty strings for "${field}".`, + field + ); + } + + const seen = new Set(); + const normalized: string[] = []; + for (let i = 0; i < raw.length; i += 1) { + const item: unknown = raw[i]; + if (typeof item !== 'string' || item.trim().length === 0) { + throw new MarketDataStoreValidationError( + `Invalid non-empty string at ${field}[${i}]: ${String(item)}.`, + field + ); + } + if (!seen.has(item)) { + seen.add(item); + normalized.push(item); + } + } + return normalized; +} + +interface ParsedCrossSectionFeatureRef { + readonly ref: string; + readonly name: string; + readonly version: number; +} + +function validateCrossSectionFeatures(raw: unknown): ParsedCrossSectionFeatureRef[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + 'Expected a non-empty array of versioned feature refs ("@v") for "features".', + 'features' + ); + } + + const seen = new Set(); + const parsed: ParsedCrossSectionFeatureRef[] = []; + for (let i = 0; i < raw.length; i += 1) { + const item: unknown = raw[i]; + if (typeof item !== 'string') { + throw new MarketDataStoreValidationError( + `Invalid feature ref at features[${i}]: ${String(item)}. Expected "@v".`, + 'features' + ); + } + const match = CROSS_SECTION_FEATURE_REF_RE.exec(item); + if (match === null) { + throw new MarketDataStoreValidationError( + `Invalid feature ref "${item}" at features[${i}]. Expected "@v" with lowercase name and canonical positive integer version.`, + 'features' + ); + } + const name = match[1] as string; + const version = Number(match[2]); + if (!Number.isSafeInteger(version) || version < 1) { + throw new MarketDataStoreValidationError( + `Invalid feature version in ref "${item}" at features[${i}]. Expected a positive safe integer.`, + 'features' + ); + } + if (!seen.has(item)) { + seen.add(item); + parsed.push({ ref: item, name, version }); + } + } + return parsed; +} + function validateUniverseLookbackDays(raw: unknown, vaultCutoffTs?: number): number { const days = raw === undefined ? DEFAULT_UNIVERSE_LOOKBACK_DAYS : raw; if (typeof days !== 'number' || !Number.isSafeInteger(days) || days < 1) { @@ -1813,6 +1908,172 @@ export function planFundamentalsAsOfQuery( return planFundamentalsAsOfInternal(q, ctx).planned; } +/** + * Plans a Vault-fenced DuckDB SQL query for point-in-time curated macro series + * (`macro/part.parquet`). + */ +export function planMacroAsOfQuery(q: MacroAsOfQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { + const curatedRoot = validateContext(ctx); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a macroAsOf query object.', 'query'); + } + + const countries = validateNonEmptyStringArray(q.countries, 'countries'); + const indicators = validateNonEmptyStringArray(q.indicators, 'indicators'); + const fenced = applyVaultFence( + { + from: q.from, + to: q.to, + asOf: q.asOf, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + } + ); + + const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); + const fromDate = formatUtcDate(fenced.fromMs); + const toDate = formatUtcDate(fenced.toMs); + const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); + const macroPath = joinCuratedPath(curatedRoot, 'macro/part.parquet'); + const countryPlaceholders = buildPlaceholders(countries.length); + const indicatorPlaceholders = buildPlaceholders(indicators.length); + + const sql = + 'SELECT m.country_iso, m.indicator, CAST(m.period_date AS VARCHAR) AS period_date, epoch_ms(m.known_at) AS known_at, m.known_at_source, m.value ' + + `FROM read_parquet('${macroPath}') AS m ` + + `WHERE m.country_iso IN (${countryPlaceholders}) AND m.indicator IN (${indicatorPlaceholders}) AND m.period_date >= ? AND m.period_date <= ? AND m.known_at <= ? ` + + 'ORDER BY m.country_iso ASC, m.indicator ASC, m.period_date ASC'; + const params: DuckDbParam[] = [...countries, ...indicators, fromDate, toDate, asOfIso]; + return { sql, params, fenced }; +} + +interface PlannedCrossSectionInternal { + readonly planned: PlannedDuckDbQuery; + readonly columns: readonly string[]; + readonly schema: readonly TableColumnSpec[]; +} + +function planCrossSectionInternal( + q: CrossSectionQuery, + ctx: DuckDbPlanContext +): PlannedCrossSectionInternal { + const curatedRoot = validateContext(ctx); + const lookbackDays = validateUniverseLookbackDays(ctx.universeLookbackDays); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a crossSection query object.', 'query'); + } + + const features = validateCrossSectionFeatures(q.features); + const currencies = validateUniverseRef(q.universe, 'universe'); + if (typeof q.date !== 'string' || !DATE_ONLY_RE.test(q.date)) { + throw new MarketDataStoreValidationError( + `Invalid crossSection date "${String(q.date)}". Expected a UTC calendar date in YYYY-MM-DD format.`, + 'date' + ); + } + + const rawAsOf = q.asOf ?? q.date; + let fenced: FencedTimeRange; + try { + fenced = applyVaultFence( + { + from: q.date, + to: q.date, + asOf: rawAsOf, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + } + ); + } catch (err: unknown) { + if ( + err instanceof MarketDataStoreValidationError && + (err.field === 'from' || err.field === 'to' || (err.field === 'asOf' && q.asOf === undefined)) + ) { + throw new MarketDataStoreValidationError(err.message, 'date'); + } + throw err; + } + + const lookbackStartMs = fenced.fromMs - lookbackDays * MS_PER_DAY; + if (!Number.isSafeInteger(lookbackStartMs) || lookbackStartMs < MIN_ISO_DATE_EPOCH_MS) { + throw new MarketDataStoreValidationError( + `Invalid universeLookbackDays "${lookbackDays}". Lookback start precedes supported YYYY-MM-DD UTC date range.`, + 'universeLookbackDays' + ); + } + + const lookbackStartDate = formatUtcDate(lookbackStartMs); + const endDate = formatUtcDate(fenced.toMs); + const fromIso = formatUtcIsoWithMicros(fenced.fromMs, 0); + const toIso = formatUtcIsoWithMicros(fenced.toMs, resolveToSubMsMicros(q.date, fenced)); + const asOfIso = formatUtcIsoWithMicros( + fenced.asOfMs, + resolveAsOfSubMsMicros(rawAsOf, q.date, fenced) + ); + const featureYear = new Date(fenced.fromMs).getUTCFullYear(); + + const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet'); + const currencyPredicate = + currencies.length === 1 + ? 'b.currency = ?' + : `b.currency IN (${buildPlaceholders(currencies.length)})`; + + const ctes: string[] = [ + `u AS (SELECT DISTINCT b.listing_id FROM read_parquet('${barsPath}', hive_partitioning = true) AS b WHERE ${currencyPredicate} AND b.session_date >= ? AND b.session_date <= ? AND b.ts <= ? AND b.known_at <= ?)`, + ]; + const params: DuckDbParam[] = [...currencies, lookbackStartDate, endDate, toIso, asOfIso]; + + const selectCols: string[] = ['u.listing_id']; + const joins: string[] = []; + const columns: string[] = ['listing_id']; + const schema: TableColumnSpec[] = [{ name: 'listing_id', kind: 'int32', nullable: false }]; + + for (let i = 0; i < features.length; i += 1) { + const feat = features[i] as ParsedCrossSectionFeatureRef; + const alias = `f_${i}`; + const featurePath = joinCuratedPath( + curatedRoot, + `features/${feat.name}/v${feat.version}/year=*/part.parquet` + ); + ctes.push( + `${alias} AS (SELECT f.listing_id, f.value FROM read_parquet('${featurePath}', hive_partitioning = true) AS f WHERE CAST(f.year AS BIGINT) = ? AND f.ts >= ? AND f.ts <= ? AND f.known_at <= ? QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.ts DESC, f.known_at DESC) = 1)` + ); + params.push(featureYear, fromIso, toIso, asOfIso); + selectCols.push(`${alias}.value AS "${feat.ref}"`); + joins.push(`LEFT JOIN ${alias} ON u.listing_id = ${alias}.listing_id`); + columns.push(feat.ref); + schema.push({ name: feat.ref, kind: 'number', nullable: true }); + } + + const sql = + `WITH ${ctes.join(', ')} ` + + `SELECT ${selectCols.join(', ')} ` + + `FROM u ${joins.join(' ')} ` + + 'ORDER BY u.listing_id ASC'; + + return { + planned: { sql, params, fenced }, + columns, + schema, + }; +} + +/** + * Plans a Vault-fenced DuckDB SQL query joining versioned curated feature + * Parquet datasets (`features//v/year=*\/part.parquet`) onto the + * survivorship-free active universe on `q.date`. + */ +export function planCrossSectionQuery( + q: CrossSectionQuery, + ctx: DuckDbPlanContext +): PlannedDuckDbQuery { + return planCrossSectionInternal(q, ctx).planned; +} + function readRequiredInt32(row: Record, key: string, rowIndex: number): number { const val = row[key]; if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) { @@ -1996,6 +2257,66 @@ function mapTableRows( }; } +function parseStrictPeriodDateMs(periodDate: string, rowIndex: number): number { + if (!DATE_ONLY_RE.test(periodDate)) { + throw new MarketDataStoreValidationError( + `Invalid macro period_date "${periodDate}" in result row ${rowIndex}. Expected YYYY-MM-DD.`, + 'period_date' + ); + } + try { + return applyVaultFence( + { from: periodDate, to: periodDate, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ).fromMs; + } catch { + throw new MarketDataStoreValidationError( + `Invalid macro period_date "${periodDate}" in result row ${rowIndex}.`, + 'period_date' + ); + } +} + +function mapMacroRows( + rows: readonly TableRow[], + vaultCutoffTs: number, + asOfMs: number +): Table { + const table = mapTableRows(MACRO_COLUMNS, MACRO_SCHEMA, rows); + for (let i = 0; i < table.rows.length; i += 1) { + const row = table.rows[i] as TableRow; + const knownAtSource = row.known_at_source as string; + if (knownAtSource !== MACRO_REQUIRED_KNOWN_AT_SOURCE) { + throw new MarketDataStoreValidationError( + `Invalid macro provenance known_at_source "${knownAtSource}" in result row ${i}. Expected "${MACRO_REQUIRED_KNOWN_AT_SOURCE}".`, + 'known_at_source' + ); + } + const periodDate = row.period_date as string; + const periodDateMs = parseStrictPeriodDateMs(periodDate, i); + const knownAt = row.known_at as number; + if (knownAt < periodDateMs + MS_PER_DAY) { + throw new MarketDataStoreValidationError( + `Unlagged macro row ${i}: known_at (${knownAt}) precedes period_date + 1d (${periodDateMs + MS_PER_DAY}).`, + 'known_at' + ); + } + if (knownAt >= vaultCutoffTs) { + throw new MarketDataStoreValidationError( + `Macro row ${i} known_at (${knownAt}) reaches or exceeds Vault cutoff (${vaultCutoffTs}).`, + 'known_at' + ); + } + if (knownAt > asOfMs) { + throw new MarketDataStoreValidationError( + `Macro row ${i} known_at (${knownAt}) exceeds fenced asOf (${asOfMs}).`, + 'known_at' + ); + } + } + return table; +} + function mapUniverseRows(rows: readonly TableRow[]): number[] { if (!Array.isArray(rows)) { throw new MarketDataStoreValidationError( @@ -2280,8 +2601,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption return mapTableRows(FX_1D_COLUMNS, FX_1D_SCHEMA, rawRows); }, - crossSection(): Promise { - return Promise.reject(new MarketDataStoreNotImplementedError('crossSection')); + async crossSection(q: CrossSectionQuery): Promise
{ + const { planned, columns, schema } = planCrossSectionInternal(q, planCtx); + await ensureBudgetInitialized(); + const rawRows = await typedExecutor.query(planned.sql, planned.params); + return mapTableRows(columns, schema, rawRows); }, async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ @@ -2291,8 +2615,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption return mapTableRows(columns, schema, rawRows); }, - macroAsOf(): Promise
{ - return Promise.reject(new MarketDataStoreNotImplementedError('macroAsOf')); + async macroAsOf(q: MacroAsOfQuery): Promise
{ + const planned = planMacroAsOfQuery(q, planCtx); + await ensureBudgetInitialized(); + const rawRows = await typedExecutor.query(planned.sql, planned.params); + return mapMacroRows(rawRows, planCtx.vaultCutoffTs, planned.fenced.asOfMs); }, async universe(q: UniverseQuery): Promise { diff --git a/libs/research/src/market-data-store-questdb.ts b/libs/research/src/market-data-store-questdb.ts index c6da320c..dc0f94f0 100644 --- a/libs/research/src/market-data-store-questdb.ts +++ b/libs/research/src/market-data-store-questdb.ts @@ -29,6 +29,8 @@ import { type FencedTimeRange, type MarketDataStore, MarketDataStoreValidationError, + type Table, + type TableRow, type VaultFenceContext, applyVaultFence, } from './market-data-store'; @@ -42,9 +44,17 @@ const CANONICAL_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/; /** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */ export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000; +/** Output columns for QuestDB `fx_1m` queries. */ +export const FX_1M_COLUMNS = ['pair', 'ts', 'open', 'high', 'low', 'close', 'source'] as const; + +const FX_1M_ACCEPTED_PAIRS: ReadonlySet = new Set(['USDCAD', 'USD.CAD']); + /** Input query type derived from `MarketDataStore['bars']`. */ export type QuestDbBars1mQuery = Parameters[0]; +/** Input query type derived from `MarketDataStore['fx']`. */ +export type QuestDbFx1mQuery = Parameters[0]; + /** * Injected PGWire SQL executor port, structurally compatible with * `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`. @@ -63,6 +73,13 @@ export interface PlannedQuestDbBars1mQuery { readonly fence: FencedTimeRange; } +/** Pure output of {@link planFx1mQuery}. */ +export interface PlannedQuestDbFx1mQuery { + readonly sql: string; + readonly params: readonly string[]; + readonly fence: FencedTimeRange; +} + /** Configuration for {@link createQuestDbIntradayBarsReader}. */ export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext { readonly executor: QuestDbQueryExecutor; @@ -70,6 +87,11 @@ export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext { readonly batchSize?: number; } +/** Configuration for {@link createQuestDbIntradayFxReader}. */ +export interface QuestDbIntradayFxReaderOptions extends VaultFenceContext { + readonly executor: QuestDbQueryExecutor; +} + interface InternalPlannedBars1mQuery { readonly planned: PlannedQuestDbBars1mQuery; readonly requestedListingIds: ReadonlySet; @@ -215,6 +237,67 @@ export function planBars1mQuery( return planBars1mQueryInternal(q, ctx).planned; } +/** + * Pure, Vault-fenced, parameterized SQL planner for QuestDB `fx_1m`. + * + * Always fences under `scope: 'vault_fenced'` with `vaultOperatorAuthorized: false` + * and binds both `'USDCAD'` and `'USD.CAD'` pair symbols via `$3, $4`. + */ +export function planFx1mQuery( + q: QuestDbFx1mQuery, + ctx: VaultFenceContext +): PlannedQuestDbFx1mQuery { + if (!isPlainRecord(ctx)) { + throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx'); + } + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected an fx query object.', 'query'); + } + + const timeframe: unknown = q.timeframe; + if (timeframe !== '1m') { + throw new MarketDataStoreValidationError( + `Invalid fx timeframe "${String(timeframe)}". Expected '1m'.`, + 'timeframe' + ); + } + + const pair: unknown = q.pair; + if (pair !== 'USD.CAD') { + throw new MarketDataStoreValidationError( + `Unsupported FX pair "${String(pair)}". Expected 'USD.CAD'.`, + 'pair' + ); + } + + const fence = applyVaultFence( + { + from: q.from, + to: q.to, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + vaultOperatorAuthorized: false, + } + ); + + const sql = + 'SELECT pair, CAST(ts AS LONG) AS ts_us, open, high, low, close, source ' + + 'FROM fx_1m ' + + 'WHERE ts >= $1 AND ts <= $2 AND pair IN ($3, $4) ' + + 'ORDER BY ts ASC'; + + const params: string[] = [ + formatUtcIsoMs(fence.fromMs), + formatUtcIsoMs(fence.toMs), + 'USDCAD', + 'USD.CAD', + ]; + + return { sql, params, fence }; +} + function parseListingIdSymbol( row: Record, rowIndex: number, @@ -460,3 +543,140 @@ export function createQuestDbIntradayBarsReader( }, }; } + +function mapFx1mRows( + rows: readonly Record[], + fence: FencedTimeRange, + vaultCutoffTs: number +): Table { + const fromUs = BigInt(fence.fromMs) * 1000n; + const toUs = BigInt(fence.toMs) * 1000n; + const vaultCutoffUs = BigInt(vaultCutoffTs) * 1000n; + + const out: TableRow[] = new Array(rows.length); + for (let i = 0; i < rows.length; i += 1) { + const raw = rows[i]; + if (!isPlainRecord(raw)) { + throw new MarketDataStoreValidationError( + `Executor returned a non-object fx_1m row at index ${i}.`, + 'rows' + ); + } + + const pair = raw.pair; + if (typeof pair !== 'string' || !FX_1M_ACCEPTED_PAIRS.has(pair)) { + throw new MarketDataStoreValidationError( + `Invalid fx_1m pair in result row ${i}: ${String(pair)}.`, + 'pair' + ); + } + + const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i); + if (tsUs < fromUs || tsUs > toUs || tsUs >= vaultCutoffUs) { + throw new MarketDataStoreValidationError( + `Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us (cutoff ${vaultCutoffUs.toString()} us).`, + 'ts' + ); + } + + const source = raw.source; + if (typeof source !== 'string' || source.length === 0) { + throw new MarketDataStoreValidationError( + `Invalid fx_1m source in result row ${i}: ${String(source)}.`, + 'source' + ); + } + + out[i] = { + pair, + ts: microsToEpochMs(tsUs, 'ts', i, 'floor'), + open: readRequiredFiniteNumber(raw, 'open', i), + high: readRequiredFiniteNumber(raw, 'high', i), + low: readRequiredFiniteNumber(raw, 'low', i), + close: readRequiredFiniteNumber(raw, 'close', i), + source, + }; + } + + return { + columns: [...FX_1M_COLUMNS], + rows: out, + }; +} + +/** + * Creates a read-only Vault-fenced intraday `fx` reader backed by an injected + * {@link QuestDbQueryExecutor} over QuestDB `fx_1m`. + */ +export function createQuestDbIntradayFxReader( + options: QuestDbIntradayFxReaderOptions +): Pick { + if (!isPlainRecord(options)) { + throw new MarketDataStoreValidationError( + 'Expected a QuestDbIntradayFxReaderOptions object.', + 'options' + ); + } + + const executor: unknown = options.executor; + if (!isPlainRecord(executor) || typeof executor.query !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `executor` with a `query(sql, params)` method.', + 'executor' + ); + } + const typedExecutor = executor as unknown as QuestDbQueryExecutor; + const vaultCutoffTs = validateVaultCutoffTs(options.vaultCutoffTs); + + if ( + options.vaultOperatorAuthorized !== undefined && + typeof options.vaultOperatorAuthorized !== 'boolean' + ) { + throw new MarketDataStoreValidationError( + `Invalid vaultOperatorAuthorized "${String(options.vaultOperatorAuthorized)}". Expected a boolean.`, + 'vaultOperatorAuthorized' + ); + } + + const planCtx: VaultFenceContext = { + vaultCutoffTs, + vaultOperatorAuthorized: false, + }; + + return { + async fx(q: QuestDbFx1mQuery): Promise
{ + const planned = planFx1mQuery(q, planCtx); + const result: unknown = await typedExecutor.query(planned.sql, [...planned.params]); + if (!isPlainRecord(result) || !Array.isArray(result.rows)) { + throw new MarketDataStoreValidationError( + 'Executor returned a malformed result; expected `{ rows: Record[] }`.', + 'rows' + ); + } + return mapFx1mRows( + result.rows as readonly Record[], + planned.fence, + vaultCutoffTs + ); + }, + }; +} + +/** + * Creates a combined read-only intraday `bars` + `fx` reader backed by an + * injected {@link QuestDbQueryExecutor} over QuestDB `bars_1m` and `fx_1m`. + */ +export function createQuestDbIntradayReader( + options: QuestDbIntradayBarsReaderOptions +): Pick { + const barsReader = createQuestDbIntradayBarsReader(options); + const fxReader = createQuestDbIntradayFxReader(options); + return { + bars(q) { + return barsReader.bars(q); + }, + fx(q) { + return fxReader.fx(q); + }, + }; +} diff --git a/libs/research/src/market-data-store-routed.ts b/libs/research/src/market-data-store-routed.ts index a7b52608..4f7492a7 100644 --- a/libs/research/src/market-data-store-routed.ts +++ b/libs/research/src/market-data-store-routed.ts @@ -28,8 +28,8 @@ import { type MarketDataStore, MarketDataStoreValidationError } from './market-d export interface RoutedMarketDataStoreOptions { /** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */ readonly daily: MarketDataStore; - /** Backing intraday reader for `bars` queries with `timeframe: '1m'`. */ - readonly intraday: Pick; + /** Backing intraday reader for `bars` (and optional `fx`) queries with `timeframe: '1m'`. */ + readonly intraday: Pick & Partial>; } const REQUIRED_DAILY_METHODS = [ @@ -55,7 +55,7 @@ function isDelegateObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } -function isIntraday1mBarsQuery(q: unknown): boolean { +function isIntraday1mQuery(q: unknown): boolean { return ( typeof q === 'object' && q !== null && @@ -150,12 +150,19 @@ export function createRoutedMarketDataStore( ); } + if (rawIntraday.fx !== undefined && typeof rawIntraday.fx !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `intraday.fx` to be a function when provided.', + 'intraday.fx' + ); + } + const daily = options.daily; const intraday = options.intraday; return { bars(q) { - if (isIntraday1mBarsQuery(q)) { + if (isIntraday1mQuery(q)) { return intraday.bars(q); } return daily.bars(q); @@ -182,6 +189,9 @@ export function createRoutedMarketDataStore( }, fx(q) { + if (intraday.fx !== undefined && isIntraday1mQuery(q)) { + return intraday.fx(q); + } return daily.fx(q); }, diff --git a/libs/research/src/mcp/host/stdio-host.ts b/libs/research/src/mcp/host/stdio-host.ts index b7ff3c3a..7d4f8bf8 100644 --- a/libs/research/src/mcp/host/stdio-host.ts +++ b/libs/research/src/mcp/host/stdio-host.ts @@ -54,6 +54,17 @@ 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 ENV_QUESTDB_URL = 'RESEARCH_MCP_QUESTDB_URL'; +const ENV_QUESTDB_HOST = 'RESEARCH_MCP_QUESTDB_HOST'; +const ENV_QUESTDB_PG_PORT = 'RESEARCH_MCP_QUESTDB_PG_PORT'; +const ENV_QUESTDB_DATABASE = 'RESEARCH_MCP_QUESTDB_DATABASE'; +const ENV_QUESTDB_USER = 'RESEARCH_MCP_QUESTDB_USER'; +const ENV_QUESTDB_PASSWORD = 'RESEARCH_MCP_QUESTDB_PASSWORD'; +const ENV_QUESTDB_SSL = 'RESEARCH_MCP_QUESTDB_SSL'; + +const DEFAULT_QUESTDB_PG_PORT = 8812; +const DEFAULT_QUESTDB_DATABASE = 'qdb'; +const STRICT_UINT_PORT_RE = /^\d+$/; const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; const AGENT_PRINCIPAL_RE = @@ -75,9 +86,27 @@ const rawHostEnvSchema = z [ENV_LIBRARY_ROOT]: nonBlankEnvString, [ENV_SESSION_REFERENCE_LISTINGS]: nonBlankEnvString, [ENV_EARLY_CLOSES]: nonBlankEnvString.optional(), + [ENV_QUESTDB_URL]: nonBlankEnvString.optional(), + [ENV_QUESTDB_HOST]: nonBlankEnvString.optional(), + [ENV_QUESTDB_PG_PORT]: nonBlankEnvString.optional(), + [ENV_QUESTDB_DATABASE]: nonBlankEnvString.optional(), + [ENV_QUESTDB_USER]: nonBlankEnvString.optional(), + [ENV_QUESTDB_PASSWORD]: nonBlankEnvString.optional(), + [ENV_QUESTDB_SSL]: nonBlankEnvString.optional(), }) .strict(); +/** Optional QuestDB intraday connection settings parsed from `RESEARCH_MCP_QUESTDB_*`. */ +export interface ResearchCopilotQuestDbConfig { + readonly url?: string; + readonly host?: string; + readonly port?: number; + readonly database?: string; + readonly user?: string; + readonly password?: string; + readonly ssl?: boolean; +} + /** Validated configuration parsed from `RESEARCH_MCP_*` environment variables. */ export interface ResearchCopilotHostConfig { readonly postgresUrl: string; @@ -88,6 +117,7 @@ export interface ResearchCopilotHostConfig { readonly libraryRoot: string; readonly referenceListingIds: BarSessionDatesPortOptions['referenceListingIds']; readonly earlyCloses?: EarlyCloseOverrides; + readonly questdb?: ResearchCopilotQuestDbConfig; } /** @@ -175,11 +205,11 @@ function defineDataProperty(target: Record, key: string, value: T) }); } -function parsePostgresUrl(raw: string): string { +function parsePgWireUrl(raw: string, variable: 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.` + variable, + `Invalid configuration variable "${variable}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.` ); } let parsed: URL; @@ -187,8 +217,8 @@ function parsePostgresUrl(raw: string): string { parsed = new URL(raw); } catch { throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_URL, - `Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL.` + variable, + `Invalid configuration variable "${variable}": expected a valid postgres:// or postgresql:// URL.` ); } if ( @@ -196,8 +226,8 @@ function parsePostgresUrl(raw: string): string { 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.` + variable, + `Invalid configuration variable "${variable}": expected a postgres:// or postgresql:// URL with a non-empty host.` ); } try { @@ -209,13 +239,124 @@ function parsePostgresUrl(raw: string): string { } } catch { throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_URL, - `Invalid configuration variable "${ENV_POSTGRES_URL}": URL credentials contain invalid percent-encoding.` + variable, + `Invalid configuration variable "${variable}": URL credentials contain invalid percent-encoding.` ); } return raw; } +function parsePostgresUrl(raw: string): string { + return parsePgWireUrl(raw, ENV_POSTGRES_URL); +} + +function parseQuestDbSsl(raw: string): boolean { + const normalized = raw.trim().toLowerCase(); + if (normalized === 'true' || normalized === '1') { + return true; + } + if (normalized === 'false' || normalized === '0') { + return false; + } + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_SSL, + `Invalid configuration variable "${ENV_QUESTDB_SSL}": expected "true", "false", "1", or "0".` + ); +} + +function parseQuestDbPort(raw: string): number { + const trimmed = raw.trim(); + if (!STRICT_UINT_PORT_RE.test(trimmed)) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_PG_PORT, + `Invalid configuration variable "${ENV_QUESTDB_PG_PORT}": expected an integer port from 1 through 65535.` + ); + } + const port = Number(trimmed); + if (!Number.isSafeInteger(port) || port < 1 || port > 65535) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_PG_PORT, + `Invalid configuration variable "${ENV_QUESTDB_PG_PORT}": expected an integer port from 1 through 65535.` + ); + } + return port; +} + +function parseQuestDbConfig(data: { + readonly [ENV_QUESTDB_URL]?: string; + readonly [ENV_QUESTDB_HOST]?: string; + readonly [ENV_QUESTDB_PG_PORT]?: string; + readonly [ENV_QUESTDB_DATABASE]?: string; + readonly [ENV_QUESTDB_USER]?: string; + readonly [ENV_QUESTDB_PASSWORD]?: string; + readonly [ENV_QUESTDB_SSL]?: string; +}): ResearchCopilotQuestDbConfig | undefined { + const rawUrl = data[ENV_QUESTDB_URL]; + const rawHost = data[ENV_QUESTDB_HOST]; + const rawPort = data[ENV_QUESTDB_PG_PORT]; + const rawDatabase = data[ENV_QUESTDB_DATABASE]; + const rawUser = data[ENV_QUESTDB_USER]; + const rawPassword = data[ENV_QUESTDB_PASSWORD]; + const rawSsl = data[ENV_QUESTDB_SSL]; + + const hasAnyDiscrete = + rawHost !== undefined || + rawPort !== undefined || + rawDatabase !== undefined || + rawUser !== undefined || + rawPassword !== undefined; + + if (rawUrl === undefined && !hasAnyDiscrete && rawSsl === undefined) { + return undefined; + } + + const ssl = rawSsl !== undefined ? parseQuestDbSsl(rawSsl) : undefined; + + if (rawUrl !== undefined) { + if (hasAnyDiscrete) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_URL, + `Conflicting configuration variable "${ENV_QUESTDB_URL}": cannot be combined with discrete RESEARCH_MCP_QUESTDB_HOST/PG_PORT/DATABASE/USER/PASSWORD variables.` + ); + } + const url = parsePgWireUrl(rawUrl, ENV_QUESTDB_URL); + return { + url, + ...(ssl !== undefined ? { ssl } : {}), + }; + } + + if (rawHost === undefined) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_HOST, + `Missing required configuration variable "${ENV_QUESTDB_HOST}" when other RESEARCH_MCP_QUESTDB_* variables are set.` + ); + } + + const host = rawHost.trim(); + if (host !== rawHost || /\s/.test(host)) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_HOST, + `Invalid configuration variable "${ENV_QUESTDB_HOST}": expected a hostname without whitespace.` + ); + } + + const port = rawPort !== undefined ? parseQuestDbPort(rawPort) : DEFAULT_QUESTDB_PG_PORT; + const database = + rawDatabase !== undefined ? rawDatabase.trim() : DEFAULT_QUESTDB_DATABASE; + const user = rawUser !== undefined ? rawUser.trim() : undefined; + const password = rawPassword; + + return { + host, + port, + database, + ...(user !== undefined ? { user } : {}), + ...(password !== undefined ? { password } : {}), + ...(ssl !== undefined ? { ssl } : {}), + }; +} + function parsePostgresSchema(raw: string): string { if (!SCHEMA_IDENT_RE.test(raw)) { throw new ResearchCopilotHostConfigError( @@ -526,6 +667,7 @@ export function parseResearchCopilotHostConfig( data[ENV_EARLY_CLOSES] !== undefined ? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES]) : undefined; + const questdb = parseQuestDbConfig(data); return { postgresUrl, @@ -536,6 +678,7 @@ export function parseResearchCopilotHostConfig( libraryRoot, referenceListingIds, ...(earlyCloses !== undefined ? { earlyCloses } : {}), + ...(questdb !== undefined ? { questdb } : {}), }; } @@ -554,13 +697,12 @@ function addRawAndDecodedNeedle(needles: Set, raw: string): void { } } -function collectSecretNeedles(postgresUrl: string): readonly string[] { - const needles = new Set(); - if (postgresUrl.length > 0) { - needles.add(postgresUrl); +function collectUrlSecretNeedles(needles: Set, rawUrl: string): void { + if (rawUrl.length > 0) { + needles.add(rawUrl); } try { - const parsed = new URL(postgresUrl); + const parsed = new URL(rawUrl); if (parsed.href.length > 0) { needles.add(parsed.href); } @@ -591,7 +733,23 @@ function collectSecretNeedles(postgresUrl: string): readonly string[] { } } } catch { - // Non-URL postgresUrl passed directly to runResearchCopilotStdioHost: raw string is covered. + // Non-URL string passed directly: raw string is already covered. + } +} + +function collectSecretNeedles( + postgresUrl: string, + questdb?: ResearchCopilotQuestDbConfig +): readonly string[] { + const needles = new Set(); + collectUrlSecretNeedles(needles, postgresUrl); + if (questdb !== undefined) { + if (typeof questdb.url === 'string' && questdb.url.length > 0) { + collectUrlSecretNeedles(needles, questdb.url); + } + if (typeof questdb.password === 'string' && questdb.password.length > 0) { + addRawAndDecodedNeedle(needles, questdb.password); + } } return Array.from(needles); } @@ -708,7 +866,8 @@ export async function runResearchCopilotStdioHost( const { config } = deps; const secretNeedles = collectSecretNeedles( - typeof config.postgresUrl === 'string' ? config.postgresUrl : '' + typeof config.postgresUrl === 'string' ? config.postgresUrl : '', + config.questdb ); const closers: Array<() => Promise | void> = []; diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index 0103f10a..98022160 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -6,12 +6,14 @@ import { analyzeSignalPanel, } from '@stock-bot/calculations'; import { z } from 'zod'; +import { parseFeatureRef } from '../../feature-library'; import { type BarRecord, type MarketDataStore, MarketDataStoreValidationError, type Table, type TableRow, + type UniverseRef, type VaultFenceContext, } from '../../market-data-store'; import { @@ -77,6 +79,9 @@ export const ANALYZE_SIGNAL_MAX_SERIES_POINTS = 100; /** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */ export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120; +/** Hard maximum number of per-session feature cross-section queries in a single study. */ +export const ANALYZE_SIGNAL_MAX_FEATURE_SESSION_QUERIES = 5_500; + const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; 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}$/; @@ -90,6 +95,15 @@ function canonicalDailyHorizonBucket(horizonSessions: number): HorizonBucket { const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE); +function isValidFeatureRef(raw: string): boolean { + try { + parseFeatureRef(raw); + return true; + } catch { + return false; + } +} + const shortsSignalSpecSchema = z .object({ source: z.literal('shorts').describe('Signal data source ("shorts").'), @@ -118,9 +132,30 @@ const fundamentalsSignalSpecSchema = z .strict() .describe('Point-in-time fundamentals signal specification.'); +const featureSignalSpecSchema = z + .object({ + source: z.literal('feature').describe('Signal data source ("feature").'), + featureRef: z + .string() + .min(1) + .refine( + isValidFeatureRef, + 'Expected canonical versioned feature reference "@v" (e.g. "ret_1d@v1").' + ) + .describe('Canonical versioned feature reference ("@v"), e.g. "ret_1d@v1".'), + }) + .strict() + .describe('Versioned curated feature signal specification.'); + const signalSpecSchema = z - .discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema]) - .describe('Discriminated signal source and field specification ("shorts" or "fundamentals").'); + .discriminatedUnion('source', [ + shortsSignalSpecSchema, + fundamentalsSignalSpecSchema, + featureSignalSpecSchema, + ]) + .describe( + 'Discriminated signal source specification ("shorts", "fundamentals", or "feature").' + ); const analyzeSignalSharedFieldsSchema = z .object({ @@ -227,7 +262,9 @@ export const analyzeSignalInputSchema = analyzeSignalSharedFieldsSchema message: data.signal.source === 'shorts' ? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).' - : 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', + : data.signal.source === 'fundamentals' + ? 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).' + : 'Feature signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', }); } }); @@ -238,29 +275,35 @@ function buildAnalyzeSignalJsonSchema(): JsonSchemaObject { const sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema); const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema); const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema); + const featureBranch = zodObjectToJsonSchema(featureSignalSpecSchema); const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? { type: 'boolean' as const, default: false, }; + const featureRefProp = featureBranch.properties.featureRef ?? { + type: 'string' as const, + minLength: 1, + }; const signalProperty: JsonSchemaProperty = { type: 'object', description: signalSpecSchema.description, properties: { source: { type: 'string', - enum: ['shorts', 'fundamentals'], - description: 'Signal data source ("shorts" or "fundamentals").', + enum: ['shorts', 'fundamentals', 'feature'], + description: 'Signal data source ("shorts", "fundamentals", or "feature").', }, field: { type: 'string', enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS], - description: 'Signal field name valid for the chosen source.', + description: 'Signal field name valid for "shorts" or "fundamentals".', }, allowEstimatedLag: allowEstimatedLagProp, + featureRef: featureRefProp, }, - required: ['source', 'field'], + required: ['source'], additionalProperties: false, - anyOf: [shortsBranch, fundamentalsBranch], + anyOf: [shortsBranch, fundamentalsBranch, featureBranch], }; return { @@ -732,6 +775,94 @@ function appendEligibleFundamentalsObservations(params: { return latestKnownAtByListing; } +function deriveFeatureSessionQueries( + bars: readonly BarRecord[], + fencedAsOfMs: number, + vaultCutoffTs: number, + vaultCutoffDate: string +): Array<{ readonly sessionDate: string; readonly asOfMs: number }> { + const unique = new Map(); + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i]; + if ( + typeof bar !== 'object' || + bar === null || + typeof bar.ts !== 'number' || + !Number.isFinite(bar.ts) + ) { + continue; + } + const sessionDate = utcDateOf(bar.ts); + if (sessionDate >= vaultCutoffDate) { + continue; + } + const asOfMs = Math.min(bar.ts, fencedAsOfMs); + if (asOfMs >= vaultCutoffTs) { + continue; + } + const key = `${sessionDate}:${asOfMs}`; + if (!unique.has(key)) { + unique.set(key, { sessionDate, asOfMs }); + } + } + return [...unique.values()].sort((a, b) => + a.sessionDate !== b.sessionDate ? (a.sessionDate < b.sessionDate ? -1 : 1) : a.asOfMs - b.asOfMs + ); +} + +function appendEligibleFeatureObservations(params: { + readonly table: Table; + readonly featureRef: string; + readonly listingIdSet: ReadonlySet; + readonly sessionQueryAsOfMs: number; + readonly seenKeys: Set; + readonly out: SignalObservation[]; +}): void { + const { table, featureRef, listingIdSet, sessionQueryAsOfMs, seenKeys, out } = params; + if ( + typeof table !== 'object' || + table === null || + !Array.isArray(table.columns) || + !Array.isArray(table.rows) + ) { + throw new SignalPanelError( + 'invalid_input', + 'Expected a crossSection Table object with array columns and rows.' + ); + } + + const normalizedKnownAt = sessionQueryAsOfMs === 0 ? 0 : sessionQueryAsOfMs; + for (let i = 0; i < table.rows.length; i += 1) { + const row = table.rows[i]; + if (typeof row !== 'object' || row === null) { + continue; + } + const listingId = row.listing_id; + if ( + typeof listingId !== 'number' || + !Number.isSafeInteger(listingId) || + !listingIdSet.has(listingId) + ) { + continue; + } + const rawValue = row[featureRef]; + if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { + continue; + } + const normalizedListingId = listingId === 0 ? 0 : listingId; + const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; + if (seenKeys.has(dedupeKey)) { + continue; + } + seenKeys.add(dedupeKey); + out.push({ + listingId: normalizedListingId, + knownAt: normalizedKnownAt, + value: rawValue === 0 ? 0 : rawValue, + }); + } +} + function buildCanonicalStudyExpression(params: { readonly input: AnalyzeSignalInput; readonly listingIds: readonly number[]; @@ -742,15 +873,23 @@ function buildCanonicalStudyExpression(params: { }): SignalStudyExpression { const { input, listingIds, universeSnapshotDate, effectiveFrom, effectiveTo, effectiveAsOf } = params; + const signalExprSuffix = + input.signal.source === 'feature' + ? `feature:${input.signal.featureRef}` + : `${input.signal.source}:${input.signal.field}`; return { - expression: `mcp:analyze_signal:v1:${input.signal.source}:${input.signal.field}`, + expression: `mcp:analyze_signal:v1:${signalExprSuffix}`, params: { version: 1, signalSource: input.signal.source, - signalField: input.signal.field, - ...(input.signal.source === 'fundamentals' - ? { allowEstimatedLag: input.signal.allowEstimatedLag } - : {}), + ...(input.signal.source === 'feature' + ? { featureRef: input.signal.featureRef } + : { + signalField: input.signal.field, + ...(input.signal.source === 'fundamentals' + ? { allowEstimatedLag: input.signal.allowEstimatedLag } + : {}), + }), horizonSessions: input.horizonSessions, maxSignalAgeSessions: input.maxSignalAgeSessions ?? null, adjustment: input.adjustment, @@ -824,12 +963,13 @@ function validateFactoryOptions(options: AnalyzeSignalToolOptions): number { typeof options.store !== 'object' || options.store === null || typeof options.store.bars !== 'function' || + typeof options.store.crossSection !== 'function' || typeof options.store.shortsAsOf !== 'function' || typeof options.store.fundamentalsAsOf !== 'function' || typeof options.store.universe !== 'function' ) { throw new MarketDataStoreValidationError( - 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.', + 'Invalid `store`: expected a MarketDataStore implementing `bars`, `crossSection`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.', 'store' ); } @@ -875,7 +1015,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT return defineMcpTool({ name: 'analyze_signal', description: - 'Run a Vault-fenced cross-sectional short-interest or point-in-time fundamentals signal study and record eligible trials to trial_ledger.', + 'Run a Vault-fenced cross-sectional short-interest, point-in-time fundamentals, or versioned feature signal study and record eligible trials to trial_ledger.', inputSchema: analyzeSignalInputSchema, jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA, async handler(input: AnalyzeSignalInput): Promise { @@ -913,11 +1053,16 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT source: 'shorts', field: input.signal.field, } - : { - source: 'fundamentals', - field: input.signal.field, - allowEstimatedLag: input.signal.allowEstimatedLag, - }; + : input.signal.source === 'fundamentals' + ? { + source: 'fundamentals', + field: input.signal.field, + allowEstimatedLag: input.signal.allowEstimatedLag, + } + : { + source: 'feature', + featureRef: input.signal.featureRef, + }; const basePayloadFields = { scope: 'vault_fenced' as const, @@ -996,6 +1141,50 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT fenced.vaultCutoffDate ); signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); + } else if (input.signal.source === 'feature') { + const { featureRef } = input.signal; + const sessionQueries = deriveFeatureSessionQueries( + eligibleBars, + fenced.asOfMs, + vaultCutoffTs, + fenced.vaultCutoffDate + ); + if (sessionQueries.length > ANALYZE_SIGNAL_MAX_FEATURE_SESSION_QUERIES) { + return { + content: [ + { + type: 'text', + text: `Invalid arguments for tool "analyze_signal": Feature study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FEATURE_SESSION_QUERIES} session queries.`, + }, + ], + isError: true, + }; + } + + const featureUniverse: UniverseRef = + input.universe ?? (input.universeMarket as UniverseRef); + signals = []; + const seenKeys = new Set(); + for (const sessionQuery of sessionQueries) { + const sessionQueryAsOfIso = + sessionQuery.asOfMs === fenced.asOfMs + ? fenced.canonicalAsOf + : formatUtcIsoWithMicros(sessionQuery.asOfMs, 0); + const rawCrossSection = await store.crossSection({ + features: [featureRef], + date: sessionQuery.sessionDate, + universe: featureUniverse, + asOf: sessionQueryAsOfIso, + }); + appendEligibleFeatureObservations({ + table: rawCrossSection, + featureRef, + listingIdSet, + sessionQueryAsOfMs: sessionQuery.asOfMs, + seenKeys, + out: signals, + }); + } } else { const { field: fundamentalsField, allowEstimatedLag } = input.signal; const snapshotDates = deriveMonthlySnapshotDates(eligibleBars); diff --git a/libs/research/src/mcp/tools/vault-fenced-input.ts b/libs/research/src/mcp/tools/vault-fenced-input.ts index 3eaa97c7..fe2620d2 100644 --- a/libs/research/src/mcp/tools/vault-fenced-input.ts +++ b/libs/research/src/mcp/tools/vault-fenced-input.ts @@ -249,6 +249,10 @@ const SAFE_VALIDATION_FIELDS: ReadonlySet = new Set([ 'adjustment', 'scope', 'limit', + 'countries', + 'indicators', + 'features', + 'universe', ]); const SAFE_STORE_METHODS: ReadonlySet = new Set([ diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index 9315471d..6bebfcc6 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -446,8 +446,8 @@ describe('validateFeatureDefinition', () => { () => validateFeatureDefinition( makeSimpleDef({ - inputs: ['macro' as FeatureDefinition['inputs'][number]], - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:macro}}', + inputs: ['bars_1m' as FeatureDefinition['inputs'][number]], + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1m}}', }) ), 'UNSUPPORTED_INPUT_DATASET' @@ -800,6 +800,54 @@ describe('planFeatureBatch', () => { } }); + it('expands {{input:macro}} with lagged regime-only provenance and {{input:corporate_actions}} with Vault-fenced known_at', () => { + const macroAndCaDef: FeatureDefinition = { + name: 'macro_ca_regime', + version: 1, + family: 'regime', + kind: 'duckdb_sql', + inputs: ['bars_1d', 'corporate_actions', 'macro'], + warmupBars: 0, + knownAtRule: 'max_input_known_at', + sql: ` + SELECT + b.listing_id, + b.ts, + GREATEST(b.known_at, ca.known_at, m.known_at) AS known_at, + m.value AS value + FROM {{input:bars_1d}} AS b + LEFT JOIN {{input:corporate_actions}} AS ca ON b.listing_id = ca.listing_id + LEFT JOIN {{input:macro}} AS m ON m.country_iso = 'US' AND m.indicator = 'cpi_yoy' + `, + }; + + const [write] = planFeatureBatch(macroAndCaDef, { + curatedRoot: '/data', + fromYear: 2022, + toYear: 2022, + vaultCutoffDate: '2023-06-01', + }); + expect(write).toBeDefined(); + expect(write?.outputPath).toBe('/data/features/macro_ca_regime/v1/year=2022/part.parquet'); + expect(write?.sql).toContain( + "read_parquet('/data/corporate_actions/part.parquet') WHERE known_at <= ?" + ); + expect(write?.sql).toContain( + "read_parquet('/data/macro/part.parquet') WHERE known_at <= ? AND known_at_source = 'publication_lag_estimate'" + ); + const ts2022 = '2022-12-31T23:59:59.999999Z'; + const vaultCeiling = '2023-05-31T23:59:59.999999Z'; + expect(write?.params).toEqual([ + ts2022, + vaultCeiling, // bars_1d + vaultCeiling, // corporate_actions + vaultCeiling, // macro + 2022, + ts2022, + vaultCeiling, // outer filter + ]); + }); + it('enforces Vault fence for midyear cutoff, January 1 cutoff, entirely post-cutoff ranges, and invalid options', () => { // Midyear cutoff: 2022-06-15 -> plans 2020, 2021, 2022; clamps 2022 ts and all known_at to 2022-06-14T23:59:59.999999Z. const midyear = planFeatureBatch(RET_1D_V1, { diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index 9897210a..d85cdd3e 100644 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -16,6 +16,7 @@ import { FUNDAMENTALS_PIT_VALUE_FIELDS, FX_1D_COLUMNS, FX_PAIR_MAP, + MACRO_COLUMNS, MarketDataStoreNotImplementedError, MarketDataStoreValidationError, type PinnedAdjFactorsArtifact, @@ -28,9 +29,11 @@ import { parseAdjFactorsSnapshotMetadata, planAdjFactorsMetadataQuery, planBars1dQuery, + planCrossSectionQuery, planEventsQuery, planFundamentalsAsOfQuery, planFx1dQuery, + planMacroAsOfQuery, planShortsAsOfQuery, planUniverseQuery, resolveDuckDbConnectionBudget, @@ -2418,25 +2421,6 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { to: '2025-02-01', }), }, - { - method: 'crossSection', - run: () => - store.crossSection({ - features: ['ret_20d'], - date: '2025-01-15', - universe: 'US_EQ', - }), - }, - { - method: 'macroAsOf', - run: () => - store.macroAsOf({ - countries: ['US'], - indicators: ['CPI'], - from: '2025-01-01', - to: '2025-02-01', - }), - }, ]; for (const c of cases) { @@ -3277,3 +3261,205 @@ describe('fundamentalsAsOf hostile request inputs', () => { expect(afterCutoff.fenced.clampedAsOf).toBe(true); }); }); + +describe('planMacroAsOfQuery and store.macroAsOf', () => { + it('plans parameterized Vault-fenced SQL, deduplicates countries/indicators, and rejects post-cutoff from', () => { + const planned = planMacroAsOfQuery( + { + countries: ['US', 'CA', 'US'], + indicators: ['cpi_yoy', 'policy_rate', 'cpi_yoy'], + from: '2025-01-01', + to: '2026-08-01', + asOf: '2026-08-01', + }, + DEFAULT_CTX + ); + + expect(planned.sql).toContain(`read_parquet('${CURATED_ROOT}/macro/part.parquet') AS m`); + expect(planned.sql).toContain( + 'WHERE m.country_iso IN (?, ?) AND m.indicator IN (?, ?) AND m.period_date >= ? AND m.period_date <= ? AND m.known_at <= ?' + ); + expect(planned.sql).toContain( + 'ORDER BY m.country_iso ASC, m.indicator ASC, m.period_date ASC' + ); + expect(planned.sql).not.toContain('cpi_yoy'); + expect(planned.sql).not.toContain('policy_rate'); + expect(planned.params).toEqual([ + 'US', + 'CA', + 'cpi_yoy', + 'policy_rate', + '2025-01-01', + '2026-05-27', + MAX_ALLOWED_ISO_MICROS, + ]); + expect(planned.fenced.clampedTo).toBe(true); + expect(planned.fenced.clampedAsOf).toBe(true); + + expect(() => + planMacroAsOfQuery( + { + countries: ['US'], + indicators: ['cpi_yoy'], + from: '2026-05-28', + to: '2026-06-01', + }, + DEFAULT_CTX + ) + ).toThrow(VaultHoldoutFenceError); + }); + + it('fails closed on invalid inputs and corrupt macro provenance/unlagged/post-cutoff rows', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + + await expect( + store.macroAsOf({ countries: [], indicators: ['cpi_yoy'], from: '2025-01-01', to: '2025-06-01' }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + await expect( + store.macroAsOf({ countries: ['US'], indicators: [' '], from: '2025-01-01', to: '2025-06-01' }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + await expect( + store.macroAsOf({ countries: ['US'], indicators: ['cpi_yoy'], from: '2026-05-28', to: '2026-06-01' }) + ).rejects.toBeInstanceOf(VaultHoldoutFenceError); + expect(fake.calls).toHaveLength(0); + + const periodMs = Date.UTC(2025, 0, 1); + const badSourceStore = createDuckDbMarketDataStore({ + executor: createRecordingExecutor({ + onQuery: () => [ + { + country_iso: 'US', + indicator: 'cpi_yoy', + period_date: '2025-01-01', + known_at: periodMs + 35 * 86_400_000, + known_at_source: 'release_timestamp', + value: 2.9, + }, + ], + }).executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + await expect( + badSourceStore.macroAsOf({ + countries: ['US'], + indicators: ['cpi_yoy'], + from: '2025-01-01', + to: '2025-06-01', + }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + + const unlaggedStore = createDuckDbMarketDataStore({ + executor: createRecordingExecutor({ + onQuery: () => [ + { + country_iso: 'US', + indicator: 'policy_rate', + period_date: '2025-01-01', + known_at: periodMs + 86_400_000 - 1, + known_at_source: 'publication_lag_estimate', + value: 4.5, + }, + ], + }).executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + await expect( + unlaggedStore.macroAsOf({ + countries: ['US'], + indicators: ['policy_rate'], + from: '2025-01-01', + to: '2025-06-01', + }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + + const validStore = createDuckDbMarketDataStore({ + executor: createRecordingExecutor({ + onQuery: () => [ + { + country_iso: 'US', + indicator: 'policy_rate', + period_date: '2025-01-01', + known_at: periodMs + 86_400_000, + known_at_source: 'publication_lag_estimate', + value: 4.5, + }, + ], + }).executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + const result = await validStore.macroAsOf({ + countries: ['US'], + indicators: ['policy_rate'], + from: '2025-01-01', + to: '2025-06-01', + }); + expect(result.columns).toEqual([...MACRO_COLUMNS]); + expect(result.rows).toHaveLength(1); + expect(result.rows[0]?.value).toBe(4.5); + }); +}); + +describe('planCrossSectionQuery and store.crossSection', () => { + it('plans survivorship-free universe join with versioned features, defaults omitted asOf to date, and rejects invalid/post-cutoff inputs', () => { + const planned = planCrossSectionQuery( + { + features: ['ret_1d@v1', 'rsi_14@v2', 'ret_1d@v1'], + date: '2025-06-10', + universe: 'US_CA_EQ', + }, + DEFAULT_CTX + ); + + expect(planned.sql).toContain( + `read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b` + ); + expect(planned.sql).toContain( + `read_parquet('${CURATED_ROOT}/features/ret_1d/v1/year=*/part.parquet', hive_partitioning = true) AS f` + ); + expect(planned.sql).toContain( + `read_parquet('${CURATED_ROOT}/features/rsi_14/v2/year=*/part.parquet', hive_partitioning = true) AS f` + ); + expect(planned.sql).toContain('SELECT u.listing_id, f_0.value AS "ret_1d@v1", f_1.value AS "rsi_14@v2"'); + expect(planned.sql).toContain('ORDER BY u.listing_id ASC'); + expect(planned.params).toEqual([ + 'USD', + 'CAD', + '2025-06-03', + '2025-06-10', + '2025-06-10T23:59:59.999999Z', + '2025-06-10T23:59:59.999999Z', + 2025, + '2025-06-10T00:00:00.000Z', + '2025-06-10T23:59:59.999999Z', + '2025-06-10T23:59:59.999999Z', + 2025, + '2025-06-10T00:00:00.000Z', + '2025-06-10T23:59:59.999999Z', + '2025-06-10T23:59:59.999999Z', + ]); + + for (const badRef of ['ret_1d', 'ret_1d@v0', 'ret_1d@v01', '../evil@v1', 'RET_1D@v1', '']) { + expect(() => + planCrossSectionQuery( + { features: [badRef], date: '2025-06-10', universe: 'US_EQ' }, + DEFAULT_CTX + ) + ).toThrow(MarketDataStoreValidationError); + } + + expect(() => + planCrossSectionQuery( + { features: ['ret_1d@v1'], date: '2026-05-28', universe: 'US_EQ' }, + DEFAULT_CTX + ) + ).toThrow(VaultHoldoutFenceError); + }); +}); diff --git a/libs/research/test/market-data-store-questdb.test.ts b/libs/research/test/market-data-store-questdb.test.ts index b17e06a2..3e6aba05 100644 --- a/libs/research/test/market-data-store-questdb.test.ts +++ b/libs/research/test/market-data-store-questdb.test.ts @@ -3,14 +3,19 @@ import { type BarBatch, type BarRecord, DEFAULT_QUESTDB_BARS_BATCH_SIZE, + FX_1M_COLUMNS, MarketDataStoreNotImplementedError, MarketDataStoreValidationError, type QuestDbBars1mQuery, + type QuestDbFx1mQuery, type QuestDbQueryExecutor, VaultHoldoutFenceError, VaultScopeNotAuthorizedError, createQuestDbIntradayBarsReader, + createQuestDbIntradayFxReader, + createQuestDbIntradayReader, planBars1mQuery, + planFx1mQuery, } from '@stock-bot/research'; interface RecordedCall { @@ -766,3 +771,111 @@ describe('Malformed and out-of-fence row defence-in-depth', () => { expect(exactMsBar.knownAt <= exactKnownAt143200000).toBe(true); }); }); + +describe('QuestDB fx_1m planner and reader', () => { + it('plans parameterized $1..$4 SQL binding USDCAD and USD.CAD and enforces Vault fence', () => { + const planned = planFx1mQuery( + { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-06-30T23:55:00.000Z', + to: '2025-07-05T00:00:00.000Z', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS, vaultOperatorAuthorized: true } + ); + + expect(planned.sql).toBe( + 'SELECT pair, CAST(ts AS LONG) AS ts_us, open, high, low, close, source FROM fx_1m WHERE ts >= $1 AND ts <= $2 AND pair IN ($3, $4) ORDER BY ts ASC' + ); + expect(planned.params).toEqual([ + '2025-06-30T23:55:00.000Z', + '2025-06-30T23:59:59.999Z', + 'USDCAD', + 'USD.CAD', + ]); + expect(planned.fence.clampedTo).toBe(true); + + expect(() => + planFx1mQuery( + { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-07-01T00:00:00.000Z', + to: '2025-07-02T00:00:00.000Z', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ) + ).toThrow(VaultHoldoutFenceError); + }); + + it('reads both USDCAD and USD.CAD rows via createQuestDbIntradayFxReader / createQuestDbIntradayReader and rejects post-cutoff microsecond rows', async () => { + const executor = new RecordingQuestDbExecutor(); + const ts1Ms = Date.UTC(2025, 5, 30, 23, 55, 0, 0); + const ts2Ms = Date.UTC(2025, 5, 30, 23, 56, 0, 0); + executor.setRows([ + { + pair: 'USDCAD', + ts_us: (BigInt(ts1Ms) * 1000n).toString(), + open: 1.36, + high: 1.362, + low: 1.359, + close: 1.361, + source: 'polygon', + }, + { + pair: 'USD.CAD', + ts_us: BigInt(ts2Ms) * 1000n, + open: 1.361, + high: 1.363, + low: 1.36, + close: 1.362, + source: 'polygon', + }, + ]); + + const reader = createQuestDbIntradayReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const q: QuestDbFx1mQuery = { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-06-30T23:55:00.000Z', + to: '2025-07-02T00:00:00.000Z', + }; + const table = await reader.fx(q); + expect(table.columns).toEqual([...FX_1M_COLUMNS]); + expect(table.rows).toHaveLength(2); + expect(table.rows[0]?.pair).toBe('USDCAD'); + expect(table.rows[1]?.pair).toBe('USD.CAD'); + + // Post-cutoff from rejects with zero additional executor calls. + await expect( + reader.fx({ + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-07-01T00:00:00.000Z', + to: '2025-07-02T00:00:00.000Z', + }) + ).rejects.toBeInstanceOf(VaultHoldoutFenceError); + expect(executor.calls).toHaveLength(1); + + // Row at exact vaultCutoffTs microsecond fails closed. + const fxReader = createQuestDbIntradayFxReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + executor.setRows([ + { + pair: 'USDCAD', + ts_us: (BigInt(VAULT_CUTOFF_TS) * 1000n).toString(), + open: 1.37, + high: 1.37, + low: 1.37, + close: 1.37, + source: 'polygon', + }, + ]); + await expect(fxReader.fx(q)).rejects.toBeInstanceOf(MarketDataStoreValidationError); + }); +}); diff --git a/libs/research/test/market-data-store-routed.test.ts b/libs/research/test/market-data-store-routed.test.ts index 81b38fb6..f8734e17 100644 --- a/libs/research/test/market-data-store-routed.test.ts +++ b/libs/research/test/market-data-store-routed.test.ts @@ -13,6 +13,7 @@ import { type TableRow, createDuckDbMarketDataStore, createQuestDbIntradayBarsReader, + createQuestDbIntradayReader, createRoutedMarketDataStore, } from '@stock-bot/research'; import { createQuestDbIntradayBarsReader as subpathCreateQuestDbIntradayBarsReader } from '@stock-bot/research/market-data-store-questdb'; @@ -1094,5 +1095,97 @@ describe('createRoutedMarketDataStore', () => { expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); } }); + + it('routes fx(1m) to intraday.fx when provided while keeping fx(1d) on daily, and validates intraday.fx', async () => { + const intradayFxCalls: FxQuery[] = []; + const intradayFxTable: Table = { + columns: ['pair', 'ts', 'open', 'high', 'low', 'close', 'source'], + rows: [ + { + pair: 'USDCAD', + ts: Date.UTC(2025, 5, 30, 14, 30, 0), + open: 1.36, + high: 1.361, + low: 1.359, + close: 1.3605, + source: 'polygon', + }, + ], + }; + + const daily = new PrototypeDailyStore(); + const baseIntraday = new PrototypeIntradayReader(); + const intraday = { + bars: baseIntraday.bars.bind(baseIntraday), + async fx(q: FxQuery): Promise
{ + intradayFxCalls.push(q); + return intradayFxTable; + }, + }; + const store = createRoutedMarketDataStore({ daily, intraday }); + + const qFx1m: FxQuery = { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-06-30T14:30:00Z', + to: '2025-06-30T14:35:00Z', + }; + const qFx1d: FxQuery = { + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-06-01', + to: '2025-06-30', + }; + + const res1m = await store.fx(qFx1m); + expect(res1m).toBe(intradayFxTable); + expect(intradayFxCalls).toEqual([qFx1m]); + expect(daily.calls).toHaveLength(0); + + const res1d = await store.fx(qFx1d); + expect(res1d).toEqual({ columns: ['pair', 'close'], rows: [] }); + expect(daily.calls).toHaveLength(1); + expect(daily.calls[0]?.method).toBe('fx'); + expect(daily.calls[0]?.arg).toBe(qFx1d); + + // Invalid non-callable intraday.fx is rejected eagerly. + expect(() => + createRoutedMarketDataStore({ + daily, + intraday: { + bars: intraday.bars, + fx: 'not-a-fn' as unknown as MarketDataStore['fx'], + }, + }) + ).toThrow(MarketDataStoreValidationError); + + // Composed with real QuestDB intraday reader. + const questExec: QuestDbQueryExecutor = { + async query() { + return { + rows: [ + { + pair: 'USDCAD', + ts_us: (BigInt(Date.UTC(2025, 5, 30, 14, 30, 0)) * 1000n).toString(), + open: 1.36, + high: 1.361, + low: 1.359, + close: 1.3605, + source: 'polygon', + }, + ], + }; + }, + }; + const routedReal = createRoutedMarketDataStore({ + daily, + intraday: createQuestDbIntradayReader({ + executor: questExec, + vaultCutoffTs: VAULT_CUTOFF_TS, + }), + }); + const realFx1m = await routedReal.fx(qFx1m); + expect(realFx1m.rows).toHaveLength(1); + }); }); }); diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index e871fdeb..f99d6402 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -10,6 +10,7 @@ import { } from '../src/market-data-store'; import { type BarsQuery, + type CrossSectionQuery, FUNDAMENTALS_PIT_VALUE_FIELDS, type FundamentalsAsOfQuery, MarketDataStoreNotImplementedError, @@ -288,6 +289,7 @@ interface FakeStoreState { readonly barsCalls: BarsQuery[]; readonly shortsCalls: ShortsAsOfQuery[]; readonly fundamentalsCalls: FundamentalsAsOfQuery[]; + readonly crossSectionCalls: CrossSectionQuery[]; readonly universeCalls: UniverseQuery[]; readonly store: MarketDataStore; } @@ -296,17 +298,20 @@ function createFakeStore(options?: { bars?: readonly BarRecord[]; shortsTable?: Table; fundamentalsResolver?: (q: FundamentalsAsOfQuery) => Table | Promise
; + crossSectionResolver?: (q: CrossSectionQuery) => Table | Promise
; universeIds?: readonly number[]; universeResolver?: (q: UniverseQuery) => number[]; leaky?: boolean; barsError?: Error; shortsError?: Error; fundamentalsError?: Error; + crossSectionError?: Error; universeError?: Error; }): FakeStoreState { const barsCalls: BarsQuery[] = []; const shortsCalls: ShortsAsOfQuery[] = []; const fundamentalsCalls: FundamentalsAsOfQuery[] = []; + const crossSectionCalls: CrossSectionQuery[] = []; const universeCalls: UniverseQuery[] = []; const allBars = options?.bars ?? []; @@ -402,7 +407,14 @@ function createFakeStore(options?: { return [...(options?.universeIds ?? [])]; }, - crossSection() { + async crossSection(q: CrossSectionQuery): Promise
{ + crossSectionCalls.push(q); + if (options?.crossSectionError !== undefined) { + throw options.crossSectionError; + } + if (options?.crossSectionResolver !== undefined) { + return options.crossSectionResolver(q); + } throw new MarketDataStoreNotImplementedError('crossSection'); }, async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ @@ -426,7 +438,7 @@ function createFakeStore(options?: { }, }; - return { barsCalls, shortsCalls, fundamentalsCalls, universeCalls, store }; + return { barsCalls, shortsCalls, fundamentalsCalls, crossSectionCalls, universeCalls, store }; } async function callAnalyzeSignal(params: { @@ -1898,16 +1910,19 @@ describe('MCP analyze_signal tool — fundamentals source', () => { expect(signalSchema.additionalProperties).toBe(false); expect(Object.keys(signalSchema.properties).sort()).toEqual([ 'allowEstimatedLag', + 'featureRef', 'field', 'source', ]); - expect(signalSchema.anyOf).toHaveLength(2); + expect(signalSchema.anyOf).toHaveLength(3); expect(signalSchema.anyOf[0]?.additionalProperties).toBe(false); expect(signalSchema.anyOf[0]?.properties.source?.const).toBe('shorts'); expect(signalSchema.anyOf[1]?.additionalProperties).toBe(false); expect(signalSchema.anyOf[1]?.properties.source?.const).toBe('fundamentals'); expect(signalSchema.anyOf[1]?.properties.field?.enum).toEqual([...FUNDAMENTALS_PIT_VALUE_FIELDS]); expect(signalSchema.anyOf[1]?.properties.allowEstimatedLag?.default).toBe(false); + expect(signalSchema.anyOf[2]?.additionalProperties).toBe(false); + expect(signalSchema.anyOf[2]?.properties.source?.const).toBe('feature'); const validBase = { listingIds: [70_001, 70_002], @@ -3400,4 +3415,162 @@ describe('MCP analyze_signal tool — fundamentals source', () => { expect(badTableRes.text).toBe('SignalPanelError: Invalid signal panel input.'); expect(badTableLedger.rows).toHaveLength(0); }); + + test('signal.source === "feature" evaluates versioned crossSection features PIT, matches direct baseline, and logs trial_ledger', async () => { + const fixture = buildCeoShortsFixture({ + preCutoffSessions: 45, + postCutoffSessions: 5, + listingCount: 16, + }); + const featureRef = 'ret_1d@v1'; + const from = fixture.allDates[0]!; + const lastPreCutoff = fixture.allDates[44]!; + const postCutoff = fixture.allDates[49]!; + + // Deterministic synthetic feature values per (date, listing_id). + const valueFor = (date: string, lid: number): number => { + const dayIdx = fixture.allDates.indexOf(date); + return ((lid * 17 + dayIdx * 13) % 29) / 100 - 0.14; + }; + + const fakeStore = createFakeStore({ + bars: fixture.bars, + crossSectionResolver: q => { + expect(q.features).toEqual([featureRef]); + expect(q.universe).toBe('US_EQ'); + return { + columns: ['listing_id', featureRef], + rows: [ + ...fixture.listingIds.map(lid => ({ + listing_id: lid, + [featureRef]: valueFor(q.date, lid), + })), + // Extra unrequested listing and non-finite/null rows should be ignored cleanly. + { listing_id: 999_999, [featureRef]: 999.0 }, + ], + }; + }, + }); + const fakeLedger = createFakeTrialLedger(); + + // 1. Invalid featureRef and FX universeMarket are rejected with zero store/ledger calls. + for (const badArgs of [ + { + listingIds: fixture.listingIds, + from, + to: lastPreCutoff, + signal: { source: 'feature', featureRef: 'bad_no_version' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + { + listingIds: fixture.listingIds, + from, + to: lastPreCutoff, + signal: { source: 'feature', featureRef }, + horizonSessions: 5, + universeMarket: 'FX', + horizonBucket: 'swing_1_10d', + }, + ]) { + const rejected = await callAnalyzeSignal({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: badArgs, + }); + expect(rejected.isError).toBe(true); + } + expect(fakeStore.barsCalls).toHaveLength(0); + expect(fakeStore.crossSectionCalls).toHaveLength(0); + expect(fakeLedger.rows).toHaveLength(0); + + // 2. Valid feature study spanning past vaultCutoffTs fences crossSection queries strictly < vaultCutoffTs. + const res = await callAnalyzeSignal({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + listingIds: fixture.listingIds, + from, + to: postCutoff, + asOf: postCutoff, + signal: { source: 'feature', featureRef }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + + expect(res.isError).toBe(false); + const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; + expect(payload.status).toBe('ok'); + expect(payload.signal).toEqual({ source: 'feature', featureRef }); + expect(fakeStore.crossSectionCalls.length).toBe(45); + for (const call of fakeStore.crossSectionCalls) { + expect(call.date < fixture.vaultCutoffDate).toBe(true); + expect(call.asOf).toBeDefined(); + expect(Date.parse(call.asOf!)).toBeLessThan(fixture.vaultCutoffTs); + } + + // 3. Direct baseline equivalence & deterministic expression hash. + const preBars = fixture.bars.filter( + b => b.ts < fixture.vaultCutoffTs && b.knownAt < fixture.vaultCutoffTs + ); + const directSignals: SignalObservation[] = []; + for (const bar of preBars) { + const sessionDate = new Date(bar.ts).toISOString().slice(0, 10); + directSignals.push({ + listingId: bar.listingId, + knownAt: bar.ts, + value: valueFor(sessionDate, bar.listingId), + }); + } + const directBuilt = buildForwardReturnPanel({ + bars: preBars, + signals: directSignals, + horizonSessions: 5, + vaultCutoffDate: fixture.vaultCutoffDate, + }); + const baselineLedger = createFakeTrialLedger(); + const expectedExpr = { + expression: `mcp:analyze_signal:v1:feature:${featureRef}`, + params: { + version: 1, + signalSource: 'feature', + featureRef, + horizonSessions: 5, + maxSignalAgeSessions: null, + adjustment: 'raw', + ledgerSeries: 'rank_ic', + effectiveFrom: payload.effectiveFrom, + effectiveTo: payload.effectiveTo, + effectiveAsOf: payload.effectiveAsOf, + }, + universe: { + kind: 'listingIds', + listingIds: [...fixture.listingIds].sort((a, b) => a - b), + }, + horizon: '5d', + }; + const directStudy = await analyzeSignal(baselineLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: expectedExpr, + panel: directBuilt.panel, + vaultCutoffDate: fixture.vaultCutoffDate, + ledgerSeries: 'rank_ic', + }); + + expect(directStudy.status).toBe('ok'); + if (payload.status === 'ok' && directStudy.status === 'ok') { + expect(payload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); + expect(payload.trial.expressionHash).toBe(canonicalExpressionHash(expectedExpr)); + } + expect(fakeLedger.rows).toHaveLength(1); + expect(fakeLedger.rows[0]?.stage).toBe('signal_ic'); + expect(fakeLedger.rows[0]?.expression_hash).toBe(canonicalExpressionHash(expectedExpr)); + }); }); diff --git a/libs/research/test/mcp-stdio-host.test.ts b/libs/research/test/mcp-stdio-host.test.ts index 3dd7cdee..22c56f8b 100644 --- a/libs/research/test/mcp-stdio-host.test.ts +++ b/libs/research/test/mcp-stdio-host.test.ts @@ -1190,6 +1190,98 @@ describe('runResearchCopilotStdioHost', () => { expect(caughtSafe).toBe(safeAggregate); }); + + test('parses optional RESEARCH_MCP_QUESTDB_* URL or host/port/user/password/database, rejects conflicting/partial configs, and redacts QuestDB secrets', async () => { + // 1. DuckDB-only startup omits questdb when unset. + const baseConfig = parseResearchCopilotHostConfig(buildValidEnv()); + expect(baseConfig.questdb).toBeUndefined(); + expect('questdb' in baseConfig).toBe(false); + + // 2. URL mode (+ optional SSL). + const questSecret = 'qdb_s3cr!t#42'; + const questUrl = `postgresql://admin:${encodeURIComponent(questSecret)}@10.0.0.51:8812/qdb`; + const urlConfig = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_URL: questUrl, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }) + ); + expect(urlConfig.questdb).toEqual({ + url: questUrl, + ssl: true, + }); + + // 3. Discrete host mode with defaults and explicit overrides. + const hostDefaultConfig = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', + }) + ); + expect(hostDefaultConfig.questdb).toEqual({ + host: '10.0.0.51', + port: 8812, + database: 'qdb', + }); + + const hostFullConfig = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', + RESEARCH_MCP_QUESTDB_PG_PORT: '18812', + RESEARCH_MCP_QUESTDB_DATABASE: 'qdb_m2', + RESEARCH_MCP_QUESTDB_USER: 'reader', + RESEARCH_MCP_QUESTDB_PASSWORD: questSecret, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }) + ); + expect(hostFullConfig.questdb).toEqual({ + host: '10.0.0.51', + port: 18812, + database: 'qdb_m2', + user: 'reader', + password: questSecret, + ssl: false, + }); + + // 4. Rejects conflicting URL + host, partial port-without-host, bad port, bad ssl, unknown var. + const invalidEnvs: Array> = [ + { RESEARCH_MCP_QUESTDB_URL: questUrl, RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51' }, + { RESEARCH_MCP_QUESTDB_PG_PORT: '8812' }, + { RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', RESEARCH_MCP_QUESTDB_PG_PORT: '99999' }, + { RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', RESEARCH_MCP_QUESTDB_SSL: 'maybe' }, + { RESEARCH_MCP_QUESTDB_UNKNOWN: '1' }, + ]; + for (const override of invalidEnvs) { + expect(() => parseResearchCopilotHostConfig(buildValidEnv(override))).toThrow( + ResearchCopilotHostConfigError + ); + } + + // 5. Redacts QuestDB URL / password on openStore and cleanup errors. + for (const cfg of [urlConfig, hostFullConfig]) { + let caught: unknown; + try { + await runResearchCopilotStdioHost({ + config: cfg, + openExecutor: async () => ({ + executor: createFakeExecutor().executor, + close: async () => {}, + }), + openStore: async () => { + throw new Error(`connect failed for ${cfg.questdb?.url ?? cfg.questdb?.password}`); + }, + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).not.toContain(questSecret); + expect((caught as Error).message).not.toContain(questUrl); + } + }); }); describe('stdio-host dependency-free source invariants', () => { diff --git a/scripts/questdb-init-m2.ts b/scripts/questdb-init-m2.ts new file mode 100644 index 00000000..f0094709 --- /dev/null +++ b/scripts/questdb-init-m2.ts @@ -0,0 +1,87 @@ +#!/usr/bin/env bun +/** + * Opt-in CLI to initialize M2 QuestDB 10.2.0 intraday tables (`bars_1m`, + * `fx_1m`, `bar_revisions`) via PGWire using `applyM2IntradayDDL()`. + * + * Connection env vars (checked in order): + * - `QUESTDB_URL` or `RESEARCH_MCP_QUESTDB_URL` + * - `QUESTDB_HOST` / `RESEARCH_MCP_QUESTDB_HOST` (default `localhost`) + * - `QUESTDB_PG_PORT` / `RESEARCH_MCP_QUESTDB_PG_PORT` (default `8812`) + * - `QUESTDB_DATABASE` / `RESEARCH_MCP_QUESTDB_DATABASE` (default `qdb`) + * - `QUESTDB_USER` / `RESEARCH_MCP_QUESTDB_USER` + * - `QUESTDB_PASSWORD` / `RESEARCH_MCP_QUESTDB_PASSWORD` + * - `QUESTDB_SSL` / `RESEARCH_MCP_QUESTDB_SSL` (`true` | `false`) + */ + +import { + applyM2IntradayDDL, + openQuestDbPgExecutor, + type QuestDbPgExecutorConfig, +} from '@stock-bot/questdb'; + +function readEnv(primary: string, fallback: string): string | undefined { + const value = process.env[primary] ?? process.env[fallback]; + if (value === undefined) { + return undefined; + } + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +} + +function resolveConfig(): QuestDbPgExecutorConfig { + const url = readEnv('QUESTDB_URL', 'RESEARCH_MCP_QUESTDB_URL'); + const sslRaw = readEnv('QUESTDB_SSL', 'RESEARCH_MCP_QUESTDB_SSL'); + const ssl = + sslRaw === undefined + ? undefined + : sslRaw.toLowerCase() === 'true' || sslRaw === '1' + ? true + : sslRaw.toLowerCase() === 'false' || sslRaw === '0' + ? false + : undefined; + + if (url !== undefined) { + return { + url, + ...(ssl !== undefined ? { ssl } : {}), + }; + } + + const host = readEnv('QUESTDB_HOST', 'RESEARCH_MCP_QUESTDB_HOST') ?? 'localhost'; + const portRaw = readEnv('QUESTDB_PG_PORT', 'RESEARCH_MCP_QUESTDB_PG_PORT'); + const port = portRaw !== undefined ? Number(portRaw) : 8812; + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`Invalid QuestDB PGWire port "${String(portRaw)}". Expected 1..65535.`); + } + const database = readEnv('QUESTDB_DATABASE', 'RESEARCH_MCP_QUESTDB_DATABASE') ?? 'qdb'; + const user = readEnv('QUESTDB_USER', 'RESEARCH_MCP_QUESTDB_USER'); + const password = readEnv('QUESTDB_PASSWORD', 'RESEARCH_MCP_QUESTDB_PASSWORD'); + + return { + host, + port, + database, + ...(user !== undefined ? { user } : {}), + ...(password !== undefined ? { password } : {}), + ...(ssl !== undefined ? { ssl } : {}), + }; +} + +async function main(): Promise { + const config = resolveConfig(); + const handle = await openQuestDbPgExecutor(config); + try { + const result = await applyM2IntradayDDL(handle.executor); + process.stdout.write( + `Initialized QuestDB M2 intraday tables: ${result.appliedTables.join(', ')}\n` + ); + } finally { + await handle.close(); + } +} + +main().catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + process.stderr.write(`questdb-init-m2 failed: ${message}\n`); + process.exit(1); +});