T-210: M2.3s — Implement MarketDataStore.macroAsOf, crossSection, QuestDB fx('1m'), and copilot 1m routing
This commit is contained in:
parent
a3a31f7562
commit
0c33d8ae19
23 changed files with 2440 additions and 82 deletions
|
|
@ -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,211 @@ describe('co-published ceo_post Vault boundary via real DuckDB (store.events + M
|
|||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('macroAsOf and crossSection via real DuckDB', () => {
|
||||
test('macroAsOf enforces country/indicator/date filtering, known_at <= asOf lag, Vault fence, and fail-closed provenance', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-macro-'));
|
||||
tempDirs.push(root);
|
||||
const curatedRoot = join(root, 'curated');
|
||||
const duckTempDir = join(root, 'duckdb-tmp');
|
||||
await mkdir(join(curatedRoot, 'macro'), { recursive: true });
|
||||
await mkdir(duckTempDir, { recursive: true });
|
||||
|
||||
const vaultCutoffTs = Date.UTC(2025, 4, 1, 0, 0, 0, 0); // 2025-05-01T00:00:00Z
|
||||
const writer = await createNodeDuckDbExecutor();
|
||||
try {
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-02-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.50::DOUBLE),
|
||||
('US'::VARCHAR, 'cpi_yoy'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-03-07 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 3.00::DOUBLE),
|
||||
('CA'::VARCHAR, 'gdp_qoq'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-04-06 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 1.80::DOUBLE),
|
||||
('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-04-30', TIMESTAMPTZ '2025-05-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.25::DOUBLE)
|
||||
) AS t(country_iso, indicator, period_date, known_at, known_at_source, value)
|
||||
) TO '${join(curatedRoot, 'macro', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
} finally {
|
||||
await writer.close();
|
||||
}
|
||||
|
||||
const opened = await openDuckDbMarketDataStore({
|
||||
curatedRoot,
|
||||
vaultCutoffTs,
|
||||
env: {
|
||||
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
|
||||
STOCK_BOT_DUCKDB_THREADS: '2',
|
||||
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
|
||||
},
|
||||
});
|
||||
try {
|
||||
// Early asOf sees +1d policy_rate, hides +35d cpi_yoy and +65d gdp_qoq.
|
||||
const feb = await opened.store.macroAsOf({
|
||||
countries: ['US', 'CA'],
|
||||
indicators: ['policy_rate', 'cpi_yoy', 'gdp_qoq'],
|
||||
from: '2025-01-01',
|
||||
to: '2025-06-01',
|
||||
asOf: '2025-02-15',
|
||||
});
|
||||
expect(feb.rows.map(r => `${r.country_iso}:${r.indicator}`)).toEqual(['US:policy_rate']);
|
||||
|
||||
// Post-cutoff to/asOf clamps strictly below 2025-05-01T00:00:00Z, hiding the at-cutoff row.
|
||||
const clamped = await opened.store.macroAsOf({
|
||||
countries: ['US', 'CA'],
|
||||
indicators: ['policy_rate', 'cpi_yoy', 'gdp_qoq'],
|
||||
from: '2025-01-01',
|
||||
to: '2025-06-01',
|
||||
asOf: '2025-06-01',
|
||||
});
|
||||
expect(clamped.rows.map(r => `${r.country_iso}:${r.indicator}:${r.period_date}`)).toEqual([
|
||||
'CA:gdp_qoq:2025-01-31',
|
||||
'US:cpi_yoy:2025-01-31',
|
||||
'US:policy_rate:2025-01-31',
|
||||
]);
|
||||
|
||||
// from >= vaultCutoffTs throws VaultHoldoutFenceError.
|
||||
await expect(
|
||||
opened.store.macroAsOf({
|
||||
countries: ['US'],
|
||||
indicators: ['policy_rate'],
|
||||
from: '2025-05-01',
|
||||
to: '2025-05-15',
|
||||
})
|
||||
).rejects.toBeInstanceOf(VaultHoldoutFenceError);
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
|
||||
// Corrupt provenance row fails closed with MarketDataStoreValidationError.
|
||||
const corruptRoot = join(root, 'corrupt-curated');
|
||||
await mkdir(join(corruptRoot, 'macro'), { recursive: true });
|
||||
const corruptWriter = await createNodeDuckDbExecutor();
|
||||
try {
|
||||
await corruptWriter.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
('US'::VARCHAR, 'cpi_yoy'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-03-07 00:00:00+00', 'bad_source'::VARCHAR, 3.00::DOUBLE)
|
||||
) AS t(country_iso, indicator, period_date, known_at, known_at_source, value)
|
||||
) TO '${join(corruptRoot, 'macro', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
} finally {
|
||||
await corruptWriter.close();
|
||||
}
|
||||
const corruptOpened = await openDuckDbMarketDataStore({
|
||||
curatedRoot: corruptRoot,
|
||||
vaultCutoffTs,
|
||||
env: {
|
||||
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
|
||||
STOCK_BOT_DUCKDB_THREADS: '2',
|
||||
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
|
||||
},
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
corruptOpened.store.macroAsOf({
|
||||
countries: ['US'],
|
||||
indicators: ['cpi_yoy'],
|
||||
from: '2025-01-01',
|
||||
to: '2025-04-01',
|
||||
})
|
||||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
} finally {
|
||||
await corruptOpened.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('crossSection joins versioned features to survivorship-free universe, null-fills missing/delayed rows, and enforces Vault fence', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-xsec-'));
|
||||
tempDirs.push(root);
|
||||
const curatedRoot = join(root, 'curated');
|
||||
const duckTempDir = join(root, 'duckdb-tmp');
|
||||
await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true });
|
||||
await mkdir(join(curatedRoot, 'features', 'ret_1d', 'v1', 'year=2025'), { recursive: true });
|
||||
await mkdir(join(curatedRoot, 'features', 'rsi_14', 'v1', 'year=2025'), { recursive: true });
|
||||
await mkdir(duckTempDir, { recursive: true });
|
||||
|
||||
const vaultCutoffTs = Date.UTC(2025, 4, 15, 0, 0, 0, 0); // 2025-05-15T00:00:00Z
|
||||
const writer = await createNodeDuckDbExecutor();
|
||||
try {
|
||||
// Active on 2025-05-10: 101 (USD), 102 (USD), 201 (CAD). Delisted earlier: 103 (USD, 2025-04-01).
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(101::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 10.0::DOUBLE, 11.0::DOUBLE, 9.5::DOUBLE, 10.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00'),
|
||||
(102::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 20.0::DOUBLE, 21.0::DOUBLE, 19.5::DOUBLE, 20.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00'),
|
||||
(103::INTEGER, DATE '2025-04-01', TIMESTAMPTZ '2025-04-01 20:00:00+00', 5.0::DOUBLE, 5.5::DOUBLE, 4.5::DOUBLE, 5.0::DOUBLE, 500.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-04-01 20:00:00+00'),
|
||||
(201::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 30.0::DOUBLE, 31.0::DOUBLE, 29.5::DOUBLE, 30.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00')
|
||||
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
|
||||
) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
|
||||
// ret_1d@v1: 101 known on 2025-05-09; 102 delayed until 2025-05-12; 201 known on 2025-05-09.
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(101::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', 0.02::DOUBLE),
|
||||
(102::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-12 20:00:00+00', 0.05::DOUBLE),
|
||||
(201::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', -0.01::DOUBLE)
|
||||
) AS t(listing_id, ts, known_at, value)
|
||||
) TO '${join(curatedRoot, 'features', 'ret_1d', 'v1', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
|
||||
// rsi_14@v1: only listing 101 present.
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(101::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', 62.5::DOUBLE)
|
||||
) AS t(listing_id, ts, known_at, value)
|
||||
) TO '${join(curatedRoot, 'features', 'rsi_14', 'v1', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
} finally {
|
||||
await writer.close();
|
||||
}
|
||||
|
||||
const opened = await openDuckDbMarketDataStore({
|
||||
curatedRoot,
|
||||
vaultCutoffTs,
|
||||
env: {
|
||||
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
|
||||
STOCK_BOT_DUCKDB_THREADS: '2',
|
||||
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
|
||||
},
|
||||
});
|
||||
try {
|
||||
// Omitted asOf defaults to q.date (2025-05-09) so 102's delayed ret_1d (known 2025-05-12) is NULL.
|
||||
const usSameDay = await opened.store.crossSection({
|
||||
features: ['ret_1d@v1', 'rsi_14@v1'],
|
||||
date: '2025-05-09',
|
||||
universe: 'US_EQ',
|
||||
});
|
||||
expect(usSameDay.columns).toEqual(['listing_id', 'ret_1d@v1', 'rsi_14@v1']);
|
||||
expect(usSameDay.rows).toEqual([
|
||||
{ listing_id: 101, 'ret_1d@v1': 0.02, 'rsi_14@v1': 62.5 },
|
||||
{ listing_id: 102, 'ret_1d@v1': null, 'rsi_14@v1': null },
|
||||
]);
|
||||
|
||||
// Explicit later asOf (2025-05-13) reveals 102's delayed ret_1d@v1 while US_CA_EQ includes 201.
|
||||
const usCaLater = await opened.store.crossSection({
|
||||
features: ['ret_1d@v1', 'rsi_14@v1'],
|
||||
date: '2025-05-09',
|
||||
universe: 'US_CA_EQ',
|
||||
asOf: '2025-05-13',
|
||||
});
|
||||
expect(usCaLater.rows).toEqual([
|
||||
{ listing_id: 101, 'ret_1d@v1': 0.02, 'rsi_14@v1': 62.5 },
|
||||
{ listing_id: 102, 'ret_1d@v1': 0.05, 'rsi_14@v1': null },
|
||||
{ listing_id: 201, 'ret_1d@v1': -0.01, 'rsi_14@v1': null },
|
||||
]);
|
||||
|
||||
// Post-cutoff date throws VaultHoldoutFenceError.
|
||||
await expect(
|
||||
opened.store.crossSection({
|
||||
features: ['ret_1d@v1'],
|
||||
date: '2025-05-15',
|
||||
universe: 'US_EQ',
|
||||
})
|
||||
).rejects.toBeInstanceOf(VaultHoldoutFenceError);
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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,22 @@ export {
|
|||
type IlpV2EncodeErrorKind,
|
||||
} from './ilp-v2-writer';
|
||||
export {
|
||||
applyM2IntradayDDL,
|
||||
formatCreateTableSQL,
|
||||
getM2IntradayDDL,
|
||||
M2_INTRADAY_SCHEMAS,
|
||||
M2_INTRADAY_TABLE_NAMES,
|
||||
QuestDBSchemaManager,
|
||||
type ApplyM2IntradayDDLOptions,
|
||||
type ApplyM2IntradayDDLResult,
|
||||
type M2IntradayTableName,
|
||||
} from './schema';
|
||||
export {
|
||||
openQuestDbPgExecutor,
|
||||
type QuestDbPgExecutorConfig,
|
||||
type QuestDbPgExecutorHandle,
|
||||
type QuestDbPgQueryExecutor,
|
||||
} from './pg-executor';
|
||||
|
||||
// Types
|
||||
export type {
|
||||
|
|
|
|||
80
libs/data/questdb/src/pg-executor.ts
Normal file
80
libs/data/questdb/src/pg-executor.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import { Pool, type PoolConfig } from 'pg';
|
||||
|
||||
export interface QuestDbPgExecutorConfig {
|
||||
readonly url?: string;
|
||||
readonly host?: string;
|
||||
readonly port?: number;
|
||||
readonly database?: string;
|
||||
readonly user?: string;
|
||||
readonly password?: string;
|
||||
readonly ssl?: boolean;
|
||||
readonly max?: number;
|
||||
readonly connectionTimeoutMillis?: number;
|
||||
readonly idleTimeoutMillis?: number;
|
||||
}
|
||||
|
||||
export interface QuestDbPgQueryExecutor {
|
||||
query(
|
||||
sql: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Record<string, unknown>[] }>;
|
||||
}
|
||||
|
||||
export interface QuestDbPgExecutorHandle {
|
||||
readonly executor: QuestDbPgQueryExecutor;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a lightweight PGWire `pg.Pool` executor for QuestDB read queries or
|
||||
* opt-in DDL without creating legacy tables or starting background health timers.
|
||||
*/
|
||||
export async function openQuestDbPgExecutor(
|
||||
config: QuestDbPgExecutorConfig
|
||||
): Promise<QuestDbPgExecutorHandle> {
|
||||
const poolConfig: PoolConfig = {
|
||||
max: config.max ?? 4,
|
||||
connectionTimeoutMillis: config.connectionTimeoutMillis ?? 5_000,
|
||||
idleTimeoutMillis: config.idleTimeoutMillis ?? 30_000,
|
||||
...(config.url !== undefined
|
||||
? { connectionString: config.url }
|
||||
: {
|
||||
host: config.host ?? 'localhost',
|
||||
port: config.port ?? 8812,
|
||||
database: config.database ?? 'qdb',
|
||||
...(config.user !== undefined ? { user: config.user } : {}),
|
||||
...(config.password !== undefined ? { password: config.password } : {}),
|
||||
}),
|
||||
...(config.ssl !== undefined ? { ssl: config.ssl } : {}),
|
||||
};
|
||||
|
||||
const pool = new Pool(poolConfig);
|
||||
try {
|
||||
await pool.query('SELECT 1');
|
||||
} catch (err: unknown) {
|
||||
await pool.end().catch(() => undefined);
|
||||
throw err;
|
||||
}
|
||||
|
||||
let closePromise: Promise<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
|
||||
*
|
||||
|
|
|
|||
|
|
@ -2,7 +2,12 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
|||
import { QuestDBHealthMonitor } from '../src/health';
|
||||
import { QuestDBInfluxWriter } from '../src/influx-writer';
|
||||
import { QuestDBQueryBuilder } from '../src/query-builder';
|
||||
import { QuestDBSchemaManager } from '../src/schema';
|
||||
import {
|
||||
applyM2IntradayDDL,
|
||||
getM2IntradayDDL,
|
||||
M2_INTRADAY_TABLE_NAMES,
|
||||
QuestDBSchemaManager,
|
||||
} from '../src/schema';
|
||||
import type { OHLCVData, QuestDBClientConfig, TradeData } from '../src/types';
|
||||
|
||||
// Simple in-memory QuestDB client for testing
|
||||
|
|
@ -474,6 +479,41 @@ describe('QuestDB', () => {
|
|||
expect(stats.min_timestamp).toBeDefined();
|
||||
expect(stats.max_timestamp).toBeDefined();
|
||||
});
|
||||
|
||||
it('applyM2IntradayDDL executes getM2IntradayDDL() for bars_1m, fx_1m, and bar_revisions without altering initializeDatabase()', async () => {
|
||||
const executed: string[] = [];
|
||||
const mockQueryable = {
|
||||
query: mock(async (sql: string) => {
|
||||
executed.push(sql);
|
||||
return { rows: [], count: 0 };
|
||||
}),
|
||||
};
|
||||
|
||||
const expectedDdl = getM2IntradayDDL();
|
||||
const result = await applyM2IntradayDDL(mockQueryable);
|
||||
expect(result.appliedTables).toEqual([...M2_INTRADAY_TABLE_NAMES]);
|
||||
expect(executed).toEqual([
|
||||
expectedDdl.bars_1m,
|
||||
expectedDdl.fx_1m,
|
||||
expectedDdl.bar_revisions,
|
||||
]);
|
||||
|
||||
// Subset option executes only requested tables in deduplicated order.
|
||||
executed.length = 0;
|
||||
const subset = await applyM2IntradayDDL(mockQueryable, {
|
||||
tables: ['fx_1m', 'bars_1m', 'fx_1m'],
|
||||
});
|
||||
expect(subset.appliedTables).toEqual(['fx_1m', 'bars_1m']);
|
||||
expect(executed).toEqual([expectedDdl.fx_1m, expectedDdl.bars_1m]);
|
||||
|
||||
// Rejects unknown or empty table lists.
|
||||
await expect(applyM2IntradayDDL(mockQueryable, { tables: [] })).rejects.toThrow();
|
||||
await expect(
|
||||
applyM2IntradayDDL(mockQueryable, {
|
||||
tables: ['unknown_table' as unknown as 'bars_1m'],
|
||||
})
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('QuestDBHealthMonitor', () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue