T-210: M2.3s — Implement MarketDataStore.macroAsOf, crossSection, QuestDB fx('1m'), and copilot 1m routing
This commit is contained in:
commit
6c6e132b83
25 changed files with 3209 additions and 82 deletions
1
bun.lock
1
bun.lock
|
|
@ -360,6 +360,7 @@
|
|||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@duckdb/node-api": "^1.4.4-r.1",
|
||||
"@stock-bot/questdb": "workspace:*",
|
||||
"@stock-bot/research": "workspace:*",
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@
|
|||
},
|
||||
"dependencies": {
|
||||
"@duckdb/node-api": "^1.4.4-r.1",
|
||||
"@stock-bot/questdb": "workspace:*",
|
||||
"@stock-bot/research": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
|||
|
|
@ -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<QuestDbPgExecutorHandle>;
|
||||
|
||||
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<Record<string, string | undefined>>;
|
||||
/** 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<void> | null = null;
|
||||
const close = (): Promise<void> => {
|
||||
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'];
|
||||
|
|
|
|||
|
|
@ -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,385 @@ 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('macroAsOf and crossSection point-in-time edge cases via real DuckDB (QA)', () => {
|
||||
const budgetEnv = (duckTempDir: string) => ({
|
||||
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
|
||||
STOCK_BOT_DUCKDB_THREADS: '2',
|
||||
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
|
||||
});
|
||||
|
||||
test('crossSection keeps recently delisted listings, picks latest pre-asOf restatement, and never leaks post-cutoff bars or feature revisions', async () => {
|
||||
// Arrange
|
||||
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-xsec-pit-'));
|
||||
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', 'mom_5d', 'v2', '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 {
|
||||
// 301: last bar 2025-05-08 (inside 7-day lookback from 2025-05-14) -> recently delisted, kept.
|
||||
// 302: last bar 2025-05-06 (outside lookback) -> excluded.
|
||||
// 303: first bar 2025-05-15 (post-cutoff session) -> excluded.
|
||||
// 304: 2025-05-14 bar whose known_at lands after the cutoff -> excluded even with a late asOf.
|
||||
// 305: active 2025-05-14.
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(301::INTEGER, DATE '2025-05-08', TIMESTAMPTZ '2025-05-08 20:00:00+00', 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 10.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-08 20:00:00+00'),
|
||||
(302::INTEGER, DATE '2025-05-06', TIMESTAMPTZ '2025-05-06 20:00:00+00', 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 10.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-06 20:00:00+00'),
|
||||
(303::INTEGER, DATE '2025-05-15', TIMESTAMPTZ '2025-05-15 20:00:00+00', 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 10.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-15 20:00:00+00'),
|
||||
(304::INTEGER, DATE '2025-05-14', TIMESTAMPTZ '2025-05-14 20:00:00+00', 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 10.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-15 01:00:00+00'),
|
||||
(305::INTEGER, DATE '2025-05-14', TIMESTAMPTZ '2025-05-14 20:00:00+00', 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 10.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-14 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)
|
||||
`);
|
||||
|
||||
// mom_5d@v2:
|
||||
// - 305: original (known 20:00, 1.0), restatement (known 22:00, 1.5), post-cutoff restatement (9.9).
|
||||
// - 301: prior-day and next-day rows only -> no same-day value.
|
||||
// - 304: same-day value, but listing is outside the PIT universe.
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(305::INTEGER, TIMESTAMPTZ '2025-05-14 20:00:00+00', TIMESTAMPTZ '2025-05-14 20:00:00+00', 1.0::DOUBLE),
|
||||
(305::INTEGER, TIMESTAMPTZ '2025-05-14 20:00:00+00', TIMESTAMPTZ '2025-05-14 22:00:00+00', 1.5::DOUBLE),
|
||||
(305::INTEGER, TIMESTAMPTZ '2025-05-14 20:00:00+00', TIMESTAMPTZ '2025-05-15 01:00:00+00', 9.9::DOUBLE),
|
||||
(301::INTEGER, TIMESTAMPTZ '2025-05-13 20:00:00+00', TIMESTAMPTZ '2025-05-13 20:00:00+00', 2.0::DOUBLE),
|
||||
(301::INTEGER, TIMESTAMPTZ '2025-05-15 20:00:00+00', TIMESTAMPTZ '2025-05-15 20:00:00+00', 3.0::DOUBLE),
|
||||
(304::INTEGER, TIMESTAMPTZ '2025-05-14 20:00:00+00', TIMESTAMPTZ '2025-05-14 20:00:00+00', 4.0::DOUBLE)
|
||||
) AS t(listing_id, ts, known_at, value)
|
||||
) TO '${join(curatedRoot, 'features', 'mom_5d', 'v2', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
} finally {
|
||||
await writer.close();
|
||||
}
|
||||
|
||||
const opened = await openDuckDbMarketDataStore({
|
||||
curatedRoot,
|
||||
vaultCutoffTs,
|
||||
env: budgetEnv(duckTempDir),
|
||||
});
|
||||
try {
|
||||
// Act: asOf requested past the cutoff must clamp strictly below it.
|
||||
const late = await opened.store.crossSection({
|
||||
features: ['mom_5d@v2'],
|
||||
date: '2025-05-14',
|
||||
universe: 'US_EQ',
|
||||
asOf: '2025-06-30',
|
||||
});
|
||||
// Act: asOf between original and restatement sees only the original.
|
||||
const early = await opened.store.crossSection({
|
||||
features: ['mom_5d@v2'],
|
||||
date: '2025-05-14',
|
||||
universe: 'US_EQ',
|
||||
asOf: '2025-05-14T21:00:00Z',
|
||||
});
|
||||
// Act: CA universe has no CAD listings at all.
|
||||
const ca = await opened.store.crossSection({
|
||||
features: ['mom_5d@v2'],
|
||||
date: '2025-05-14',
|
||||
universe: 'CA_EQ',
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(late.columns).toEqual(['listing_id', 'mom_5d@v2']);
|
||||
expect(late.rows).toEqual([
|
||||
{ listing_id: 301, 'mom_5d@v2': null },
|
||||
{ listing_id: 305, 'mom_5d@v2': 1.5 },
|
||||
]);
|
||||
expect(early.rows).toEqual([
|
||||
{ listing_id: 301, 'mom_5d@v2': null },
|
||||
{ listing_id: 305, 'mom_5d@v2': 1.0 },
|
||||
]);
|
||||
expect(ca.rows).toEqual([]);
|
||||
|
||||
// Path-traversal refs are rejected by validation.
|
||||
await expect(
|
||||
opened.store.crossSection({
|
||||
features: ['../mom_5d@v2'],
|
||||
date: '2025-05-14',
|
||||
universe: 'US_EQ',
|
||||
})
|
||||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('macroAsOf treats known_at == asOf as visible and honours the period_date from bound and country filter', async () => {
|
||||
// Arrange
|
||||
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-macro-pit-'));
|
||||
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);
|
||||
const writer = await createNodeDuckDbExecutor();
|
||||
try {
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2024-12-31', TIMESTAMPTZ '2025-01-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.75::DOUBLE),
|
||||
('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-02-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.50::DOUBLE),
|
||||
('GB'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-02-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.00::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: budgetEnv(duckTempDir),
|
||||
});
|
||||
try {
|
||||
// Act
|
||||
const atBoundary = await opened.store.macroAsOf({
|
||||
countries: ['US', 'CA'],
|
||||
indicators: ['policy_rate'],
|
||||
from: '2025-01-01',
|
||||
to: '2025-03-01',
|
||||
asOf: '2025-02-01T00:00:00Z',
|
||||
});
|
||||
const justBefore = await opened.store.macroAsOf({
|
||||
countries: ['US', 'CA'],
|
||||
indicators: ['policy_rate'],
|
||||
from: '2025-01-01',
|
||||
to: '2025-03-01',
|
||||
asOf: '2025-01-31T23:59:59.999Z',
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(atBoundary.rows).toEqual([
|
||||
{
|
||||
country_iso: 'US',
|
||||
indicator: 'policy_rate',
|
||||
period_date: '2025-01-31',
|
||||
known_at: Date.UTC(2025, 1, 1),
|
||||
known_at_source: 'publication_lag_estimate',
|
||||
value: 4.5,
|
||||
},
|
||||
]);
|
||||
expect(justBefore.rows).toEqual([]);
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -9,6 +9,9 @@
|
|||
"references": [
|
||||
{
|
||||
"path": "../../research"
|
||||
},
|
||||
{
|
||||
"path": "../questdb"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,12 +27,27 @@ 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 {
|
||||
assertNoConflictingQuestDbSsl,
|
||||
hasConflictingQuestDbUrlSsl,
|
||||
hasQuestDbUrlTlsOptions,
|
||||
openQuestDbPgExecutor,
|
||||
type OpenQuestDbPgExecutorOptions,
|
||||
type QuestDbPgExecutorConfig,
|
||||
type QuestDbPgExecutorHandle,
|
||||
type QuestDbPgPoolLike,
|
||||
type QuestDbPgQueryExecutor,
|
||||
} from './pg-executor';
|
||||
|
||||
// Types
|
||||
export type {
|
||||
|
|
|
|||
248
libs/data/questdb/src/pg-executor.ts
Normal file
248
libs/data/questdb/src/pg-executor.ts
Normal file
|
|
@ -0,0 +1,248 @@
|
|||
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<string, unknown>[] }>;
|
||||
}
|
||||
|
||||
export interface QuestDbPgExecutorHandle {
|
||||
readonly executor: QuestDbPgQueryExecutor;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Minimal `pg.Pool` surface used by {@link openQuestDbPgExecutor}. */
|
||||
export interface QuestDbPgPoolLike {
|
||||
on(event: 'error', listener: (err: Error) => void): unknown;
|
||||
query(
|
||||
sql: string,
|
||||
params?: unknown[]
|
||||
): Promise<{ readonly rows: readonly unknown[] }>;
|
||||
end(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface OpenQuestDbPgExecutorOptions {
|
||||
/** Optional pool factory override for unit tests; defaults to `new Pool(cfg)`. */
|
||||
readonly createPool?: (poolConfig: PoolConfig) => QuestDbPgPoolLike;
|
||||
/**
|
||||
* Optional diagnostic callback invoked when an idle pool client emits `'error'`.
|
||||
* Always receives a credential-safe `Error`.
|
||||
*/
|
||||
readonly onPoolError?: (error: Error) => void;
|
||||
}
|
||||
|
||||
const SAFE_ERROR_CODE_RE = /^[A-Z0-9_]{1,32}$/;
|
||||
|
||||
function isQuestDbUrlTlsParamKey(rawKey: string): boolean {
|
||||
const key = rawKey.trim().toLowerCase();
|
||||
return key === 'uselibpqcompat' || key === 'ssl' || key.startsWith('ssl');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` when `rawUrl` contains any TLS/SSL query parameter
|
||||
* (`ssl`, `sslmode`, `sslcert`, `sslkey`, `sslrootcert`, `uselibpqcompat`, or
|
||||
* any other `ssl*` parameter).
|
||||
*
|
||||
* TLS settings must have a single source of truth: either configure TLS in the
|
||||
* URL query string (omitting the explicit `ssl` flag) or pass the explicit
|
||||
* `ssl` flag with a URL that contains no TLS query parameters.
|
||||
*/
|
||||
export function hasQuestDbUrlTlsOptions(rawUrl: string): boolean {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
try {
|
||||
parsed = new URL(rawUrl, 'postgres://base');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (const [rawKey] of parsed.searchParams.entries()) {
|
||||
if (isQuestDbUrlTlsParamKey(rawKey)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` when an explicit boolean `ssl` setting is combined with any
|
||||
* TLS/SSL query parameter embedded in `rawUrl`.
|
||||
*/
|
||||
export function hasConflictingQuestDbUrlSsl(rawUrl: string, _explicitSsl?: boolean): boolean {
|
||||
return hasQuestDbUrlTlsOptions(rawUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws a credential-free `RangeError` if an explicit `ssl` option is combined
|
||||
* with any TLS/SSL query parameter in `rawUrl`.
|
||||
*/
|
||||
export function assertNoConflictingQuestDbSsl(rawUrl: string, _explicitSsl?: boolean): void {
|
||||
if (hasQuestDbUrlTlsOptions(rawUrl)) {
|
||||
throw new RangeError(
|
||||
'Conflicting QuestDB TLS/SSL configuration: cannot combine an explicit "ssl" option with TLS/SSL query parameters in the QuestDB URL. Configure TLS in either the URL or the explicit "ssl" option, not both.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
|
||||
if (raw.length === 0) {
|
||||
return;
|
||||
}
|
||||
needles.add(raw);
|
||||
try {
|
||||
const decoded = decodeURIComponent(raw);
|
||||
if (decoded.length > 0) {
|
||||
needles.add(decoded);
|
||||
}
|
||||
} catch {
|
||||
// Malformed percent-encoding: raw needle is already registered.
|
||||
}
|
||||
}
|
||||
|
||||
function collectConfigSecretNeedles(config: QuestDbPgExecutorConfig): readonly string[] {
|
||||
const needles = new Set<string>();
|
||||
if (typeof config.password === 'string' && config.password.length > 0) {
|
||||
addRawAndDecodedNeedle(needles, config.password);
|
||||
}
|
||||
if (typeof config.url === 'string' && config.url.length > 0) {
|
||||
needles.add(config.url);
|
||||
try {
|
||||
const parsed = new URL(config.url);
|
||||
if (parsed.href.length > 0) {
|
||||
needles.add(parsed.href);
|
||||
}
|
||||
addRawAndDecodedNeedle(needles, parsed.password);
|
||||
for (const [key, value] of parsed.searchParams.entries()) {
|
||||
if (key.toLowerCase() === 'password' && value.length > 0) {
|
||||
addRawAndDecodedNeedle(needles, value);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Non-URL string: raw string is already covered.
|
||||
}
|
||||
}
|
||||
return Array.from(needles);
|
||||
}
|
||||
|
||||
function sanitizePoolError(err: unknown, needles: readonly string[]): Error {
|
||||
const rawCode =
|
||||
typeof err === 'object' && err !== null && 'code' in err
|
||||
? (err as { readonly code?: unknown }).code
|
||||
: undefined;
|
||||
const safeCode =
|
||||
typeof rawCode === 'string' && SAFE_ERROR_CODE_RE.test(rawCode) ? rawCode : undefined;
|
||||
|
||||
if (err instanceof Error) {
|
||||
const messageHasSecret = needles.some(needle => err.message.includes(needle));
|
||||
const stackHasSecret =
|
||||
typeof err.stack === 'string' && needles.some(needle => err.stack?.includes(needle) === true);
|
||||
if (!messageHasSecret && !stackHasSecret) {
|
||||
return err;
|
||||
}
|
||||
}
|
||||
|
||||
const message =
|
||||
safeCode !== undefined
|
||||
? `QuestDB PGWire idle pool client error (${safeCode}; details redacted).`
|
||||
: 'QuestDB PGWire idle pool client error (details redacted).';
|
||||
const sanitized = new Error(message);
|
||||
if (safeCode !== undefined) {
|
||||
(sanitized as Error & { code?: string }).code = safeCode;
|
||||
}
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
options?: OpenQuestDbPgExecutorOptions
|
||||
): Promise<QuestDbPgExecutorHandle> {
|
||||
if (config.url !== undefined && config.ssl !== undefined) {
|
||||
assertNoConflictingQuestDbSsl(config.url, config.ssl);
|
||||
}
|
||||
|
||||
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 secretNeedles = collectConfigSecretNeedles(config);
|
||||
const createPool = options?.createPool ?? ((cfg: PoolConfig) => new Pool(cfg));
|
||||
const pool = createPool(poolConfig);
|
||||
|
||||
// Register an idle-client error listener before the startup probe so backend
|
||||
// restarts or network disconnects on idle connections cannot crash the host
|
||||
// with an unhandled EventEmitter 'error' event; pg-pool automatically drops
|
||||
// the failed idle client and opens a fresh connection on the next query.
|
||||
pool.on('error', (err: Error) => {
|
||||
if (options?.onPoolError !== undefined) {
|
||||
const safeError = sanitizePoolError(err, secretNeedles);
|
||||
try {
|
||||
options.onPoolError(safeError);
|
||||
} catch {
|
||||
// Never allow diagnostic callbacks to re-throw from an EventEmitter error handler.
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
await pool.query('SELECT 1');
|
||||
} catch (err: unknown) {
|
||||
await pool.end().catch(() => undefined);
|
||||
throw err;
|
||||
}
|
||||
|
||||
let closePromise: Promise<void> | null = null;
|
||||
const close = (): Promise<void> => {
|
||||
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<string, unknown>[],
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return { executor, close };
|
||||
}
|
||||
|
|
@ -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<string> = new Set<string>(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<M2IntradayTableName, string> {
|
|||
};
|
||||
}
|
||||
|
||||
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<unknown> },
|
||||
options?: ApplyM2IntradayDDLOptions
|
||||
): Promise<ApplyM2IntradayDDLResult> {
|
||||
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<M2IntradayTableName>();
|
||||
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
|
||||
*
|
||||
|
|
|
|||
|
|
@ -1,8 +1,19 @@
|
|||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { Client, type PoolConfig } from 'pg';
|
||||
import { QuestDBHealthMonitor } from '../src/health';
|
||||
import { QuestDBInfluxWriter } from '../src/influx-writer';
|
||||
import {
|
||||
openQuestDbPgExecutor,
|
||||
type QuestDbPgPoolLike,
|
||||
} from '../src/pg-executor';
|
||||
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 +485,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', () => {
|
||||
|
|
@ -531,4 +577,189 @@ describe('QuestDB', () => {
|
|||
monitor.stopMonitoring();
|
||||
});
|
||||
});
|
||||
|
||||
describe('openQuestDbPgExecutor', () => {
|
||||
it('registers pool error listener before SELECT 1, redacts credentials, and recovers on next query after idle disconnect', async () => {
|
||||
const secret = 'qdb_idle_s3cr3t!';
|
||||
const url = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`;
|
||||
|
||||
class FakePool extends EventEmitter implements QuestDbPgPoolLike {
|
||||
connectionEpoch = 1;
|
||||
probeSawErrorListener = false;
|
||||
ended = false;
|
||||
readonly queries: Array<{ readonly sql: string; readonly epoch: number }> = [];
|
||||
|
||||
async query(sql: string): Promise<{ readonly rows: readonly unknown[] }> {
|
||||
if (sql === 'SELECT 1') {
|
||||
this.probeSawErrorListener = this.listenerCount('error') > 0;
|
||||
this.queries.push({ sql, epoch: this.connectionEpoch });
|
||||
return { rows: [{ '?column?': 1 }] };
|
||||
}
|
||||
this.queries.push({ sql, epoch: this.connectionEpoch });
|
||||
return { rows: [{ ok: true, epoch: this.connectionEpoch }] };
|
||||
}
|
||||
|
||||
async end(): Promise<void> {
|
||||
this.ended = true;
|
||||
}
|
||||
}
|
||||
|
||||
const fakePool = new FakePool();
|
||||
const observedErrors: Error[] = [];
|
||||
|
||||
const handle = await openQuestDbPgExecutor(
|
||||
{ url },
|
||||
{
|
||||
createPool: () => fakePool,
|
||||
onPoolError: err => {
|
||||
observedErrors.push(err);
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
try {
|
||||
// Listener must be attached before the startup probe runs.
|
||||
expect(fakePool.probeSawErrorListener).toBe(true);
|
||||
expect(fakePool.listenerCount('error')).toBeGreaterThan(0);
|
||||
|
||||
// Simulate QuestDB restarting while the connection opened by SELECT 1 is idle.
|
||||
const idleErr = Object.assign(
|
||||
new Error(`idle connection dropped for ${url} (password=${secret})`),
|
||||
{ code: 'ECONNRESET' }
|
||||
);
|
||||
expect(() => fakePool.emit('error', idleErr)).not.toThrow();
|
||||
|
||||
// Diagnostic callback receives a credential-free Error with the safe error code.
|
||||
expect(observedErrors).toHaveLength(1);
|
||||
expect(observedErrors[0]?.message).not.toContain(secret);
|
||||
expect(observedErrors[0]?.message).not.toContain(url);
|
||||
expect(observedErrors[0]?.message).toContain('ECONNRESET');
|
||||
expect((observedErrors[0] as Error & { code?: string }).code).toBe('ECONNRESET');
|
||||
|
||||
// Pool replaces the failed idle client and serves the next query cleanly.
|
||||
fakePool.connectionEpoch = 2;
|
||||
const result = await handle.executor.query('SELECT pair FROM fx_1m LIMIT 1');
|
||||
expect(result.rows).toEqual([{ ok: true, epoch: 2 }]);
|
||||
expect(fakePool.queries).toEqual([
|
||||
{ sql: 'SELECT 1', epoch: 1 },
|
||||
{ sql: 'SELECT pair FROM fx_1m LIMIT 1', epoch: 2 },
|
||||
]);
|
||||
} finally {
|
||||
await handle.close();
|
||||
await handle.close();
|
||||
}
|
||||
expect(fakePool.ended).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects any URL TLS/SSL query parameter when explicit ssl is set and verifies pinned pg effective TLS config without connecting', async () => {
|
||||
const secret = 'qdb_ssl_s3cr3t!';
|
||||
const base = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`;
|
||||
|
||||
const conflictingCases: ReadonlyArray<readonly [string, boolean]> = [
|
||||
[`${base}?sslmode=no-verify`, true],
|
||||
[`${base}?sslmode=no-verify`, false],
|
||||
[`${base}?sslmode=disable`, true],
|
||||
[`${base}?sslmode=disable`, false],
|
||||
[`${base}?SSLMODE=DISABLE`, true],
|
||||
[`${base}?sslmode=require`, true],
|
||||
[`${base}?sslmode=require`, false],
|
||||
[`${base}?sslmode=verify-ca`, true],
|
||||
[`${base}?sslmode=verify-ca`, false],
|
||||
[`${base}?sslmode=verify-full`, true],
|
||||
[`${base}?sslmode=verify-full`, false],
|
||||
[`${base}?sslmode=prefer`, true],
|
||||
[`${base}?sslmode=prefer`, false],
|
||||
[`${base}?sslmode=allow`, true],
|
||||
[`${base}?ssl=false`, true],
|
||||
[`${base}?ssl=false`, false],
|
||||
[`${base}?ssl=0`, true],
|
||||
[`${base}?ssl=0`, false],
|
||||
[`${base}?ssl=true`, true],
|
||||
[`${base}?ssl=true`, false],
|
||||
[`${base}?ssl=1`, true],
|
||||
[`${base}?ssl=1`, false],
|
||||
[`${base}?ssl=`, true],
|
||||
[`${base}?sslrootcert=/etc/ssl/ca.pem`, true],
|
||||
[`${base}?sslrootcert=/etc/ssl/ca.pem`, false],
|
||||
[`${base}?uselibpqcompat=true`, true],
|
||||
[`${base}?uselibpqcompat=true`, false],
|
||||
];
|
||||
|
||||
let createPoolCalls = 0;
|
||||
for (const [url, ssl] of conflictingCases) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openQuestDbPgExecutor(
|
||||
{ url, ssl },
|
||||
{
|
||||
createPool: () => {
|
||||
createPoolCalls += 1;
|
||||
throw new Error('createPool must not be called on conflicting SSL config');
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(RangeError);
|
||||
expect((caught as Error).message).toContain('SSL');
|
||||
expect((caught as Error).message).not.toContain(secret);
|
||||
expect((caught as Error).message).not.toContain(url);
|
||||
}
|
||||
expect(createPoolCalls).toBe(0);
|
||||
|
||||
// Single-source-of-truth configs proceed to pool creation and produce the
|
||||
// expected effective TLS settings in the pinned `pg` driver without opening
|
||||
// a network connection.
|
||||
const effectiveCases: ReadonlyArray<{
|
||||
readonly config: Parameters<typeof openQuestDbPgExecutor>[0];
|
||||
readonly expectedSsl: unknown;
|
||||
}> = [
|
||||
{ config: { url: base, ssl: true }, expectedSsl: true },
|
||||
{
|
||||
config: { url: `${base}?application_name=copilot`, ssl: false },
|
||||
expectedSsl: false,
|
||||
},
|
||||
{ config: { url: `${base}?sslmode=require` }, expectedSsl: {} },
|
||||
{ config: { url: `${base}?sslmode=disable` }, expectedSsl: false },
|
||||
{
|
||||
config: { url: `${base}?sslmode=no-verify` },
|
||||
expectedSsl: { rejectUnauthorized: false },
|
||||
},
|
||||
{
|
||||
config: { host: '10.0.0.51', port: 8812, database: 'qdb', ssl: true },
|
||||
expectedSsl: true,
|
||||
},
|
||||
{
|
||||
config: { host: '10.0.0.51', port: 8812, database: 'qdb', ssl: false },
|
||||
expectedSsl: false,
|
||||
},
|
||||
];
|
||||
|
||||
for (const { config, expectedSsl } of effectiveCases) {
|
||||
let capturedPoolConfig: PoolConfig | undefined;
|
||||
const pool = Object.assign(new EventEmitter(), {
|
||||
query: async () => ({ rows: [{ '?column?': 1 }] }),
|
||||
end: async () => {},
|
||||
}) as unknown as QuestDbPgPoolLike;
|
||||
const handle = await openQuestDbPgExecutor(config, {
|
||||
createPool: poolConfig => {
|
||||
capturedPoolConfig = poolConfig;
|
||||
return pool;
|
||||
},
|
||||
});
|
||||
await handle.close();
|
||||
|
||||
expect(capturedPoolConfig).toBeDefined();
|
||||
// Instantiate pg.Client without calling connect() to inspect the pinned
|
||||
// driver's effective ConnectionParameters.ssl resolution.
|
||||
const client = new Client(capturedPoolConfig);
|
||||
const effectiveSsl: unknown = (
|
||||
client as unknown as { connectionParameters: { ssl: unknown } }
|
||||
).connectionParameters.ssl;
|
||||
expect(effectiveSsl).toEqual(expectedSsl);
|
||||
expect(client.ssl as unknown).toEqual(expectedSsl);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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<Record<FeatureInputDataset, DatasetScanSpec>> = {
|
||||
|
|
@ -567,6 +569,11 @@ const DATASET_SCAN_SPECS: Readonly<Record<FeatureInputDataset, DatasetScanSpec>>
|
|||
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<Record<FeatureInputDataset, DatasetScanSpec>>
|
|||
hivePartitioning: true,
|
||||
predicateKind: 'effective_known_at',
|
||||
},
|
||||
macro: {
|
||||
relativePath: 'macro/part.parquet',
|
||||
hivePartitioning: false,
|
||||
predicateKind: 'macro_known_at',
|
||||
},
|
||||
};
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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<MarketDataStore['shortsAsOf']>[0];
|
|||
export type FxQuery = Parameters<MarketDataStore['fx']>[0];
|
||||
export type UniverseQuery = Parameters<MarketDataStore['universe']>[0];
|
||||
export type FundamentalsAsOfQuery = Parameters<MarketDataStore['fundamentalsAsOf']>[0];
|
||||
export type MacroAsOfQuery = Parameters<MarketDataStore['macroAsOf']>[0];
|
||||
export type CrossSectionQuery = Parameters<MarketDataStore['crossSection']>[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<string>();
|
||||
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 ("<name>@v<version>") for "features".',
|
||||
'features'
|
||||
);
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
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 "<name>@v<version>".`,
|
||||
'features'
|
||||
);
|
||||
}
|
||||
const match = CROSS_SECTION_FEATURE_REF_RE.exec(item);
|
||||
if (match === null) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid feature ref "${item}" at features[${i}]. Expected "<name>@v<version>" 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/<name>/v<version>/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<string, unknown>, 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<Table> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('crossSection'));
|
||||
async crossSection(q: CrossSectionQuery): Promise<Table> {
|
||||
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<Table> {
|
||||
|
|
@ -2291,8 +2615,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
|||
return mapTableRows(columns, schema, rawRows);
|
||||
},
|
||||
|
||||
macroAsOf(): Promise<Table> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('macroAsOf'));
|
||||
async macroAsOf(q: MacroAsOfQuery): Promise<Table> {
|
||||
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<number[]> {
|
||||
|
|
|
|||
|
|
@ -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<string> = new Set(['USDCAD', 'USD.CAD']);
|
||||
|
||||
/** Input query type derived from `MarketDataStore['bars']`. */
|
||||
export type QuestDbBars1mQuery = Parameters<MarketDataStore['bars']>[0];
|
||||
|
||||
/** Input query type derived from `MarketDataStore['fx']`. */
|
||||
export type QuestDbFx1mQuery = Parameters<MarketDataStore['fx']>[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<number>;
|
||||
|
|
@ -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<string, unknown>,
|
||||
rowIndex: number,
|
||||
|
|
@ -460,3 +543,140 @@ export function createQuestDbIntradayBarsReader(
|
|||
},
|
||||
};
|
||||
}
|
||||
|
||||
function mapFx1mRows(
|
||||
rows: readonly Record<string, unknown>[],
|
||||
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<MarketDataStore, 'fx'> {
|
||||
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<Table> {
|
||||
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<string, unknown>[] }`.',
|
||||
'rows'
|
||||
);
|
||||
}
|
||||
return mapFx1mRows(
|
||||
result.rows as readonly Record<string, unknown>[],
|
||||
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<MarketDataStore, 'bars' | 'fx'> {
|
||||
const barsReader = createQuestDbIntradayBarsReader(options);
|
||||
const fxReader = createQuestDbIntradayFxReader(options);
|
||||
return {
|
||||
bars(q) {
|
||||
return barsReader.bars(q);
|
||||
},
|
||||
fx(q) {
|
||||
return fxReader.fx(q);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<MarketDataStore, 'bars'>;
|
||||
/** Backing intraday reader for `bars` (and optional `fx`) queries with `timeframe: '1m'`. */
|
||||
readonly intraday: Pick<MarketDataStore, 'bars'> & Partial<Pick<MarketDataStore, 'fx'>>;
|
||||
}
|
||||
|
||||
const REQUIRED_DAILY_METHODS = [
|
||||
|
|
@ -55,7 +55,7 @@ function isDelegateObject(value: unknown): value is Record<string, unknown> {
|
|||
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);
|
||||
},
|
||||
|
||||
|
|
|
|||
|
|
@ -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<T>(target: Record<string, T>, 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,152 @@ 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 isQuestDbUrlTlsParamKey(rawKey: string): boolean {
|
||||
const key = rawKey.trim().toLowerCase();
|
||||
return key === 'uselibpqcompat' || key === 'ssl' || key.startsWith('ssl');
|
||||
}
|
||||
|
||||
function hasQuestDbUrlTlsOptions(rawUrl: string): boolean {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const [rawKey] of parsed.searchParams.entries()) {
|
||||
if (isQuestDbUrlTlsParamKey(rawKey)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
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);
|
||||
if (ssl !== undefined && hasQuestDbUrlTlsOptions(url)) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_QUESTDB_SSL,
|
||||
`Conflicting configuration variable "${ENV_QUESTDB_SSL}": cannot be combined with TLS/SSL query parameters in "${ENV_QUESTDB_URL}". Configure TLS in either the URL or "${ENV_QUESTDB_SSL}", not both.`
|
||||
);
|
||||
}
|
||||
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 +695,7 @@ export function parseResearchCopilotHostConfig(
|
|||
data[ENV_EARLY_CLOSES] !== undefined
|
||||
? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES])
|
||||
: undefined;
|
||||
const questdb = parseQuestDbConfig(data);
|
||||
|
||||
return {
|
||||
postgresUrl,
|
||||
|
|
@ -536,6 +706,7 @@ export function parseResearchCopilotHostConfig(
|
|||
libraryRoot,
|
||||
referenceListingIds,
|
||||
...(earlyCloses !== undefined ? { earlyCloses } : {}),
|
||||
...(questdb !== undefined ? { questdb } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -554,13 +725,12 @@ function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
|
|||
}
|
||||
}
|
||||
|
||||
function collectSecretNeedles(postgresUrl: string): readonly string[] {
|
||||
const needles = new Set<string>();
|
||||
if (postgresUrl.length > 0) {
|
||||
needles.add(postgresUrl);
|
||||
function collectUrlSecretNeedles(needles: Set<string>, 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 +761,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<string>();
|
||||
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 +894,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> | void> = [];
|
||||
|
|
|
|||
|
|
@ -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 "<name>@v<version>" (e.g. "ret_1d@v1").'
|
||||
)
|
||||
.describe('Canonical versioned feature reference ("<name>@v<version>"), 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<string, { readonly sessionDate: string; readonly asOfMs: number }>();
|
||||
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<number>;
|
||||
readonly sessionQueryAsOfMs: number;
|
||||
readonly seenKeys: Set<string>;
|
||||
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<McpToolCallResult> {
|
||||
|
|
@ -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<string>();
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -249,6 +249,10 @@ const SAFE_VALIDATION_FIELDS: ReadonlySet<string> = new Set([
|
|||
'adjustment',
|
||||
'scope',
|
||||
'limit',
|
||||
'countries',
|
||||
'indicators',
|
||||
'features',
|
||||
'universe',
|
||||
]);
|
||||
|
||||
const SAFE_STORE_METHODS: ReadonlySet<string> = new Set([
|
||||
|
|
|
|||
|
|
@ -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, {
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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<Table> {
|
||||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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<Table>;
|
||||
crossSectionResolver?: (q: CrossSectionQuery) => Table | Promise<Table>;
|
||||
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<Table> {
|
||||
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<Table> {
|
||||
|
|
@ -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,168 @@ 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') {
|
||||
const expectedHash = canonicalExpressionHash({
|
||||
...expectedExpr,
|
||||
sampleStart: payload.trial.sampleStart,
|
||||
sampleEnd: payload.trial.sampleEnd,
|
||||
});
|
||||
expect(payload.analysis.rankIc).toEqual(directStudy.analysis.rankIc);
|
||||
expect(payload.trial.expressionHash).toBe(expectedHash);
|
||||
expect(payload.trial.expressionHash).toBe(directStudy.trial.expressionHash);
|
||||
expect(fakeLedger.rows).toHaveLength(1);
|
||||
expect(fakeLedger.rows[0]?.stage).toBe('signal_ic');
|
||||
expect(fakeLedger.rows[0]?.expression_hash).toBe(expectedHash);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1190,6 +1190,178 @@ 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,
|
||||
// and any URL TLS/SSL query parameters combined with RESEARCH_MCP_QUESTDB_SSL without leaking secrets.
|
||||
const invalidEnvs: Array<Record<string, string>> = [
|
||||
{ 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' },
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=no-verify`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'true',
|
||||
},
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=disable`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'true',
|
||||
},
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=disable`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'false',
|
||||
},
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=require`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'true',
|
||||
},
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=require`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'false',
|
||||
},
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?ssl=false`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'true',
|
||||
},
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?ssl=false`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'false',
|
||||
},
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?ssl=true`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'false',
|
||||
},
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=prefer`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'true',
|
||||
},
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslrootcert=/etc/ssl/ca.pem`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'false',
|
||||
},
|
||||
{
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?uselibpqcompat=true`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'true',
|
||||
},
|
||||
];
|
||||
for (const override of invalidEnvs) {
|
||||
let caughtInvalid: unknown;
|
||||
try {
|
||||
parseResearchCopilotHostConfig(buildValidEnv(override));
|
||||
} catch (err) {
|
||||
caughtInvalid = err;
|
||||
}
|
||||
expect(caughtInvalid).toBeInstanceOf(ResearchCopilotHostConfigError);
|
||||
expect((caughtInvalid as Error).message).not.toContain(questSecret);
|
||||
expect((caughtInvalid as Error).message).not.toContain(questUrl);
|
||||
}
|
||||
|
||||
// Single-source-of-truth TLS configs are accepted (URL-only TLS params without
|
||||
// RESEARCH_MCP_QUESTDB_SSL, or clean URL with non-TLS query params + RESEARCH_MCP_QUESTDB_SSL).
|
||||
const urlOnlyTlsEnable = parseResearchCopilotHostConfig(
|
||||
buildValidEnv({
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=require`,
|
||||
})
|
||||
);
|
||||
expect(urlOnlyTlsEnable.questdb).toEqual({
|
||||
url: `${questUrl}?sslmode=require`,
|
||||
});
|
||||
const urlOnlyTlsDisable = parseResearchCopilotHostConfig(
|
||||
buildValidEnv({
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=disable`,
|
||||
})
|
||||
);
|
||||
expect(urlOnlyTlsDisable.questdb).toEqual({
|
||||
url: `${questUrl}?sslmode=disable`,
|
||||
});
|
||||
const flagOnlyTls = parseResearchCopilotHostConfig(
|
||||
buildValidEnv({
|
||||
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?application_name=copilot`,
|
||||
RESEARCH_MCP_QUESTDB_SSL: 'true',
|
||||
})
|
||||
);
|
||||
expect(flagOnlyTls.questdb).toEqual({
|
||||
url: `${questUrl}?application_name=copilot`,
|
||||
ssl: true,
|
||||
});
|
||||
|
||||
// 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', () => {
|
||||
|
|
|
|||
113
scripts/questdb-init-m2.ts
Normal file
113
scripts/questdb-init-m2.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
#!/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,
|
||||
assertNoConflictingQuestDbSsl,
|
||||
openQuestDbPgExecutor,
|
||||
type QuestDbPgExecutorConfig,
|
||||
} from '@stock-bot/questdb';
|
||||
|
||||
function readEnv(
|
||||
env: Readonly<Record<string, string | undefined>>,
|
||||
primary: string,
|
||||
fallback: string
|
||||
): string | undefined {
|
||||
const value = env[primary] ?? env[fallback];
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function parseSslFlag(raw: string): boolean {
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === 'true' || normalized === '1') {
|
||||
return true;
|
||||
}
|
||||
if (normalized === 'false' || normalized === '0') {
|
||||
return false;
|
||||
}
|
||||
throw new RangeError(
|
||||
'Invalid QuestDB SSL configuration: expected "true", "false", "1", or "0".'
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveQuestDbInitM2Config(
|
||||
env: Readonly<Record<string, string | undefined>> = process.env
|
||||
): QuestDbPgExecutorConfig {
|
||||
const url = readEnv(env, 'QUESTDB_URL', 'RESEARCH_MCP_QUESTDB_URL');
|
||||
const sslRaw = readEnv(env, 'QUESTDB_SSL', 'RESEARCH_MCP_QUESTDB_SSL');
|
||||
const ssl = sslRaw !== undefined ? parseSslFlag(sslRaw) : undefined;
|
||||
|
||||
if (url !== undefined) {
|
||||
if (ssl !== undefined) {
|
||||
assertNoConflictingQuestDbSsl(url, ssl);
|
||||
}
|
||||
return {
|
||||
url,
|
||||
...(ssl !== undefined ? { ssl } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const host = readEnv(env, 'QUESTDB_HOST', 'RESEARCH_MCP_QUESTDB_HOST') ?? 'localhost';
|
||||
const portRaw = readEnv(env, '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 RangeError(
|
||||
`Invalid QuestDB PGWire port "${String(portRaw)}". Expected 1..65535.`
|
||||
);
|
||||
}
|
||||
const database = readEnv(env, 'QUESTDB_DATABASE', 'RESEARCH_MCP_QUESTDB_DATABASE') ?? 'qdb';
|
||||
const user = readEnv(env, 'QUESTDB_USER', 'RESEARCH_MCP_QUESTDB_USER');
|
||||
const password = readEnv(env, 'QUESTDB_PASSWORD', 'RESEARCH_MCP_QUESTDB_PASSWORD');
|
||||
|
||||
return {
|
||||
host,
|
||||
port,
|
||||
database,
|
||||
...(user !== undefined ? { user } : {}),
|
||||
...(password !== undefined ? { password } : {}),
|
||||
...(ssl !== undefined ? { ssl } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function runQuestDbInitM2(
|
||||
env: Readonly<Record<string, string | undefined>> = process.env,
|
||||
openExecutor: typeof openQuestDbPgExecutor = openQuestDbPgExecutor
|
||||
): Promise<{ readonly appliedTables: readonly string[] }> {
|
||||
const config = resolveQuestDbInitM2Config(env);
|
||||
const handle = await openExecutor(config);
|
||||
try {
|
||||
return await applyM2IntradayDDL(handle.executor);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
runQuestDbInitM2()
|
||||
.then(result => {
|
||||
process.stdout.write(
|
||||
`Initialized QuestDB M2 intraday tables: ${result.appliedTables.join(', ')}\n`
|
||||
);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
process.stderr.write(`questdb-init-m2 failed: ${message}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
90
scripts/test/questdb-init-m2.test.ts
Normal file
90
scripts/test/questdb-init-m2.test.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { M2_INTRADAY_TABLE_NAMES } from '@stock-bot/questdb';
|
||||
import { resolveQuestDbInitM2Config, runQuestDbInitM2 } from '../questdb-init-m2';
|
||||
|
||||
describe('scripts/questdb-init-m2', () => {
|
||||
test('rejects conflicting URL SSL settings before opening a QuestDB connection', async () => {
|
||||
const secret = 'ddl_init_s3cr3t!';
|
||||
const baseUrl = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`;
|
||||
|
||||
const conflictingEnvs: Array<Record<string, string>> = [
|
||||
{ QUESTDB_URL: `${baseUrl}?sslmode=no-verify`, QUESTDB_SSL: 'true' },
|
||||
{ QUESTDB_URL: `${baseUrl}?sslmode=disable`, QUESTDB_SSL: 'true' },
|
||||
{ QUESTDB_URL: `${baseUrl}?sslmode=disable`, QUESTDB_SSL: 'false' },
|
||||
{ RESEARCH_MCP_QUESTDB_URL: `${baseUrl}?sslmode=disable`, RESEARCH_MCP_QUESTDB_SSL: 'true' },
|
||||
{ QUESTDB_URL: `${baseUrl}?sslmode=require`, QUESTDB_SSL: 'true' },
|
||||
{ QUESTDB_URL: `${baseUrl}?sslmode=require`, QUESTDB_SSL: 'false' },
|
||||
{ QUESTDB_URL: `${baseUrl}?ssl=false`, QUESTDB_SSL: 'true' },
|
||||
{ QUESTDB_URL: `${baseUrl}?ssl=false`, QUESTDB_SSL: 'false' },
|
||||
{ QUESTDB_URL: `${baseUrl}?sslmode=prefer`, QUESTDB_SSL: 'true' },
|
||||
{ QUESTDB_URL: `${baseUrl}?uselibpqcompat=true`, QUESTDB_SSL: 'true' },
|
||||
];
|
||||
|
||||
let openCalls = 0;
|
||||
for (const env of conflictingEnvs) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await runQuestDbInitM2(env, async () => {
|
||||
openCalls += 1;
|
||||
throw new Error('openExecutor must not be called on conflicting SSL config');
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(RangeError);
|
||||
expect((caught as Error).message).toContain('SSL');
|
||||
expect((caught as Error).message).not.toContain(secret);
|
||||
expect((caught as Error).message).not.toContain(baseUrl);
|
||||
}
|
||||
expect(openCalls).toBe(0);
|
||||
});
|
||||
|
||||
test('rejects invalid SSL flag values and accepts single-source-of-truth URL or flag TLS configs', async () => {
|
||||
expect(() =>
|
||||
resolveQuestDbInitM2Config({
|
||||
QUESTDB_HOST: '10.0.0.51',
|
||||
QUESTDB_SSL: 'maybe',
|
||||
})
|
||||
).toThrow(RangeError);
|
||||
|
||||
const urlOnlyTls = resolveQuestDbInitM2Config({
|
||||
QUESTDB_URL: 'postgresql://admin:pass@10.0.0.51:8812/qdb?sslmode=require',
|
||||
});
|
||||
expect(urlOnlyTls).toEqual({
|
||||
url: 'postgresql://admin:pass@10.0.0.51:8812/qdb?sslmode=require',
|
||||
});
|
||||
|
||||
const flagOnlyTls = resolveQuestDbInitM2Config({
|
||||
QUESTDB_URL: 'postgresql://admin:pass@10.0.0.51:8812/qdb?application_name=init-m2',
|
||||
QUESTDB_SSL: 'true',
|
||||
});
|
||||
expect(flagOnlyTls).toEqual({
|
||||
url: 'postgresql://admin:pass@10.0.0.51:8812/qdb?application_name=init-m2',
|
||||
ssl: true,
|
||||
});
|
||||
|
||||
const executed: string[] = [];
|
||||
let closed = false;
|
||||
const result = await runQuestDbInitM2(
|
||||
{
|
||||
QUESTDB_URL: 'postgresql://admin:pass@10.0.0.51:8812/qdb',
|
||||
QUESTDB_SSL: 'false',
|
||||
},
|
||||
async () => ({
|
||||
executor: {
|
||||
async query(sql: string) {
|
||||
executed.push(sql);
|
||||
return { rows: [] };
|
||||
},
|
||||
},
|
||||
async close() {
|
||||
closed = true;
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
expect(result.appliedTables).toEqual([...M2_INTRADAY_TABLE_NAMES]);
|
||||
expect(executed).toHaveLength(3);
|
||||
expect(closed).toBe(true);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue