T-210: M2.3s — Implement MarketDataStore.macroAsOf, crossSection, QuestDB fx('1m'), and copilot 1m routing

This commit is contained in:
Studio 2026-12-04 15:06:51 -05:00
parent a3a31f7562
commit 0c33d8ae19
23 changed files with 2440 additions and 82 deletions

View file

@ -15,6 +15,7 @@
},
"dependencies": {
"@duckdb/node-api": "^1.4.4-r.1",
"@stock-bot/questdb": "workspace:*",
"@stock-bot/research": "workspace:*"
},
"devDependencies": {

View file

@ -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'];

View file

@ -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();
}
});
});

View file

@ -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);
});
});

View file

@ -9,6 +9,9 @@
"references": [
{
"path": "../../research"
},
{
"path": "../questdb"
}
]
}