T-200: merge dev

This commit is contained in:
Studio 2026-12-03 15:23:16 -05:00
commit 267e655e63
6 changed files with 1243 additions and 1168 deletions

View file

@ -12,8 +12,8 @@ import {
runPostgresMigrations,
} from '@stock-bot/postgres';
import {
type FiledFindingRecord,
createPostgresFindingWritePort,
createPostgresKnowledgeReaders,
createPostgresTrialRefLookupPort,
} from '../../libs/research/src/mcp/index';
@ -22,11 +22,10 @@ const logger = getLogger('mcp-copilot-executor-pg-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
// Vault cutoff date 2025-06-30 (exclusive): sample_end must be < 2025-06-30 to be research-visible.
const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0);
const FIXED_TS = '2026-01-15T12:34:56.789Z';
const cleanup: (() => Promise<void> | void)[] = [];
const cleanup: Array<() => Promise<void> | void> = [];
afterEach(async () => {
let firstError: unknown;
for (const close of cleanup.splice(0).reverse()) {
@ -68,59 +67,76 @@ function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
return connectionString;
}
function buildSchemaUrl(
connectionString: string,
schema: string,
extraQuery?: Record<string, string>
): string {
const parsed = new URL(connectionString);
parsed.searchParams.set('options', `-c search_path=${schema} -c statement_timeout=0 -c lock_timeout=0`);
if (extraQuery) {
for (const [k, v] of Object.entries(extraQuery)) {
parsed.searchParams.set(k, v);
}
}
return parsed.toString();
}
function buildIsolatedPoolConfig(connectionString: string, schema: string): PoolConfig {
const parsed = new URL(connectionString);
const safeUrl = assertSafetyDatabaseUrl(connectionString);
const parsed = new URL(safeUrl);
const existingOptions = parsed.searchParams
.getAll('options')
.map(value => value.trim())
.filter(value => value.length > 0);
parsed.searchParams.delete('options');
const options = [
...existingOptions,
`-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
].join(' ');
return {
connectionString: parsed.toString(),
options,
};
}
function buildExecutorUrl(
connectionString: string,
schema: string,
applicationName: string,
extraParams?: Readonly<Record<string, string>>
): string {
const safeUrl = assertSafetyDatabaseUrl(connectionString);
const parsed = new URL(safeUrl);
const existingOptions = parsed.searchParams
.getAll('options')
.map(value => value.trim())
.filter(value => value.length > 0);
parsed.searchParams.delete('options');
const combinedOptions = [...existingOptions, `-c search_path=${schema}`].join(' ');
parsed.searchParams.set('options', combinedOptions);
parsed.searchParams.set('application_name', applicationName);
if (extraParams) {
for (const [k, v] of Object.entries(extraParams)) {
parsed.searchParams.set(k, v);
}
}
return parsed.toString();
}
async function createIsolatedFixture(connectionString: string | undefined = url) {
const safeUrl = assertSafetyDatabaseUrl(connectionString);
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: safeUrl });
cleanup.push(async () => {
await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
await admin.end();
});
cleanup.push(() => admin.end());
await admin.query(`CREATE SCHEMA ${schema}`);
const migrationPool = new Pool(buildIsolatedPoolConfig(safeUrl, schema));
cleanup.push(async () => {
await migrationPool.end();
});
cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined));
const setupPool = new Pool(buildIsolatedPoolConfig(safeUrl, schema));
cleanup.push(() => setupPool.end());
const { rows: schemaRows } = await setupPool.query<{ current_schema: string | null }>(
'SELECT current_schema() AS current_schema'
);
if (schemaRows[0]?.current_schema !== schema) {
throw new Error(
`Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}`
);
}
for (const filename of [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',
'08-create-runs-table.sql',
]) {
await migrationPool.query(readFileSync(`${initDir}${filename}`, 'utf8'));
await setupPool.query(readFileSync(`${initDir}${filename}`, 'utf8'));
}
const postgres = new PostgreSQLClient(
@ -129,38 +145,34 @@ async function createIsolatedFixture(connectionString: string | undefined = url)
);
Object.defineProperty(postgres, 'connectionPool', {
get: () => ({
connect: () => migrationPool.connect(),
connect: () => setupPool.connect(),
}),
});
await runPostgresMigrations(postgres, { track: 'research' });
return { admin, migrationPool, safeUrl, schema };
return { admin, setupPool, schema, safeUrl };
}
async function waitForZeroBackends(
admin: Pool,
appName: string,
timeoutMs = 3000
): Promise<number> {
const deadline = Date.now() + timeoutMs;
let lastCount = -1;
async function waitForZeroBackends(admin: Pool, applicationName: string): Promise<number> {
const deadline = Date.now() + 2_000;
let count = -1;
while (Date.now() < deadline) {
const { rows } = await admin.query<{ count: string }>(
'SELECT count(*)::text AS count FROM pg_stat_activity WHERE application_name = $1',
[appName]
const { rows } = await admin.query<{ c: number }>(
'SELECT count(*)::int AS c FROM pg_stat_activity WHERE application_name = $1',
[applicationName]
);
lastCount = Number(rows[0]?.count ?? '0');
if (lastCount === 0) {
count = rows[0]?.c ?? -1;
if (count === 0) {
return 0;
}
await new Promise(resolve => setTimeout(resolve, 25));
}
return lastCount;
return count;
}
describe('PostgreSQL MCP copilot executor safety guard', () => {
test('rejects unsafe database targets before connecting', () => {
test('rejects missing or non-safety database URLs', () => {
expect(() => assertSafetyDatabaseUrl(undefined)).toThrow(
'Dedicated stock_bot_safety database required'
);
@ -170,212 +182,223 @@ describe('PostgreSQL MCP copilot executor safety guard', () => {
expect(() =>
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev')
).toThrow('Dedicated stock_bot_safety database required');
expect(
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test')
).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test');
});
});
describe.skipIf(!url)('PostgreSQL MCP copilot executor integration', () => {
test('enforces effective 10s statement_timeout, 2s lock_timeout, preserved search_path, max 4 backends, and 0 backends after close', async () => {
describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () => {
test('enforces effective 10s statement_timeout and 2s lock_timeout even when URL specifies overrides', async () => {
const f = await createIsolatedFixture();
const appName = `copilot_exec_${randomUUID().replaceAll('-', '').slice(0, 12)}`;
const postgresUrl = buildSchemaUrl(f.safeUrl, f.schema, { application_name: appName });
const appName = `copilot_timeouts_${randomUUID().slice(0, 8)}`;
const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName, {
statement_timeout: '99999',
lock_timeout: '99999',
query_timeout: '99999',
});
const handle = await openResearchCopilotExecutor(
{ postgresUrl, postgresSchema: f.schema },
{ env: {} }
);
const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl });
cleanup.push(() => handle.close());
const settings = await handle.executor.query<{
statement_timeout: string;
lock_timeout: string;
search_path: string;
current_schema: string;
}>(
`SELECT
current_setting('statement_timeout') AS statement_timeout,
current_setting('lock_timeout') AS lock_timeout,
current_setting('search_path') AS search_path,
current_schema() AS current_schema`
const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>(
'SHOW statement_timeout'
);
const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>(
'SHOW lock_timeout'
);
expect(settings.rows[0]?.statement_timeout).toBe('10s');
expect(settings.rows[0]?.lock_timeout).toBe('2s');
expect(settings.rows[0]?.current_schema).toBe(f.schema);
expect(settings.rows[0]?.search_path).toContain(f.schema);
// Run 8 concurrent queries and observe peak backend count <= 4.
const sleeps = Array.from({ length: 8 }, () =>
handle.executor.query('SELECT pg_sleep(0.08)')
);
await new Promise(resolve => setTimeout(resolve, 30));
const active = await f.admin.query<{ count: string }>(
'SELECT count(*)::text AS count FROM pg_stat_activity WHERE application_name = $1',
[appName]
);
const activeCount = Number(active.rows[0]?.count ?? '0');
expect(activeCount).toBeGreaterThanOrEqual(1);
expect(activeCount).toBeLessThanOrEqual(RESEARCH_COPILOT_PG_POOL_MAX);
await Promise.all(sleeps);
await handle.close();
// Idempotent second close.
await handle.close();
// Post-close query rejects immediately with EXECUTOR_CLOSED.
let closedErr: unknown;
try {
await handle.executor.query('SELECT 1');
} catch (error) {
closedErr = error;
}
expect(closedErr).toBeInstanceOf(ResearchCopilotExecutorError);
expect((closedErr as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED');
const remaining = await waitForZeroBackends(f.admin, appName);
expect(remaining).toBe(0);
expect(stmtRows[0]?.statement_timeout).toBe('10s');
expect(lockRows[0]?.lock_timeout).toBe('2s');
});
test('preserves PGOPTIONS search_path while overriding weakening timeouts', async () => {
test('preserves PGOPTIONS search_path when URL omits options while enforcing 10s/2s timeouts', async () => {
const f = await createIsolatedFixture();
const appName = `copilot_pgoptions_${randomUUID().slice(0, 8)}`;
// Build a URL with NO options query parameter so pg must honor PGOPTIONS.
const parsed = new URL(f.safeUrl);
parsed.searchParams.delete('options');
parsed.searchParams.set('application_name', appName);
const handle = await openResearchCopilotExecutor(
{ postgresUrl: parsed.toString(), postgresSchema: f.schema },
{ env: { PGOPTIONS: `-c search_path=${f.schema} -c statement_timeout=0 -c lock_timeout=0` } }
);
const previousPgOptions = process.env.PGOPTIONS;
process.env.PGOPTIONS = `-c search_path=${f.schema} -c statement_timeout=99999 -c lock_timeout=88888`;
cleanup.push(() => {
if (previousPgOptions === undefined) {
delete process.env.PGOPTIONS;
} else {
process.env.PGOPTIONS = previousPgOptions;
}
});
const handle = await openResearchCopilotExecutor({ postgresUrl: parsed.toString() });
cleanup.push(() => handle.close());
const settings = await handle.executor.query<{
statement_timeout: string;
lock_timeout: string;
current_schema: string;
}>(
`SELECT
current_setting('statement_timeout') AS statement_timeout,
current_setting('lock_timeout') AS lock_timeout,
current_schema() AS current_schema`
const { rows: schemaRows } = await handle.executor.query<{ current_schema: string | null }>(
'SELECT current_schema() AS current_schema'
);
const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>(
'SHOW statement_timeout'
);
const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>(
'SHOW lock_timeout'
);
expect(settings.rows[0]?.statement_timeout).toBe('10s');
expect(settings.rows[0]?.lock_timeout).toBe('2s');
expect(settings.rows[0]?.current_schema).toBe(f.schema);
expect(schemaRows[0]?.current_schema).toBe(f.schema);
expect(stmtRows[0]?.statement_timeout).toBe('10s');
expect(lockRows[0]?.lock_timeout).toBe('2s');
await handle.close();
// Verify unqualified findings writes and reads resolve against the PGOPTIONS search_path.
const writePort = createPostgresFindingWritePort({ executor: handle.executor });
const readers = createPostgresKnowledgeReaders({ executor: handle.executor });
const created = await writePort.appendFinding(
{
id: 'finding-pgoptions-0001',
kind: 'finding',
title: 'PGOPTIONS search_path finding',
summary: 'Resolved via PGOPTIONS search_path without explicit schema option.',
status: 'pending_review',
createdAt: FIXED_TS,
trialRefs: [],
evidenceRefs: [],
},
'idem-pgoptions-0001'
);
expect(created.status).toBe('created');
const listed = await readers.listFindings({ query: 'PGOPTIONS search_path' });
expect(listed).toHaveLength(1);
expect(listed[0]?.id).toBe('finding-pgoptions-0001');
});
test('supports idempotent finding replay (same-ID and same-key) and Vault-fenced trial visibility in migrated schema', async () => {
test('supports migrated findings writes, reads, idempotent replay, and real 23505 preservation', async () => {
const f = await createIsolatedFixture();
const postgresUrl = buildSchemaUrl(f.safeUrl, f.schema);
const appName = `copilot_findings_${randomUUID().slice(0, 8)}`;
const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName);
// Seed one trial strictly before the 2025-06-30 UTC Vault cutoff and one on the cutoff.
await f.migrationPool.query(
const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl });
cleanup.push(() => handle.close());
const writePort = createPostgresFindingWritePort({
executor: handle.executor,
schema: f.schema,
});
const readers = createPostgresKnowledgeReaders({
executor: handle.executor,
schema: f.schema,
});
const record = {
id: 'finding-exec-0001',
kind: 'finding' as const,
title: 'Executor integration finding',
summary: 'Verified against migrated schema via openResearchCopilotExecutor.',
status: 'pending_review' as const,
createdAt: FIXED_TS,
trialRefs: ['101'],
evidenceRefs: ['snap:2025-06-29:ic'],
};
const first = await writePort.appendFinding(record, 'idem-key-0001');
expect(first).toEqual({
status: 'created',
id: 'finding-exec-0001',
createdAt: FIXED_TS,
});
// Same-ID, same-key replay must return the original finding and timestamp.
const replay = await writePort.appendFinding(record, 'idem-key-0001');
expect(replay).toEqual({
status: 'replayed',
id: 'finding-exec-0001',
createdAt: FIXED_TS,
});
// Unkeyed duplicate-PK insert hits PostgreSQL's primary-key constraint directly;
// verify the executor preserves SQLSTATE 23505 without leaking driver fields.
let pkCollisionErr: unknown;
try {
await writePort.appendFinding(record);
} catch (err) {
pkCollisionErr = err;
}
expect(pkCollisionErr).toBeInstanceOf(ResearchCopilotExecutorError);
expect((pkCollisionErr as ResearchCopilotExecutorError).code).toBe('23505');
expect('cause' in (pkCollisionErr as object)).toBe(false);
expect('detail' in (pkCollisionErr as object)).toBe(false);
const listed = await readers.listFindings({ query: 'Executor integration' });
expect(listed).toHaveLength(1);
expect(listed[0]?.id).toBe('finding-exec-0001');
expect(listed[0]?.trialRefs).toEqual(['101']);
// Executor remains usable after 23505 collision.
const { rows } = await handle.executor.query<{ count: number }>(
`SELECT count(*)::int AS count FROM "${f.schema}".findings`
);
expect(rows[0]?.count).toBe(1);
});
test('enforces Vault cutoff when wired into createPostgresTrialRefLookupPort', async () => {
const f = await createIsolatedFixture();
await f.setupPool.query(
`INSERT INTO trial_ledger (
trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash,
sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series
)
OVERRIDING SYSTEM VALUE
VALUES
(1, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64),
'2020-01-01'::date, '2025-06-29'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[]),
(2, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('b', 64),
'2020-01-01'::date, '2025-06-30'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`
(1, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-29'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[]),
(2, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-30'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`
);
const handle = await openResearchCopilotExecutor(
{ postgresUrl, postgresSchema: f.schema },
{ env: {} }
);
const appName = `copilot_vault_${randomUUID().slice(0, 8)}`;
const handle = await openResearchCopilotExecutor({
postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName),
});
cleanup.push(() => handle.close());
// 1. Vault-fenced trial_ledger visibility check.
const trialLookup = createPostgresTrialRefLookupPort({
executor: handle.executor,
schema: f.schema,
vaultCutoffTs: VAULT_CUTOFF_TS,
schema: f.schema,
});
expect(await trialLookup.hasResearchVisibleTrial('1')).toBe(true);
expect(await trialLookup.hasResearchVisibleTrial('2')).toBe(false);
});
// 2. Findings idempotent replay (both same-key ON CONFLICT and same-ID 23505 paths).
const writePort = createPostgresFindingWritePort({
executor: handle.executor,
schema: f.schema,
test('caps concurrent backend connections at 4 and disconnects all backends on close()', async () => {
const f = await createIsolatedFixture();
const appName = `copilot_cap_${randomUUID().slice(0, 8)}`;
const handle = await openResearchCopilotExecutor({
postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName),
});
cleanup.push(() => handle.close());
const findingId = `finding-${randomUUID()}`;
const idempotencyKey = `key-${randomUUID()}`;
const baseFinding: FiledFindingRecord = {
id: findingId,
kind: 'finding',
title: 'Executor replay verification finding',
status: 'pending_review',
createdAt: FIXED_TS,
summary: 'Verifies SQLSTATE 23505 and ON CONFLICT replay through openResearchCopilotExecutor.',
trialRefs: ['1'],
evidenceRefs: ['evidence:e1'],
};
const first = await writePort.appendFinding(baseFinding, idempotencyKey);
expect(first).toEqual({
status: 'created',
id: findingId,
createdAt: FIXED_TS,
});
// Same-key replay with a different ID and later timestamp (ON CONFLICT DO NOTHING path)
// must return the original finding and timestamp.
const sameKeyReplay = await writePort.appendFinding(
{
...baseFinding,
id: `finding-${randomUUID()}`,
createdAt: '2026-02-01T00:00:00.000Z',
},
idempotencyKey
const results = await Promise.all(
Array.from({ length: RESEARCH_COPILOT_PG_POOL_MAX + 2 }, () =>
handle.executor.query<{ pid: number }>(
'SELECT pg_backend_pid() AS pid FROM pg_sleep(0.15)'
)
)
);
expect(sameKeyReplay).toEqual({
status: 'replayed',
id: findingId,
createdAt: FIXED_TS,
});
// Same-ID, same-key replay must also return the original receipt and keep 1 stored row.
const sameIdReplay = await writePort.appendFinding(
{
...baseFinding,
createdAt: '2026-03-01T00:00:00.000Z',
},
idempotencyKey
);
expect(sameIdReplay).toEqual({
status: 'replayed',
id: findingId,
createdAt: FIXED_TS,
});
// Unkeyed duplicate-PK insert hits PostgreSQL's primary-key constraint directly;
// verify the executor observes and preserves real SQLSTATE 23505 without leaking driver fields.
let pkCollisionErr: unknown;
try {
await writePort.appendFinding({
...baseFinding,
createdAt: '2026-04-01T00:00:00.000Z',
});
} catch (error) {
pkCollisionErr = error;
}
expect(pkCollisionErr).toBeInstanceOf(Error);
expect((pkCollisionErr as { code?: string }).code).toBe('23505');
expect((pkCollisionErr as Error).message).toBe('PostgreSQL research copilot query failed.');
expect('cause' in (pkCollisionErr as Error)).toBe(false);
expect('detail' in (pkCollisionErr as Error)).toBe(false);
const rowCount = await handle.executor.query<{ count: string }>(
`SELECT count(*)::text AS count FROM ${f.schema}.findings`
);
expect(rowCount.rows[0]?.count).toBe('1');
const distinctPids = new Set(results.map(r => r.rows[0]?.pid));
expect(distinctPids.size).toBeGreaterThanOrEqual(1);
expect(distinctPids.size).toBeLessThanOrEqual(RESEARCH_COPILOT_PG_POOL_MAX);
await handle.close();
const remainingBackends = await waitForZeroBackends(f.admin, appName);
expect(remainingBackends).toBe(0);
let caught: unknown;
try {
await handle.executor.query('SELECT 1');
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED');
});
});