T-158: M2.1k — PostgreSQL security-master adapter for the MCP copilot search_symbols tool: SymbolSearchPort over an injected executor in libs/research/src/mcp/adapters/postgres-symbol-search.ts (as-of-cutoff ticker resolution, parameterized SQL, no new deps)
This commit is contained in:
parent
a44815fa87
commit
4e4be190df
5 changed files with 1224 additions and 0 deletions
|
|
@ -256,6 +256,14 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
|
|||
- **Review status & Vault safety:** Server-controlled metadata (`id`, UTC ISO `createdAt`, and initial `status: 'pending_review'`) cannot be supplied by callers; director approval occurs out-of-band. Every unique `trialRef` is verified via the injected read-only `trialLookup.hasResearchVisibleTrial(ref)` before generating metadata or writing (treating unknown and Vault-only refs identically). Callers must describe research-visible evidence only in `title` and `summary` and keep Vault holdout observations out of filing text.
|
||||
- **Idempotency & receipts:** `FindingWritePort` exposes only `appendFinding(record, idempotencyKey?)` with atomic `created` / `replayed` / `conflict` semantics comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs`. Retries with the same key and normalized payload return the original `{ id, createdAt, created: false }` without appending; key reuse with a different payload returns a fixed `isError: true` conflict error with zero writes; unkeyed calls are independent. Filed records extend `FindingRecord` and can be read back by receipt ID via `read_knowledge`.
|
||||
|
||||
### PostgreSQL Symbol Search Adapter
|
||||
|
||||
- **`createPostgresSymbolSearchPort({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `SymbolSearchExecutor` and `PostgresSymbolSearchError`) implements `SymbolSearchPort` over the M1 PostgreSQL security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`) in one read-only parameterized `SELECT` with zero runtime `pg` dependency.
|
||||
- **Inputs & schema:** Validates that `executor` exposes a callable `query(text, params?)` method (`INVALID_EXECUTOR`), validates optional `schema` against `^[a-z_][a-z0-9_]*$` before quoting table identifiers (`INVALID_SCHEMA`; defaults to the executor's `search_path`), validates `q.vaultCutoffTs` (epoch milliseconds) and converts it to a UTC calendar date (`YYYY-MM-DD`), escapes `%`, `_`, and `\` before building the `ILIKE` pattern, and rejects malformed/non-integer IDs or invalid/impossible `YYYY-MM-DD` dates returned by the executor (`INVALID_ROW`).
|
||||
- **As-of ticker resolution & root suppression:** Excludes listings with `listed_from > cutoff` (retaining `listed_from IS NULL`). Defines `root_is_future` per listing when `listing_symbol_history` has at least one row with `upper(ticker) = upper(listing.ticker_root)` and none with `valid_from <= cutoff`. Resolves one ticker per listing (breaking same-`valid_from` ties by `ticker ASC`) in strict order: (1) latest history row valid at cutoff (`valid_from <= cutoff AND (valid_to IS NULL OR valid_to >= cutoff)`), (2) `listing.ticker_root` when `NOT root_is_future`, (3) latest history row with `valid_from <= cutoff` even if its `valid_to < cutoff`, (4) otherwise excludes the listing so future tickers never leak via fallback or name/ISIN lookup.
|
||||
- **`delistedAt` derivation:** Projects `delistedAt` as `listing.listed_to` (`YYYY-MM-DD`) when `delist_reason IS NOT NULL AND delist_reason <> 'active'`, else `null`. When `q.includeDelisted === false`, rows with non-null `delistedAt <= cutoff` are filtered out while future delistings (`delistedAt > cutoff`) remain eligible as of the cutoff.
|
||||
- **Port matching vs. MCP ranking:** The adapter matches on resolved as-of ticker (`ILIKE`), `listing.ticker_root` (`ILIKE`, gated by `NOT root_is_future`), `instrument.canonical_name` (`ILIKE`), or case-insensitive exact `instrument.primary_isin`, ignores `q.limit`, and returns all candidates ordered by `listing_id ASC`. When composed with `createSearchSymbolsTool`, the MCP tool applies Vault clamping/masking, ranks by exact ticker > ticker prefix > company name substring (tie-breaking by `listingId ASC`), and truncates to `limit` — so callers needing ticker-substring, root-only, or exact-ISIN lookups should call the port directly, while MCP tool callers should query by ticker or company name.
|
||||
|
||||
### Copilot Server
|
||||
|
||||
- **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions.
|
||||
|
|
|
|||
355
libs/research/src/mcp/adapters/postgres-symbol-search.ts
Normal file
355
libs/research/src/mcp/adapters/postgres-symbol-search.ts
Normal file
|
|
@ -0,0 +1,355 @@
|
|||
/**
|
||||
* Read-only PostgreSQL security-master adapter implementing {@link SymbolSearchPort}
|
||||
* for the MCP copilot `search_symbols` tool.
|
||||
*
|
||||
* Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is
|
||||
* injected via {@link SymbolSearchExecutor}.
|
||||
*/
|
||||
|
||||
import type { SymbolSearchPort, SymbolSearchQuery, SymbolSearchRow } from '../tools/search-symbols';
|
||||
import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input';
|
||||
|
||||
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
|
||||
const CALENDAR_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
|
||||
/** Error codes thrown by {@link PostgresSymbolSearchError}. */
|
||||
export type PostgresSymbolSearchErrorCode =
|
||||
| 'INVALID_EXECUTOR'
|
||||
| 'INVALID_SCHEMA'
|
||||
| 'INVALID_ROW';
|
||||
|
||||
/** Typed validation error thrown by the PostgreSQL symbol-search adapter. */
|
||||
export class PostgresSymbolSearchError extends RangeError {
|
||||
readonly code: PostgresSymbolSearchErrorCode;
|
||||
|
||||
constructor(code: PostgresSymbolSearchErrorCode, message: string) {
|
||||
super(message);
|
||||
this.name = 'PostgresSymbolSearchError';
|
||||
this.code = code;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module
|
||||
* has no runtime dependency on `pg` and is unit-testable with a fake executor.
|
||||
*/
|
||||
export interface SymbolSearchExecutor {
|
||||
query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }>;
|
||||
}
|
||||
|
||||
/** Factory options for {@link createPostgresSymbolSearchPort}. */
|
||||
export interface PostgresSymbolSearchPortOptions {
|
||||
readonly executor: SymbolSearchExecutor;
|
||||
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
|
||||
readonly schema?: string;
|
||||
}
|
||||
|
||||
interface RawSymbolSearchRow {
|
||||
readonly listing_id: unknown;
|
||||
readonly instrument_id: unknown;
|
||||
readonly ticker: unknown;
|
||||
readonly class_suffix: unknown;
|
||||
readonly name: unknown;
|
||||
readonly mic: unknown;
|
||||
readonly currency: unknown;
|
||||
readonly isin: unknown;
|
||||
readonly first_bar_date: unknown;
|
||||
readonly last_bar_date: unknown;
|
||||
readonly delisted_at: unknown;
|
||||
}
|
||||
|
||||
function isLeapYear(year: number): boolean {
|
||||
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
||||
}
|
||||
|
||||
function daysInUtcMonth(year: number, monthIndex: number): number {
|
||||
if (monthIndex === 1 && isLeapYear(year)) {
|
||||
return 29;
|
||||
}
|
||||
return DAYS_IN_MONTH[monthIndex] ?? 0;
|
||||
}
|
||||
|
||||
function isValidCalendarDate(value: unknown): value is string {
|
||||
if (typeof value !== 'string') {
|
||||
return false;
|
||||
}
|
||||
const match = CALENDAR_DATE_RE.exec(value);
|
||||
if (match === null) {
|
||||
return false;
|
||||
}
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
if (month < 1 || month > 12) {
|
||||
return false;
|
||||
}
|
||||
return day >= 1 && day <= daysInUtcMonth(year, month - 1);
|
||||
}
|
||||
|
||||
function escapeLikePattern(value: string): string {
|
||||
return value.replace(/[\\%_]/g, '\\$&');
|
||||
}
|
||||
|
||||
function quoteTable(schemaPrefix: string, table: string): string {
|
||||
return `${schemaPrefix}${table}`;
|
||||
}
|
||||
|
||||
function buildSearchSymbolsSql(schemaPrefix: string): string {
|
||||
const listingTable = quoteTable(schemaPrefix, 'listing');
|
||||
const instrumentTable = quoteTable(schemaPrefix, 'instrument');
|
||||
const exchangeTable = quoteTable(schemaPrefix, 'exchange');
|
||||
const historyTable = quoteTable(schemaPrefix, 'listing_symbol_history');
|
||||
|
||||
return [
|
||||
'SELECT',
|
||||
' l.listing_id AS listing_id,',
|
||||
' l.instrument_id AS instrument_id,',
|
||||
' resolved.ticker AS ticker,',
|
||||
" NULLIF(l.class_suffix, '') AS class_suffix,",
|
||||
' i.canonical_name AS name,',
|
||||
' l.mic AS mic,',
|
||||
' btrim(l.currency) AS currency,',
|
||||
" NULLIF(btrim(i.primary_isin), '') AS isin,",
|
||||
" to_char(l.listed_from, 'YYYY-MM-DD') AS first_bar_date,",
|
||||
" to_char(l.listed_to, 'YYYY-MM-DD') AS last_bar_date,",
|
||||
" to_char(delisted.delisted_at, 'YYYY-MM-DD') AS delisted_at",
|
||||
`FROM ${listingTable} l`,
|
||||
`INNER JOIN ${instrumentTable} i ON i.instrument_id = l.instrument_id`,
|
||||
`INNER JOIN ${exchangeTable} e ON e.mic = l.mic`,
|
||||
'CROSS JOIN LATERAL (',
|
||||
' SELECT (',
|
||||
' EXISTS (',
|
||||
' SELECT 1',
|
||||
` FROM ${historyTable} h_any`,
|
||||
' WHERE h_any.listing_id = l.listing_id',
|
||||
' AND upper(h_any.ticker) = upper(l.ticker_root)',
|
||||
' )',
|
||||
' AND NOT EXISTS (',
|
||||
' SELECT 1',
|
||||
` FROM ${historyTable} h_past`,
|
||||
' WHERE h_past.listing_id = l.listing_id',
|
||||
' AND upper(h_past.ticker) = upper(l.ticker_root)',
|
||||
' AND h_past.valid_from <= $1::date',
|
||||
' )',
|
||||
' ) AS is_future',
|
||||
') root_state',
|
||||
'LEFT JOIN LATERAL (',
|
||||
' SELECT h.ticker',
|
||||
` FROM ${historyTable} h`,
|
||||
' WHERE h.listing_id = l.listing_id',
|
||||
' AND h.valid_from <= $1::date',
|
||||
' AND (h.valid_to IS NULL OR h.valid_to >= $1::date)',
|
||||
' ORDER BY h.valid_from DESC, h.ticker ASC',
|
||||
' LIMIT 1',
|
||||
') hist_active ON TRUE',
|
||||
'LEFT JOIN LATERAL (',
|
||||
' SELECT h.ticker',
|
||||
` FROM ${historyTable} h`,
|
||||
' WHERE h.listing_id = l.listing_id',
|
||||
' AND h.valid_from <= $1::date',
|
||||
' ORDER BY h.valid_from DESC, h.ticker ASC',
|
||||
' LIMIT 1',
|
||||
') hist_prior ON TRUE',
|
||||
'CROSS JOIN LATERAL (',
|
||||
' SELECT CASE',
|
||||
' WHEN hist_active.ticker IS NOT NULL THEN hist_active.ticker',
|
||||
' WHEN NOT root_state.is_future THEN l.ticker_root',
|
||||
' ELSE hist_prior.ticker',
|
||||
' END AS ticker',
|
||||
') resolved',
|
||||
'CROSS JOIN LATERAL (',
|
||||
' SELECT CASE',
|
||||
" WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to",
|
||||
' ELSE NULL',
|
||||
' END AS delisted_at',
|
||||
') delisted',
|
||||
'WHERE (l.listed_from IS NULL OR l.listed_from <= $1::date)',
|
||||
' AND resolved.ticker IS NOT NULL',
|
||||
" AND resolved.ticker <> ''",
|
||||
' AND ($4::text IS NULL OR btrim(e.country_iso) = $4::text)',
|
||||
' AND ($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)',
|
||||
' AND (',
|
||||
" resolved.ticker ILIKE $2::text ESCAPE '\\'",
|
||||
" OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')",
|
||||
" OR i.canonical_name ILIKE $2::text ESCAPE '\\'",
|
||||
' OR (i.primary_isin IS NOT NULL AND upper(btrim(i.primary_isin)) = upper($3::text))',
|
||||
' )',
|
||||
'ORDER BY l.listing_id ASC',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function parseSafeInt(value: unknown, field: string): number {
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
`Invalid security-master row: "${field}" must be a safe integer.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseNonEmptyString(value: unknown, field: string): string {
|
||||
if (typeof value !== 'string' || value.trim().length === 0) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
`Invalid security-master row: "${field}" must be a non-empty string.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseNullableClassSuffix(value: unknown): string | null {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value !== 'string') {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
'Invalid security-master row: "class_suffix" must be a string or null.'
|
||||
);
|
||||
}
|
||||
return value === '' ? null : value;
|
||||
}
|
||||
|
||||
function parseNullableIsin(value: unknown): string | null {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value !== 'string') {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
'Invalid security-master row: "isin" must be a string or null.'
|
||||
);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed === '' ? null : trimmed;
|
||||
}
|
||||
|
||||
function parseNullableDate(value: unknown, field: string): string | null {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
if (!isValidCalendarDate(value)) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
`Invalid security-master row: "${field}" must be a valid YYYY-MM-DD calendar date or null.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function mapRawRow(raw: unknown): SymbolSearchRow {
|
||||
if (typeof raw !== 'object' || raw === null) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
'Invalid security-master row: expected a non-null object.'
|
||||
);
|
||||
}
|
||||
|
||||
const row = raw as RawSymbolSearchRow;
|
||||
const listingId = parseSafeInt(row.listing_id, 'listing_id');
|
||||
const instrumentId = parseSafeInt(row.instrument_id, 'instrument_id');
|
||||
const ticker = parseNonEmptyString(row.ticker, 'ticker');
|
||||
const classSuffix = parseNullableClassSuffix(row.class_suffix);
|
||||
const name = parseNonEmptyString(row.name, 'name');
|
||||
const mic = parseNonEmptyString(row.mic, 'mic');
|
||||
const currency = parseNonEmptyString(row.currency, 'currency').trim();
|
||||
const isin = parseNullableIsin(row.isin);
|
||||
const firstBarDate = parseNullableDate(row.first_bar_date, 'first_bar_date');
|
||||
const lastBarDate = parseNullableDate(row.last_bar_date, 'last_bar_date');
|
||||
const delistedAt = parseNullableDate(row.delisted_at, 'delisted_at');
|
||||
|
||||
return {
|
||||
listingId,
|
||||
instrumentId,
|
||||
ticker,
|
||||
classSuffix,
|
||||
name,
|
||||
mic,
|
||||
currency,
|
||||
isin,
|
||||
firstBarDate,
|
||||
lastBarDate,
|
||||
delistedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function validateFactoryOptions(options: PostgresSymbolSearchPortOptions): {
|
||||
readonly executor: SymbolSearchExecutor;
|
||||
readonly schemaPrefix: string;
|
||||
} {
|
||||
if (typeof options !== 'object' || options === null) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_EXECUTOR',
|
||||
'Invalid options: expected an object with a SymbolSearchExecutor.'
|
||||
);
|
||||
}
|
||||
|
||||
const { executor, schema } = options;
|
||||
if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_EXECUTOR',
|
||||
'Invalid executor: expected an object with a callable query(text, params?) method.'
|
||||
);
|
||||
}
|
||||
|
||||
if (schema === undefined) {
|
||||
return { executor, schemaPrefix: '' };
|
||||
}
|
||||
|
||||
if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_SCHEMA',
|
||||
'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.'
|
||||
);
|
||||
}
|
||||
|
||||
return { executor, schemaPrefix: `"${schema}".` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a read-only PostgreSQL {@link SymbolSearchPort} backed by the M1
|
||||
* security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`).
|
||||
*/
|
||||
export function createPostgresSymbolSearchPort(
|
||||
options: PostgresSymbolSearchPortOptions
|
||||
): SymbolSearchPort {
|
||||
const { executor, schemaPrefix } = validateFactoryOptions(options);
|
||||
const sql = buildSearchSymbolsSql(schemaPrefix);
|
||||
|
||||
return {
|
||||
async searchSymbols(q: SymbolSearchQuery): Promise<readonly SymbolSearchRow[]> {
|
||||
const cutoffTs = validateVaultCutoffTs(q.vaultCutoffTs);
|
||||
const cutoffDate = utcDateOf(cutoffTs);
|
||||
const ilikePattern = `%${escapeLikePattern(q.query)}%`;
|
||||
const country = q.country ?? null;
|
||||
const includeDelisted = q.includeDelisted;
|
||||
|
||||
const result = await executor.query<RawSymbolSearchRow>(sql, [
|
||||
cutoffDate,
|
||||
ilikePattern,
|
||||
q.query,
|
||||
country,
|
||||
includeDelisted,
|
||||
]);
|
||||
|
||||
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
'Invalid executor response: expected an object with a rows array.'
|
||||
);
|
||||
}
|
||||
|
||||
const mapped: SymbolSearchRow[] = [];
|
||||
for (let i = 0; i < result.rows.length; i += 1) {
|
||||
mapped.push(mapRawRow(result.rows[i]));
|
||||
}
|
||||
return mapped;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
export * from './adapters/postgres-symbol-search';
|
||||
export * from './copilot-server';
|
||||
export * from './protocol';
|
||||
export * from './server';
|
||||
|
|
|
|||
413
libs/research/test/mcp-postgres-symbol-search.test.ts
Normal file
413
libs/research/test/mcp-postgres-symbol-search.test.ts
Normal file
|
|
@ -0,0 +1,413 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { MarketDataStoreValidationError } from '../src/market-data-store';
|
||||
import {
|
||||
PostgresSymbolSearchError,
|
||||
type SymbolSearchExecutor,
|
||||
type SymbolSearchQuery,
|
||||
createPostgresSymbolSearchPort,
|
||||
} from '../src/mcp/index';
|
||||
|
||||
interface RecordedCall {
|
||||
readonly text: string;
|
||||
readonly params: readonly unknown[] | undefined;
|
||||
}
|
||||
|
||||
function createFakeExecutor(rows: readonly Record<string, unknown>[] = []): {
|
||||
readonly calls: RecordedCall[];
|
||||
readonly executor: SymbolSearchExecutor;
|
||||
} {
|
||||
const calls: RecordedCall[] = [];
|
||||
const executor: SymbolSearchExecutor = {
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }> {
|
||||
calls.push({ text, params });
|
||||
return { rows: rows as readonly Row[] };
|
||||
},
|
||||
};
|
||||
return { calls, executor };
|
||||
}
|
||||
|
||||
function makeRawRow(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
listing_id: 101,
|
||||
instrument_id: 1001,
|
||||
ticker: 'ACME',
|
||||
class_suffix: '',
|
||||
name: 'Acme Corporation',
|
||||
mic: 'XNAS',
|
||||
currency: 'USD',
|
||||
isin: 'US0000001015',
|
||||
first_bar_date: '2018-01-02',
|
||||
last_bar_date: '2024-06-28',
|
||||
delisted_at: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const BASE_QUERY: SymbolSearchQuery = {
|
||||
query: 'ACME',
|
||||
limit: 20,
|
||||
includeDelisted: true,
|
||||
vaultCutoffTs: Date.UTC(2024, 5, 30, 0, 0, 0, 0), // 2024-06-30T00:00:00.000Z
|
||||
};
|
||||
|
||||
describe('createPostgresSymbolSearchPort (fake executor)', () => {
|
||||
test('issues a single parameterized SELECT and never interpolates injection-shaped queries', async () => {
|
||||
const injection = "'; DROP TABLE listing; --";
|
||||
const fake = createFakeExecutor([makeRawRow()]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
query: injection,
|
||||
});
|
||||
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
const call = fake.calls[0]!;
|
||||
expect(call.text.trimStart().startsWith('SELECT')).toBe(true);
|
||||
expect(call.text).not.toContain(';');
|
||||
expect(call.text).not.toContain(injection);
|
||||
expect(call.text).not.toContain('DROP TABLE');
|
||||
expect(call.params).toEqual([
|
||||
'2024-06-30',
|
||||
`%${injection}%`,
|
||||
injection,
|
||||
null,
|
||||
true,
|
||||
]);
|
||||
});
|
||||
|
||||
test('escapes %, _, and backslash literals in the ILIKE pattern while preserving raw query for ISIN', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
query: 'A%B_C\\D',
|
||||
});
|
||||
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
const call = fake.calls[0]!;
|
||||
expect(call.text).toContain("ESCAPE '\\'");
|
||||
expect(call.params).toEqual([
|
||||
'2024-06-30',
|
||||
'%A\\%B\\_C\\\\D%',
|
||||
'A%B_C\\D',
|
||||
null,
|
||||
true,
|
||||
]);
|
||||
});
|
||||
|
||||
test('converts vaultCutoffTs epoch-ms to UTC calendar date across midnight boundaries', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
vaultCutoffTs: Date.UTC(2024, 5, 30, 23, 59, 59, 999),
|
||||
});
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0),
|
||||
});
|
||||
|
||||
expect(fake.calls).toHaveLength(2);
|
||||
expect(fake.calls[0]!.params?.[0]).toBe('2024-06-30');
|
||||
expect(fake.calls[1]!.params?.[0]).toBe('2024-07-01');
|
||||
});
|
||||
|
||||
test('binds optional country filter and both includeDelisted flags', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
country: 'CA',
|
||||
includeDelisted: false,
|
||||
});
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
country: 'US',
|
||||
includeDelisted: true,
|
||||
});
|
||||
|
||||
expect(fake.calls).toHaveLength(2);
|
||||
expect(fake.calls[0]!.params?.[3]).toBe('CA');
|
||||
expect(fake.calls[0]!.params?.[4]).toBe(false);
|
||||
expect(fake.calls[1]!.params?.[3]).toBe('US');
|
||||
expect(fake.calls[1]!.params?.[4]).toBe(true);
|
||||
});
|
||||
|
||||
test('ignores q.limit in SQL and returns all candidates without truncation', async () => {
|
||||
const rows = [
|
||||
makeRawRow({ listing_id: 1, instrument_id: 10, ticker: 'AA' }),
|
||||
makeRawRow({ listing_id: 2, instrument_id: 20, ticker: 'AAB' }),
|
||||
makeRawRow({ listing_id: 3, instrument_id: 30, ticker: 'AAC' }),
|
||||
];
|
||||
const fake = createFakeExecutor(rows);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
const r1 = await port.searchSymbols({ ...BASE_QUERY, limit: 1 });
|
||||
const r2 = await port.searchSymbols({ ...BASE_QUERY, limit: 100 });
|
||||
|
||||
expect(r1).toHaveLength(3);
|
||||
expect(r2).toHaveLength(3);
|
||||
expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text);
|
||||
expect(fake.calls[0]!.params).toEqual(fake.calls[1]!.params);
|
||||
// Outer query has ORDER BY listing_id ASC with no outer LIMIT clause
|
||||
expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY l.listing_id ASC')).toBe(true);
|
||||
});
|
||||
|
||||
test('gates ticker_root fallback and matching on cutoff-aware history suppression and derives delisted_at', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await port.searchSymbols(BASE_QUERY);
|
||||
|
||||
const sql = fake.calls[0]!.text;
|
||||
// Root-suppression subquery checks upper(ticker) = upper(ticker_root) and cutoff $1::date
|
||||
expect(sql).toContain('upper(h_any.ticker) = upper(l.ticker_root)');
|
||||
expect(sql).toContain('upper(h_past.ticker) = upper(l.ticker_root)');
|
||||
expect(sql).toContain('h_past.valid_from <= $1::date');
|
||||
// Both fallback resolution and root ILIKE predicate are gated by NOT root_state.is_future
|
||||
expect(sql).toContain('WHEN NOT root_state.is_future THEN l.ticker_root');
|
||||
expect(sql).toContain("OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')");
|
||||
// delisted_at derivation and $5 filter
|
||||
expect(sql).toContain("WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to");
|
||||
expect(sql).toContain('($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)');
|
||||
});
|
||||
|
||||
test('quotes optional validated schema on all security-master tables and omits prefix when unset', async () => {
|
||||
const fakeDefault = createFakeExecutor([]);
|
||||
const defaultPort = createPostgresSymbolSearchPort({ executor: fakeDefault.executor });
|
||||
await defaultPort.searchSymbols(BASE_QUERY);
|
||||
expect(fakeDefault.calls[0]!.text).toContain('FROM listing l');
|
||||
expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN instrument i');
|
||||
expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN exchange e');
|
||||
expect(fakeDefault.calls[0]!.text).toContain('FROM listing_symbol_history');
|
||||
|
||||
const fakeScoped = createFakeExecutor([]);
|
||||
const scopedPort = createPostgresSymbolSearchPort({
|
||||
executor: fakeScoped.executor,
|
||||
schema: 'custom_master_1',
|
||||
});
|
||||
await scopedPort.searchSymbols(BASE_QUERY);
|
||||
expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing l');
|
||||
expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".instrument i');
|
||||
expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".exchange e');
|
||||
expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing_symbol_history');
|
||||
});
|
||||
|
||||
test('maps raw rows into SymbolSearchRow with classSuffix, ISIN trimming, nullable dates, and delistedAt', async () => {
|
||||
const fake = createFakeExecutor([
|
||||
makeRawRow({
|
||||
listing_id: 101,
|
||||
instrument_id: 501,
|
||||
ticker: 'ACME',
|
||||
class_suffix: '',
|
||||
name: 'Acme Corp',
|
||||
mic: 'XNAS',
|
||||
currency: 'USD ',
|
||||
isin: ' US0000001015 ',
|
||||
first_bar_date: '2020-02-29',
|
||||
last_bar_date: '2024-06-28',
|
||||
delisted_at: null,
|
||||
}),
|
||||
makeRawRow({
|
||||
listing_id: 102,
|
||||
instrument_id: 502,
|
||||
ticker: 'BRK',
|
||||
class_suffix: 'B',
|
||||
name: 'Berkshire Example',
|
||||
mic: 'XNYS',
|
||||
currency: 'USD',
|
||||
isin: ' ',
|
||||
first_bar_date: null,
|
||||
last_bar_date: '2023-12-15',
|
||||
delisted_at: '2023-12-15',
|
||||
}),
|
||||
makeRawRow({
|
||||
listing_id: 103,
|
||||
instrument_id: 503,
|
||||
ticker: 'NULLY',
|
||||
class_suffix: null,
|
||||
name: 'Nullable Fields Co',
|
||||
mic: 'XTSE',
|
||||
currency: 'CAD',
|
||||
isin: null,
|
||||
first_bar_date: null,
|
||||
last_bar_date: null,
|
||||
delisted_at: null,
|
||||
}),
|
||||
]);
|
||||
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
const rows = await port.searchSymbols(BASE_QUERY);
|
||||
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
listingId: 101,
|
||||
instrumentId: 501,
|
||||
ticker: 'ACME',
|
||||
classSuffix: null,
|
||||
name: 'Acme Corp',
|
||||
mic: 'XNAS',
|
||||
currency: 'USD',
|
||||
isin: 'US0000001015',
|
||||
firstBarDate: '2020-02-29',
|
||||
lastBarDate: '2024-06-28',
|
||||
delistedAt: null,
|
||||
},
|
||||
{
|
||||
listingId: 102,
|
||||
instrumentId: 502,
|
||||
ticker: 'BRK',
|
||||
classSuffix: 'B',
|
||||
name: 'Berkshire Example',
|
||||
mic: 'XNYS',
|
||||
currency: 'USD',
|
||||
isin: null,
|
||||
firstBarDate: null,
|
||||
lastBarDate: '2023-12-15',
|
||||
delistedAt: '2023-12-15',
|
||||
},
|
||||
{
|
||||
listingId: 103,
|
||||
instrumentId: 503,
|
||||
ticker: 'NULLY',
|
||||
classSuffix: null,
|
||||
name: 'Nullable Fields Co',
|
||||
mic: 'XTSE',
|
||||
currency: 'CAD',
|
||||
isin: null,
|
||||
firstBarDate: null,
|
||||
lastBarDate: null,
|
||||
delistedAt: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('rejects invalid executors and options with INVALID_EXECUTOR before any query', () => {
|
||||
const invalidOptions: unknown[] = [
|
||||
null,
|
||||
undefined,
|
||||
{},
|
||||
{ executor: null },
|
||||
{ executor: {} },
|
||||
{ executor: { query: 'not-a-fn' } },
|
||||
];
|
||||
|
||||
for (const opts of invalidOptions) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
createPostgresSymbolSearchPort(opts as Parameters<typeof createPostgresSymbolSearchPort>[0]);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(PostgresSymbolSearchError);
|
||||
expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_EXECUTOR');
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects invalid schema names with INVALID_SCHEMA before any query', () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const badSchemas: unknown[] = [
|
||||
'',
|
||||
'Public',
|
||||
'1schema',
|
||||
'bad-name',
|
||||
'bad.name',
|
||||
'public"; DROP TABLE listing; --',
|
||||
'space name',
|
||||
123,
|
||||
null,
|
||||
];
|
||||
|
||||
for (const schema of badSchemas) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
createPostgresSymbolSearchPort({
|
||||
executor: fake.executor,
|
||||
schema: schema as string,
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(PostgresSymbolSearchError);
|
||||
expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_SCHEMA');
|
||||
}
|
||||
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('rejects invalid vaultCutoffTs before executing any query', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await expect(
|
||||
port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Number.NaN })
|
||||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('rejects malformed rows (fractional/unsafe IDs, malformed/impossible dates, invalid types) with INVALID_ROW', async () => {
|
||||
const badRows: readonly Record<string, unknown>[] = [
|
||||
makeRawRow({ listing_id: 1.5 }),
|
||||
makeRawRow({ listing_id: Number.MAX_SAFE_INTEGER + 1 }),
|
||||
makeRawRow({ listing_id: '101' }),
|
||||
makeRawRow({ listing_id: Number.NaN }),
|
||||
makeRawRow({ instrument_id: 2.25 }),
|
||||
makeRawRow({ instrument_id: Number.POSITIVE_INFINITY }),
|
||||
makeRawRow({ ticker: '' }),
|
||||
makeRawRow({ ticker: null }),
|
||||
makeRawRow({ name: '' }),
|
||||
makeRawRow({ mic: null }),
|
||||
makeRawRow({ currency: '' }),
|
||||
makeRawRow({ class_suffix: 42 }),
|
||||
makeRawRow({ isin: 12345 }),
|
||||
makeRawRow({ first_bar_date: '2024-6-1' }),
|
||||
makeRawRow({ first_bar_date: '2023-02-29' }),
|
||||
makeRawRow({ last_bar_date: '2024-02-30' }),
|
||||
makeRawRow({ last_bar_date: '2024-13-01' }),
|
||||
makeRawRow({ delisted_at: '2024-06-30T00:00:00Z' }),
|
||||
makeRawRow({ delisted_at: new Date('2024-06-30T00:00:00Z') }),
|
||||
];
|
||||
|
||||
for (const badRow of badRows) {
|
||||
const fake = createFakeExecutor([badRow]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.searchSymbols(BASE_QUERY);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(PostgresSymbolSearchError);
|
||||
expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_ROW');
|
||||
}
|
||||
|
||||
// Non-object row / invalid result shape
|
||||
const nullRowExecutor: SymbolSearchExecutor = {
|
||||
async query<Row = Record<string, unknown>>() {
|
||||
return { rows: [null as unknown as Row] };
|
||||
},
|
||||
};
|
||||
const portNullRow = createPostgresSymbolSearchPort({ executor: nullRowExecutor });
|
||||
await expect(portNullRow.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf(
|
||||
PostgresSymbolSearchError
|
||||
);
|
||||
|
||||
const badResultExecutor: SymbolSearchExecutor = {
|
||||
async query() {
|
||||
return { rows: 'not-an-array' as unknown as readonly never[] };
|
||||
},
|
||||
};
|
||||
const portBadResult = createPostgresSymbolSearchPort({ executor: badResultExecutor });
|
||||
await expect(portBadResult.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf(
|
||||
PostgresSymbolSearchError
|
||||
);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue