stock-bot/libs/data/duckdb/test/research-copilot-store.test.ts

530 lines
18 KiB
TypeScript

import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DuckDBConnection, DuckDBInstance } from '@duckdb/node-api';
import {
createNodeDuckDbExecutor,
openResearchCopilotStore,
} from '@stock-bot/duckdb';
import {
MarketDataStoreValidationError,
VaultHoldoutFenceError,
VaultScopeNotAuthorizedError,
type BarRecord,
} from '@stock-bot/research/market-data-store';
import {
RESEARCH_COPILOT_HOST_NAME,
RESEARCH_COPILOT_HOST_VERSION,
runResearchCopilotStdioHost,
type PostgresResearchCopilotExecutor,
type QueryDataResultPayload,
type ResearchCopilotHostConfig,
type ResearchCopilotStdioHostDeps,
type StdioInput,
type StdioOutput,
} from '@stock-bot/research/mcp';
// Pinned synthetic fixture for T-184 (real-DuckDB store factory & stdio host wiring):
// - Listing 101 (USD), Vault cutoff 2025-06-01T00:00:00.000Z
// - Baseline visible row: 2025-05-30 20:00:00Z (known_at 2025-05-30 20:00:00Z)
// - Excluded rows:
// * at-cutoff ts: 2025-06-01 00:00:00Z (known_at 2025-05-30 20:00:00Z)
// * post-cutoff ts: 2025-06-02 20:00:00Z (known_at 2025-06-02 20:00:00Z)
// * late-known pre-cutoff ts: 2025-05-29 20:00:00Z (known_at 2025-06-01 00:00:00Z)
const LISTING_ID = 101;
const VAULT_CUTOFF_MS = Date.UTC(2025, 5, 1, 0, 0, 0, 0);
const FIXED_NOW_MS = Date.UTC(2025, 4, 31, 12, 0, 0, 0);
const FAKE_POSTGRES_URL =
'postgresql://research_ro:test_only_not_a_real_secret@127.0.0.1:5433/trading_bot_dev?sslmode=disable';
const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
const EXPECTED_VISIBLE_BAR: BarRecord = {
listingId: LISTING_ID,
ts: Date.UTC(2025, 4, 30, 20, 0, 0, 0),
open: 100.5,
high: 102.25,
low: 99.75,
close: 101.5,
volume: 123_456,
vwap: 101.1,
knownAt: Date.UTC(2025, 4, 30, 20, 0, 0, 0),
};
const tempDirs: string[] = [];
const activeSpies: Array<{ mockRestore(): void }> = [];
function trackSpy<T extends { mockRestore(): void }>(spy: T): T {
activeSpies.push(spy);
return spy;
}
afterEach(async () => {
while (activeSpies.length > 0) {
activeSpies.pop()?.mockRestore();
}
while (tempDirs.length > 0) {
const dir = tempDirs.pop();
if (dir !== undefined) {
await rm(dir, { recursive: true, force: true });
}
}
});
function buildHostConfig(
curatedRoot: string,
overrides: Partial<ResearchCopilotHostConfig> = {}
): ResearchCopilotHostConfig {
return {
postgresUrl: FAKE_POSTGRES_URL,
curatedRoot,
vaultCutoffTs: VAULT_CUTOFF_MS,
principalId: VALID_AGENT_PRINCIPAL,
libraryRoot: '/tmp/unused-library-root',
referenceListingIds: { XNYS: [LISTING_ID] },
...overrides,
};
}
function buildDuckDbBudgetEnv(duckTempDir: string): Readonly<Record<string, string>> {
return {
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
STOCK_BOT_DUCKDB_THREADS: '2',
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
};
}
async function buildBarsFixture(): Promise<{
readonly curatedRoot: string;
readonly duckTempDir: string;
}> {
const root = await mkdtemp(join(tmpdir(), 'stockbot-mcp-duckdb-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true });
await mkdir(duckTempDir, { recursive: true });
const writer = await createNodeDuckDbExecutor();
try {
await writer.run(`
COPY (
SELECT * FROM (VALUES
(${LISTING_ID}::INTEGER, DATE '2025-05-29', TIMESTAMPTZ '2025-05-29 20:00:00+00', 94.0::DOUBLE, 96.0::DOUBLE, 93.5::DOUBLE, 95.0::DOUBLE, 80000.0::DOUBLE, 94.8::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-06-01 00:00:00+00'),
(${LISTING_ID}::INTEGER, DATE '2025-05-30', TIMESTAMPTZ '2025-05-30 20:00:00+00', 100.5::DOUBLE, 102.25::DOUBLE, 99.75::DOUBLE, 101.5::DOUBLE, 123456.0::DOUBLE, 101.1::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-30 20:00:00+00'),
(${LISTING_ID}::INTEGER, DATE '2025-06-01', TIMESTAMPTZ '2025-06-01 00:00:00+00', 199.0::DOUBLE, 201.0::DOUBLE, 198.0::DOUBLE, 200.0::DOUBLE, 200000.0::DOUBLE, 199.5::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-30 20:00:00+00'),
(${LISTING_ID}::INTEGER, DATE '2025-06-02', TIMESTAMPTZ '2025-06-02 20:00:00+00', 299.0::DOUBLE, 301.0::DOUBLE, 298.0::DOUBLE, 300.0::DOUBLE, 300000.0::DOUBLE, 299.5::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-06-02 20:00:00+00')
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
`);
} finally {
await writer.close();
}
return { curatedRoot, duckTempDir };
}
function createMemoryOutput(): {
readonly output: StdioOutput;
jsonLines(): unknown[];
} {
const chunks: string[] = [];
const output: StdioOutput = {
write(chunk: string): boolean {
chunks.push(chunk);
return true;
},
};
return {
output,
jsonLines: () => {
const raw = chunks.join('');
if (raw.length === 0) {
return [];
}
return raw
.trimEnd()
.split('\n')
.map(line => JSON.parse(line) as unknown);
},
};
}
function createMemoryInput(messages: readonly unknown[]): StdioInput {
return {
async *[Symbol.asyncIterator]() {
for (const msg of messages) {
yield `${JSON.stringify(msg)}\n`;
}
},
};
}
function createFakePostgresExecutor(): {
readonly executor: PostgresResearchCopilotExecutor;
readonly calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }>;
} {
const calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }> = [];
const executor: PostgresResearchCopilotExecutor = {
async query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
calls.push({ text, params });
return { rows: [] };
},
};
return { executor, calls };
}
async function collectBars(
iterable: AsyncIterable<{ readonly rows: readonly BarRecord[] }>
): Promise<BarRecord[]> {
const rows: BarRecord[] = [];
for await (const batch of iterable) {
rows.push(...batch.rows);
}
return rows;
}
describe('openResearchCopilotStore (@duckdb/node-api)', () => {
test('source invariants: no pg import, no process.env read, no console logging, always vault-fenced', () => {
const sourcePath = join(import.meta.dir, '..', 'src', 'research-copilot-store.ts');
const source = readFileSync(sourcePath, 'utf8');
expect(source).not.toMatch(/from\s+['"]pg['"]/);
expect(source).not.toMatch(/require\(\s*['"]pg['"]\s*\)/);
expect(source).not.toContain('process.env');
expect(source).not.toMatch(/\bprocess\b/);
expect(source).not.toContain('console.');
expect(source).toContain('vaultOperatorAuthorized: false');
// Verify typed assignability to ResearchCopilotStdioHostDeps['openStore'] without casts.
const directFactory: ResearchCopilotStdioHostDeps['openStore'] = openResearchCopilotStore;
const wrappedFactory: ResearchCopilotStdioHostDeps['openStore'] = cfg =>
openResearchCopilotStore(cfg);
expect(typeof directFactory).toBe('function');
expect(typeof wrappedFactory).toBe('function');
});
test('enforces single Vault cutoff directly on store.bars(), replays identically, and blocks vault_evaluation_only even for operator principal', async () => {
const { curatedRoot, duckTempDir } = await buildBarsFixture();
const config = buildHostConfig(curatedRoot, { principalId: 'operator' });
const handle = await openResearchCopilotStore(config, {
env: buildDuckDbBudgetEnv(duckTempDir),
});
try {
expect(Object.keys(handle).sort()).toEqual(['close', 'store']);
// Straddling query: to and asOf exceed cutoff -> only visible pre-cutoff row returned.
const firstRun = await collectBars(
handle.store.bars({
listingIds: [LISTING_ID],
timeframe: '1d',
from: '2025-05-28',
to: '2025-06-05',
asOf: '2025-06-05',
adjustment: 'raw',
})
);
expect(firstRun).toEqual([EXPECTED_VISIBLE_BAR]);
// Replay produces identical results.
const replayRun = await collectBars(
handle.store.bars({
listingIds: [LISTING_ID],
timeframe: '1d',
from: '2025-05-28',
to: '2025-06-05',
asOf: '2025-06-05',
adjustment: 'raw',
})
);
expect(replayRun).toEqual(firstRun);
// Query starting at cutoff throws VaultHoldoutFenceError.
let atCutoffErr: unknown;
try {
await collectBars(
handle.store.bars({
listingIds: [LISTING_ID],
timeframe: '1d',
from: '2025-06-01',
to: '2025-06-05',
adjustment: 'raw',
})
);
} catch (err) {
atCutoffErr = err;
}
expect(atCutoffErr).toBeInstanceOf(VaultHoldoutFenceError);
// Query starting after cutoff throws VaultHoldoutFenceError.
let afterCutoffErr: unknown;
try {
await collectBars(
handle.store.bars({
listingIds: [LISTING_ID],
timeframe: '1d',
from: '2025-06-02',
to: '2025-06-05',
adjustment: 'raw',
})
);
} catch (err) {
afterCutoffErr = err;
}
expect(afterCutoffErr).toBeInstanceOf(VaultHoldoutFenceError);
// vault_evaluation_only is always rejected even when config.principalId is 'operator'.
let scopeErr: unknown;
try {
await collectBars(
handle.store.bars({
listingIds: [LISTING_ID],
timeframe: '1d',
from: '2025-05-28',
to: '2025-06-05',
adjustment: 'raw',
scope: 'vault_evaluation_only',
})
);
} catch (err) {
scopeErr = err;
}
expect(scopeErr).toBeInstanceOf(VaultScopeNotAuthorizedError);
} finally {
await handle.close();
}
});
test('wires into runResearchCopilotStdioHost end-to-end, serves initialize + query_data, and closes DuckDB exactly once at EOF', async () => {
const { curatedRoot, duckTempDir } = await buildBarsFixture();
const config = buildHostConfig(curatedRoot);
const fakePg = createFakePostgresExecutor();
const sink = createMemoryOutput();
const input = createMemoryInput([
{
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: 'duckdb-host-test', version: '1.0.0' },
},
},
{
jsonrpc: '2.0',
method: 'notifications/initialized',
},
{
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
params: {
name: 'query_data',
arguments: {
listingIds: [LISTING_ID],
from: '2025-05-28',
to: '2025-06-05',
asOf: '2025-06-05',
},
},
},
]);
// Install call-through spies after fixture writer is closed so counts reflect only the host store.
const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync'));
const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync'));
let capturedStore: Awaited<ReturnType<typeof openResearchCopilotStore>>['store'] | undefined;
await runResearchCopilotStdioHost({
config,
openExecutor: async () => ({
executor: fakePg.executor,
close: async () => {},
}),
openStore: async cfg => {
const opened = await openResearchCopilotStore(cfg, {
env: buildDuckDbBudgetEnv(duckTempDir),
});
capturedStore = opened.store;
return opened;
},
createLibraryCardReader: async () => ({
listLibraryCards: async () => [],
}),
newId: () => 'id-1',
now: () => FIXED_NOW_MS,
stdio: { input, output: sink.output },
});
const responses = sink.jsonLines() as Array<{
readonly id: number;
readonly result: Record<string, unknown>;
}>;
expect(responses).toHaveLength(2);
expect(responses[0]!.id).toBe(1);
expect(responses[0]!.result.serverInfo).toEqual({
name: RESEARCH_COPILOT_HOST_NAME,
version: RESEARCH_COPILOT_HOST_VERSION,
});
expect(responses[1]!.id).toBe(2);
const toolEnvelope = responses[1]!.result as {
readonly isError?: boolean;
readonly content: ReadonlyArray<{ readonly type: 'text'; readonly text: string }>;
};
expect(toolEnvelope.isError).toBeUndefined();
const payload = JSON.parse(toolEnvelope.content[0]!.text) as QueryDataResultPayload;
expect(payload.vaultCutoffTs).toBe(VAULT_CUTOFF_MS);
expect(payload.clampedTo).toBe(true);
expect(payload.clampedAsOf).toBe(true);
expect(payload.toMs).toBe(VAULT_CUTOFF_MS - 1);
expect(payload.asOfMs).toBe(VAULT_CUTOFF_MS - 1);
expect(payload.rows).toEqual([EXPECTED_VISIBLE_BAR]);
expect(fakePg.calls).toHaveLength(0);
expect(connCloseSpy).toHaveBeenCalledTimes(1);
expect(instCloseSpy).toHaveBeenCalledTimes(1);
// Confirm the host-opened store rejects subsequent queries after EOF cleanup.
expect(capturedStore).toBeDefined();
let postCloseErr: unknown;
try {
await collectBars(
capturedStore!.bars({
listingIds: [LISTING_ID],
timeframe: '1d',
from: '2025-05-28',
to: '2025-05-31',
adjustment: 'raw',
})
);
} catch (err) {
postCloseErr = err;
}
expect(postCloseErr).toBeInstanceOf(Error);
expect((postCloseErr as Error).message).toContain('closed');
});
test('directly opened handle resolves close() and rejects subsequent valid bars() queries', async () => {
const { curatedRoot, duckTempDir } = await buildBarsFixture();
const config = buildHostConfig(curatedRoot);
const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync'));
const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync'));
const handle = await openResearchCopilotStore(config, {
env: buildDuckDbBudgetEnv(duckTempDir),
});
await handle.close();
await handle.close();
expect(connCloseSpy).toHaveBeenCalledTimes(1);
expect(instCloseSpy).toHaveBeenCalledTimes(1);
let postCloseErr: unknown;
try {
await collectBars(
handle.store.bars({
listingIds: [LISTING_ID],
timeframe: '1d',
from: '2025-05-28',
to: '2025-05-31',
adjustment: 'raw',
})
);
} catch (err) {
postCloseErr = err;
}
expect(postCloseErr).toBeInstanceOf(Error);
expect((postCloseErr as Error).message).toContain('closed');
});
test('fail-closed: empty curatedRoot rejects on first bars() read and closes cleanly in finally', async () => {
const root = await mkdtemp(join(tmpdir(), 'stockbot-mcp-empty-'));
tempDirs.push(root);
const emptyCuratedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(emptyCuratedRoot, { recursive: true });
await mkdir(duckTempDir, { recursive: true });
const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync'));
const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync'));
const handle = await openResearchCopilotStore(buildHostConfig(emptyCuratedRoot), {
env: buildDuckDbBudgetEnv(duckTempDir),
});
let readErr: unknown;
try {
await collectBars(
handle.store.bars({
listingIds: [LISTING_ID],
timeframe: '1d',
from: '2025-05-28',
to: '2025-05-31',
adjustment: 'raw',
})
);
} catch (err) {
readErr = err;
} finally {
await handle.close();
}
expect(readErr).toBeInstanceOf(Error);
expect(connCloseSpy).toHaveBeenCalledTimes(1);
expect(instCloseSpy).toHaveBeenCalledTimes(1);
});
test('fail-closed: invalid relative curatedRoot closes acquired connection and instance before rejecting', async () => {
const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync'));
const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync'));
let openErr: unknown;
try {
await openResearchCopilotStore(buildHostConfig('relative/curated/root'));
} catch (err) {
openErr = err;
}
expect(openErr).toBeInstanceOf(MarketDataStoreValidationError);
expect(connCloseSpy).toHaveBeenCalledTimes(1);
expect(instCloseSpy).toHaveBeenCalledTimes(1);
});
test('fail-closed: rejected native instance.connect() closes allocated DuckDBInstance before propagating error', async () => {
const connectFailure = new Error('simulated native connect failure');
const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync'));
const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync'));
const connectSpy = trackSpy(
spyOn(DuckDBInstance.prototype, 'connect').mockImplementationOnce(async () => {
throw connectFailure;
})
);
let openErr: unknown;
try {
await openResearchCopilotStore(buildHostConfig('/tmp/unused-curated-root'));
} catch (err) {
openErr = err;
}
expect(openErr).toBe(connectFailure);
expect(connectSpy).toHaveBeenCalledTimes(1);
expect(connCloseSpy).toHaveBeenCalledTimes(0);
expect(instCloseSpy).toHaveBeenCalledTimes(1);
});
});