Compare commits

...

23 commits

Author SHA1 Message Date
Studio
17120d7e28 T-159: M2.1l — PostgreSQL trial_ledger adapter for the MCP copilot file_finding tool: TrialRefLookupPort over an injected executor in libs/research/src/mcp/adapters/postgres-trial-ref.ts (research-visible = sample_end before the Vault cutoff date, parameterized SQL, no new deps) 2026-12-02 09:29:52 -05:00
Studio
ae01904cd6 T-159: tests 2026-12-02 09:25:59 -05:00
Studio
d65016c851 T-159: M2.1l — PostgreSQL trial_ledger adapter for the MCP copilot file_finding tool: TrialRefLookupPort over an injected executor in libs/research/src/mcp/adapters/postgres-trial-ref.ts (research-visible = sample_end before the Vault cutoff date, parameterized SQL, no new deps) 2026-12-02 09:16:35 -05:00
Studio
acfd6a92da T-158: tests 2026-12-02 09:16:35 -05:00
Studio
90ab20c301 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) 2026-12-02 09:16:35 -05:00
Studio
b56329de2a 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) 2026-12-02 09:16:35 -05:00
Studio
e86c9f539e T-156: M2.2e — tools/curate-etl: Zstd Parquet writer for fundamentals_pit/year=YYYY/part.parquet (FundamentalsSnapshot<i32> → flat row matching the DuckDB fundamentalsAsOf reader columns) with tests (no new crates, no CLI/bench changes, no live Mongo) 2026-12-02 08:56:50 -05:00
Studio
498b560c85 T-156: merge master 2026-12-02 08:49:42 -05:00
Studio
42d82469a4 T-156: M2.2e — tools/curate-etl: Zstd Parquet writer for fundamentals_pit/year=YYYY/part.parquet (FundamentalsSnapshot<i32> → flat row matching the DuckDB fundamentalsAsOf reader columns) with tests (no new crates, no CLI/bench changes, no live Mongo) 2026-12-02 01:36:18 -05:00
Studio
a8cebf0605 T-152: tests 2026-12-02 00:20:59 -05:00
Studio
5e5b0d1d40 T-152: M2.3j — tools/curate-etl: pure qmIntraday → bars_1m curation stage (raw bars, no split un-adjustment → provider_mapping → Bar1mRow<i32> → IlpShardedWriter) with tests (no new crates, no CLI/bench changes, no live Mongo/QuestDB) 2026-12-02 00:14:04 -05:00
Studio
29b25e3b8e T-149: tests 2026-12-02 00:01:05 -05:00
Studio
e5b97c2324 T-149: M2.1h — MCP copilot analyze_signal: add a Vault-fenced fundamentals signal source (point-in-time fundamentalsAsOf month-end snapshots → SignalObservations) + extend the headless stdio end-to-end test to run a fundamental AND a shorts study (pure, injected ports, no new deps) 2026-12-01 23:51:50 -05:00
Studio
5fc2f74760 T-149: M2.1h — MCP copilot analyze_signal: add a Vault-fenced fundamentals signal source (point-in-time fundamentalsAsOf month-end snapshots → SignalObservations) + extend the headless stdio end-to-end test to run a fundamental AND a shorts study (pure, injected ports, no new deps) 2026-12-01 23:51:50 -05:00
Studio
bec64c5ec6 T-149: M2.1h — MCP copilot analyze_signal: add a Vault-fenced fundamentals signal source (point-in-time fundamentalsAsOf month-end snapshots → SignalObservations) + extend the headless stdio end-to-end test to run a fundamental AND a shorts study (pure, injected ports, no new deps) 2026-12-01 23:51:50 -05:00
Studio
ee6137c770 T-149: M2.1h — MCP copilot analyze_signal: add a Vault-fenced fundamentals signal source (point-in-time fundamentalsAsOf month-end snapshots → SignalObservations) + extend the headless stdio end-to-end test to run a fundamental AND a shorts study (pure, injected ports, no new deps) 2026-12-01 23:51:50 -05:00
Studio
5527cebc21 T-150: tests 2026-12-01 23:44:56 -05:00
Studio
41feb16e5f T-150: M2.3i — tools/curate-etl: zero-copy raw BSON decoder for qmIntraday raw 1m bars (bson_qm_intraday.rs, pure, with tests; no new crates, no CLI/bench changes, no live Mongo/QuestDB) 2026-12-01 23:38:56 -05:00
Studio
60d347dd1b T-146: tests 2026-12-01 22:52:38 -05:00
Studio
2e5cc2e43d T-146: M2.3f — QuestDB bars_1m intraday reader for MarketDataStore.bars (timeframe: '1m'): Vault-fenced, parameterized planBars1mQuery + batch iterator over an injected PGWire query port in libs/research/src/market-data-store-questdb.ts (pure, no new deps, no live QuestDB) 2026-12-01 22:46:56 -05:00
Studio
adf28209c6 T-146: M2.3f — QuestDB bars_1m intraday reader for MarketDataStore.bars (timeframe: '1m'): Vault-fenced, parameterized planBars1mQuery + batch iterator over an injected PGWire query port in libs/research/src/market-data-store-questdb.ts (pure, no new deps, no live QuestDB) 2026-12-01 22:40:36 -05:00
Studio
fb1c32c568 T-145: tests 2026-12-01 22:32:25 -05:00
Studio
279f425835 T-145: M2.2d — fundamentalsAsOf in the DuckDB MarketDataStore: Vault-fenced point-in-time read of fundamentals_pit/year=*/part.parquet with a real-DuckDB restatement fixture test (no new deps) 2026-12-01 22:25:46 -05:00
10 changed files with 2809 additions and 74 deletions

View file

@ -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.

View 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;
},
};
}

View file

@ -0,0 +1,150 @@
/**
* Read-only PostgreSQL `trial_ledger` adapter implementing {@link TrialRefLookupPort}
* for the MCP copilot `file_finding` tool.
*
* Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is
* injected via {@link TrialRefExecutor}.
*/
import type { TrialRefLookupPort } from '../tools/file-finding';
import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input';
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
const FOUR_DIGIT_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const CANONICAL_POSITIVE_BIGINT_RE = /^[1-9][0-9]{0,18}$/;
const MAX_SIGNED_BIGINT_STR = '9223372036854775807';
/** Error codes thrown by {@link PostgresTrialRefError}. */
export type PostgresTrialRefErrorCode =
| 'INVALID_EXECUTOR'
| 'INVALID_SCHEMA'
| 'INVALID_VAULT_CUTOFF';
/** Typed validation error thrown by the PostgreSQL trial-ref lookup adapter. */
export class PostgresTrialRefError extends RangeError {
readonly code: PostgresTrialRefErrorCode;
constructor(code: PostgresTrialRefErrorCode, message: string) {
super(message);
this.name = 'PostgresTrialRefError';
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 TrialRefExecutor {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }>;
}
/** Factory options for {@link createPostgresTrialRefLookupPort}. */
export interface PostgresTrialRefLookupPortOptions {
readonly executor: TrialRefExecutor;
/** Authoritative UTC epoch-ms Vault cutoff; trials with `sample_end < cutoffDate` are research-visible. */
readonly vaultCutoffTs: number;
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
readonly schema?: string;
}
interface TrialVisibilityRow {
readonly visible?: unknown;
}
function isCanonicalPositiveBigInt(value: unknown): value is string {
if (typeof value !== 'string' || !CANONICAL_POSITIVE_BIGINT_RE.test(value)) {
return false;
}
if (value.length === MAX_SIGNED_BIGINT_STR.length && value > MAX_SIGNED_BIGINT_STR) {
return false;
}
return true;
}
function buildTrialVisibilitySql(schemaPrefix: string): string {
return `SELECT 1 AS visible FROM ${schemaPrefix}trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1`;
}
function validateFactoryOptions(options: PostgresTrialRefLookupPortOptions): {
readonly executor: TrialRefExecutor;
readonly cutoffDate: string;
readonly schemaPrefix: string;
} {
if (typeof options !== 'object' || options === null) {
throw new PostgresTrialRefError(
'INVALID_EXECUTOR',
'Invalid options: expected an object with a TrialRefExecutor.'
);
}
const { executor, vaultCutoffTs, schema } = options;
if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') {
throw new PostgresTrialRefError(
'INVALID_EXECUTOR',
'Invalid executor: expected an object with a callable query(text, params?) method.'
);
}
let schemaPrefix = '';
if (schema !== undefined) {
if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) {
throw new PostgresTrialRefError(
'INVALID_SCHEMA',
'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.'
);
}
schemaPrefix = `"${schema}".`;
}
let validatedCutoffTs: number;
try {
validatedCutoffTs = validateVaultCutoffTs(vaultCutoffTs);
} catch {
throw new PostgresTrialRefError(
'INVALID_VAULT_CUTOFF',
'Invalid vaultCutoffTs: expected a finite safe-integer epoch-ms timestamp within ECMAScript Date bounds.'
);
}
const cutoffDate = utcDateOf(validatedCutoffTs);
if (!FOUR_DIGIT_DATE_RE.test(cutoffDate) || cutoffDate.startsWith('0000-')) {
throw new PostgresTrialRefError(
'INVALID_VAULT_CUTOFF',
'Invalid vaultCutoffTs: resolved UTC date must be a four-digit PostgreSQL calendar date (0001-01-01 through 9999-12-31).'
);
}
return { executor, cutoffDate, schemaPrefix };
}
/**
* Creates a read-only PostgreSQL {@link TrialRefLookupPort} backed by `trial_ledger`.
*
* Only trials with `sample_end < cutoffDate` (exclusive UTC Vault cutoff date) are
* research-visible. Unknown, malformed, and Vault-only references all return `false`.
*/
export function createPostgresTrialRefLookupPort(
options: PostgresTrialRefLookupPortOptions
): TrialRefLookupPort {
const { executor, cutoffDate, schemaPrefix } = validateFactoryOptions(options);
const sql = buildTrialVisibilitySql(schemaPrefix);
return {
async hasResearchVisibleTrial(trialRef: string): Promise<boolean> {
if (!isCanonicalPositiveBigInt(trialRef)) {
return false;
}
const result = await executor.query<TrialVisibilityRow>(sql, [trialRef, cutoffDate]);
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
throw new TypeError('Invalid executor response: expected an object with a rows array.');
}
return result.rows.length > 0;
},
};
}

View file

@ -1,3 +1,5 @@
export * from './adapters/postgres-symbol-search';
export * from './adapters/postgres-trial-ref';
export * from './copilot-server';
export * from './protocol';
export * from './server';

View file

@ -0,0 +1,489 @@
import { describe, expect, test } from 'bun:test';
import { MarketDataStoreValidationError } from '../src/market-data-store';
import {
createPostgresSymbolSearchPort,
PostgresSymbolSearchError,
type SymbolSearchExecutor,
type SymbolSearchQuery,
} 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
);
});
});
describe('createPostgresSymbolSearchPort (QA edge cases)', () => {
test('accepts a pg.Pool-shaped executor whose query method lives on the prototype', async () => {
class PrototypeExecutor {
readonly calls: RecordedCall[] = [];
async query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
this.calls.push({ text, params });
return { rows: [makeRawRow()] as unknown as readonly Row[] };
}
}
const executor = new PrototypeExecutor();
const port = createPostgresSymbolSearchPort({ executor });
const rows = await port.searchSymbols(BASE_QUERY);
expect(rows.map(r => r.listingId)).toEqual([101]);
expect(executor.calls).toHaveLength(1);
});
test('accepts minimal valid schema identifiers and quotes them', async () => {
for (const schema of ['_', 'a', 'stock_bot_safety_0abc']) {
const fake = createFakeExecutor([]);
const port = createPostgresSymbolSearchPort({ executor: fake.executor, schema });
await port.searchSymbols(BASE_QUERY);
expect(fake.calls[0]!.text).toContain(`FROM "${schema}".listing l`);
}
});
test('propagates executor failures unchanged without retrying', async () => {
const failure = new Error('connection terminated');
let attempts = 0;
const executor: SymbolSearchExecutor = {
async query() {
attempts += 1;
throw failure;
},
};
const port = createPostgresSymbolSearchPort({ executor });
await expect(port.searchSymbols(BASE_QUERY)).rejects.toBe(failure);
expect(attempts).toBe(1);
});
test('binds the UTC calendar date for an instant that is already the next day east of UTC', async () => {
const fake = createFakeExecutor([]);
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
// 2024-02-29T23:30Z is 2024-03-01 in UTC+1 zones; the adapter must still bind the UTC date.
await port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Date.UTC(2024, 1, 29, 23, 30) });
expect(fake.calls[0]!.params?.[0]).toBe('2024-02-29');
});
test('returns an empty array (not null) when the executor returns no rows', async () => {
const fake = createFakeExecutor([]);
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
expect(await port.searchSymbols(BASE_QUERY)).toEqual([]);
});
test('rejects the whole result when any row in a batch is malformed', async () => {
const fake = createFakeExecutor([
makeRawRow(),
makeRawRow({ listing_id: 102, last_bar_date: '2024-04-31' }),
]);
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');
});
});

View file

@ -0,0 +1,525 @@
import { describe, expect, test } from 'bun:test';
import {
type AppendFindingResult,
FILE_FINDING_ERROR_FILING_FAILED,
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
FILE_FINDING_INITIAL_STATUS,
type FileFindingResultPayload,
type FiledFindingRecord,
type FindingWritePort,
PostgresTrialRefError,
type TrialRefExecutor,
createFileFindingTool,
createMcpServer,
createPostgresTrialRefLookupPort,
} from '../src/mcp/index';
import { utcDateOf } from '../src/mcp/tools/vault-fenced-input';
interface RecordedCall {
readonly text: string;
readonly params: readonly unknown[] | undefined;
}
function createFakeExecutor(rows: readonly Record<string, unknown>[] = []): {
readonly calls: RecordedCall[];
readonly executor: TrialRefExecutor;
} {
const calls: RecordedCall[] = [];
const executor: TrialRefExecutor = {
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 createFakeWritePort(): {
readonly appended: FiledFindingRecord[];
readonly port: FindingWritePort;
} {
const appended: FiledFindingRecord[] = [];
const port: FindingWritePort = {
async appendFinding(record: FiledFindingRecord): Promise<AppendFindingResult> {
appended.push(record);
return {
status: 'created',
id: record.id,
createdAt: record.createdAt,
};
},
};
return { appended, port };
}
const CUTOFF_MIDNIGHT_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); // 2025-06-30T00:00:00.000Z
describe('createPostgresTrialRefLookupPort', () => {
test('rejects missing or non-callable executor with INVALID_EXECUTOR', () => {
const invalidOptions: unknown[] = [
null,
undefined,
{},
{ executor: null, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
{ executor: {}, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
{ executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
];
for (const opts of invalidOptions) {
let caught: unknown;
try {
createPostgresTrialRefLookupPort(
opts as Parameters<typeof createPostgresTrialRefLookupPort>[0]
);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect(caught).toBeInstanceOf(RangeError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR');
}
});
test('rejects invalid schema names with INVALID_SCHEMA before any query', () => {
const fake = createFakeExecutor([]);
const badSchemas: unknown[] = [
'',
'Bad-Schema',
'a;drop',
'1schema',
'bad.name',
'space name',
'public"; DROP TABLE trial_ledger; --',
123,
null,
];
for (const schema of badSchemas) {
let caught: unknown;
try {
createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
schema: schema as string,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_SCHEMA');
}
expect(fake.calls).toHaveLength(0);
});
test('rejects invalid or extended-year vaultCutoffTs with INVALID_VAULT_CUTOFF', () => {
const fake = createFakeExecutor([]);
const badCutoffs: unknown[] = [
Number.NaN,
Number.POSITIVE_INFINITY,
Number.NEGATIVE_INFINITY,
'2025-06-30',
null,
undefined,
123.45,
Date.parse('+010000-01-01T00:00:00.000Z'),
Date.parse('-000001-01-01T00:00:00.000Z'),
Date.parse('0000-01-01T00:00:00.000Z'),
];
for (const vaultCutoffTs of badCutoffs) {
let caught: unknown;
try {
createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: vaultCutoffTs as number,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF');
}
expect(fake.calls).toHaveLength(0);
});
test('returns true for a visible trial with one parameterized read-only SELECT and exact params', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const visible = await port.hasResearchVisibleTrial('42');
expect(visible).toBe(true);
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.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i);
expect(call.text).toContain('FROM trial_ledger');
expect(call.text).toContain('trial_id = $1::bigint');
expect(call.text).toContain('sample_end < $2::date');
expect(call.text).toContain('LIMIT 1');
expect(call.params).toEqual(['42', '2025-06-30']);
expect(typeof call.params?.[0]).toBe('string');
});
test('returns false when the executor returns empty rows (unknown or Vault-only trial)', async () => {
const fake = createFakeExecutor([]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const visible = await port.hasResearchVisibleTrial('42');
expect(visible).toBe(false);
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']);
});
test('maps midnight and non-midnight UTC vaultCutoffTs to the same UTC date as utcDateOf', async () => {
const nonMidnightTs = Date.UTC(2025, 5, 30, 23, 59, 59, 999);
const nextDayTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0);
const fakeSameDay = createFakeExecutor([{ visible: 1 }]);
const sameDayPort = createPostgresTrialRefLookupPort({
executor: fakeSameDay.executor,
vaultCutoffTs: nonMidnightTs,
});
await sameDayPort.hasResearchVisibleTrial('7');
expect(fakeSameDay.calls[0]!.params).toEqual(['7', utcDateOf(nonMidnightTs)]);
expect(fakeSameDay.calls[0]!.params?.[1]).toBe('2025-06-30');
const fakeNextDay = createFakeExecutor([{ visible: 1 }]);
const nextDayPort = createPostgresTrialRefLookupPort({
executor: fakeNextDay.executor,
vaultCutoffTs: nextDayTs,
});
await nextDayPort.hasResearchVisibleTrial('7');
expect(fakeNextDay.calls[0]!.params).toEqual(['7', '2025-07-01']);
});
test('returns false with zero executor calls for malformed, injection-shaped, overflowing, and non-string refs', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const invalidRefs: unknown[] = [
'',
' 42',
'42 ',
'042',
'0',
'-1',
'+1',
'1.0',
'1e3',
'0x10',
'42; DROP TABLE trial_ledger',
'9223372036854775808',
'10000000000000000000',
42,
42n,
null,
undefined,
{},
];
for (const ref of invalidRefs) {
const result = await port.hasResearchVisibleTrial(ref as string);
expect(result).toBe(false);
}
expect(fake.calls).toHaveLength(0);
});
test('queries the maximum signed 64-bit BIGINT verbatim as a string without numeric coercion', async () => {
const maxBigIntRef = '9223372036854775807';
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const visible = await port.hasResearchVisibleTrial(maxBigIntRef);
expect(visible).toBe(true);
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]!.text).not.toContain(maxBigIntRef);
expect(fake.calls[0]!.params).toEqual([maxBigIntRef, '2025-06-30']);
});
test('quotes validated optional schema and leaves table unqualified when omitted', async () => {
const fakeDefault = createFakeExecutor([]);
const defaultPort = createPostgresTrialRefLookupPort({
executor: fakeDefault.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
await defaultPort.hasResearchVisibleTrial('1');
expect(fakeDefault.calls[0]!.text).toContain('FROM trial_ledger ');
const fakeScoped = createFakeExecutor([]);
const scopedPort = createPostgresTrialRefLookupPort({
executor: fakeScoped.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
schema: 'research_x',
});
await scopedPort.hasResearchVisibleTrial('1');
expect(fakeScoped.calls[0]!.text).toContain('FROM "research_x".trial_ledger ');
});
test('propagates executor rejections unchanged without retrying', async () => {
const failure = new Error('postgres connection lost');
let attempts = 0;
const executor: TrialRefExecutor = {
async query() {
attempts += 1;
throw failure;
},
};
const port = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
await expect(port.hasResearchVisibleTrial('42')).rejects.toBe(failure);
expect(attempts).toBe(1);
});
test('accepts a pg.Pool-shaped executor with query on its prototype', async () => {
class PoolLikeExecutor {
readonly calls: RecordedCall[] = [];
async query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
this.calls.push({ text, params });
return { rows: [{ visible: 1 }] as unknown as readonly Row[] };
}
}
const executor = new PoolLikeExecutor();
const port = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
expect(await port.hasResearchVisibleTrial('99')).toBe(true);
expect(executor.calls).toHaveLength(1);
});
});
describe('createPostgresTrialRefLookupPort wired into createFileFindingTool', () => {
async function callFileFinding(
executor: TrialRefExecutor,
trialRefs: readonly string[]
): Promise<{
readonly appended: FiledFindingRecord[];
readonly result: { readonly content: readonly { type: string; text: string }[]; readonly isError?: boolean };
}> {
const trialLookup = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const { appended, port } = createFakeWritePort();
const tool = createFileFindingTool({
port,
trialLookup,
newId: () => 'finding-0001',
now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0),
});
const server = createMcpServer({
name: 'test-copilot',
version: '0.1.0',
tools: [tool],
});
const rawResponse = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'file_finding',
arguments: {
kind: 'finding',
title: 'Pre-vault momentum signal',
summary: 'Observed stable rank IC across US equities prior to cutoff.',
trialRefs,
},
},
})
);
const parsed = JSON.parse(rawResponse!) as {
readonly result: {
readonly content: readonly { type: string; text: string }[];
readonly isError?: boolean;
};
};
return { appended, result: parsed.result };
}
test('files a pending_review finding and returns a created receipt when the trial is visible', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const { appended, result } = await callFileFinding(fake.executor, ['42']);
expect(result.isError).toBeUndefined();
const payload = JSON.parse(result.content[0]!.text) as FileFindingResultPayload;
expect(payload).toEqual({
id: 'finding-0001',
createdAt: '2025-06-29T12:00:00.000Z',
created: true,
});
expect(appended).toHaveLength(1);
expect(appended[0]).toEqual({
id: 'finding-0001',
kind: 'finding',
title: 'Pre-vault momentum signal',
status: FILE_FINDING_INITIAL_STATUS,
createdAt: '2025-06-29T12:00:00.000Z',
summary: 'Observed stable rank IC across US equities prior to cutoff.',
trialRefs: ['42'],
evidenceRefs: [],
});
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']);
});
test('returns FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF with zero appends when executor returns no rows', async () => {
const fake = createFakeExecutor([]);
const { appended, result } = await callFileFinding(fake.executor, ['42']);
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
expect(appended).toHaveLength(0);
expect(fake.calls).toHaveLength(1);
});
test('returns FILE_FINDING_ERROR_FILING_FAILED with zero appends when executor rejects', async () => {
const executor: TrialRefExecutor = {
async query() {
throw new Error('database unavailable');
},
};
const { appended, result } = await callFileFinding(executor, ['42']);
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_FILING_FAILED);
expect(appended).toHaveLength(0);
});
});
describe('createPostgresTrialRefLookupPort (QA edge cases)', () => {
test('queries in-range 19-digit refs and rejects 19-digit refs above the signed BIGINT max', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
expect(await port.hasResearchVisibleTrial('1000000000000000000')).toBe(true);
expect(await port.hasResearchVisibleTrial('9223372036854775806')).toBe(true);
expect(await port.hasResearchVisibleTrial('9223372036854775900')).toBe(false);
expect(await port.hasResearchVisibleTrial('9999999999999999999')).toBe(false);
expect(fake.calls.map(c => c.params?.[0])).toEqual([
'1000000000000000000',
'9223372036854775806',
]);
});
test('rejects trailing-newline, tab, fullwidth-digit, and boxed-String refs without querying', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
for (const ref of ['42\n', '\n42', '4\t2', '42', '42\u0000', new String('42')] as unknown[]) {
expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false);
}
expect(fake.calls).toHaveLength(0);
});
test('accepts the four-digit PostgreSQL calendar bounds 0001-01-01 and 9999-12-31 as cutoff dates', async () => {
const earliest = Date.parse('0001-01-01T00:00:00.000Z');
const latest = Date.parse('9999-12-31T23:59:59.999Z');
for (const [ts, expected] of [
[earliest, '0001-01-01'],
[latest, '9999-12-31'],
[Date.UTC(1969, 11, 31, 23, 59, 59, 999), '1969-12-31'],
] as const) {
const fake = createFakeExecutor([]);
const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: ts });
await port.hasResearchVisibleTrial('5');
expect(fake.calls[0]!.params).toEqual(['5', expected]);
}
let caught: unknown;
try {
createPostgresTrialRefLookupPort({
executor: createFakeExecutor().executor,
vaultCutoffTs: latest + 1,
});
} catch (err) {
caught = err;
}
expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF');
});
test('freezes the cutoff date and SQL text at construction across repeated lookups', async () => {
const fake = createFakeExecutor([]);
const options = { executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS };
const port = createPostgresTrialRefLookupPort(options);
await port.hasResearchVisibleTrial('1');
(options as { vaultCutoffTs: number }).vaultCutoffTs = Date.UTC(2030, 0, 1);
await port.hasResearchVisibleTrial('2');
expect(fake.calls).toHaveLength(2);
expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text);
expect(fake.calls[1]!.params).toEqual(['2', '2025-06-30']);
});
test('returns true for multiple matching rows and rejects (not false) on a malformed executor response', async () => {
const many = createFakeExecutor([{ visible: 1 }, { visible: 1 }]);
const manyPort = createPostgresTrialRefLookupPort({
executor: many.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
expect(await manyPort.hasResearchVisibleTrial('3')).toBe(true);
for (const response of [null, {}, { rows: 'x' }, { rows: null }]) {
const executor: TrialRefExecutor = {
async query() {
return response as unknown as { readonly rows: readonly never[] };
},
};
const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS });
await expect(port.hasResearchVisibleTrial('3')).rejects.toBeInstanceOf(TypeError);
}
});
test('propagates a synchronous executor throw as a rejection with the same error', async () => {
const failure = new Error('pool exhausted');
const executor = {
query() {
throw failure;
},
} as unknown as TrialRefExecutor;
const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS });
await expect(port.hasResearchVisibleTrial('42')).rejects.toBe(failure);
});
});

View file

@ -0,0 +1,587 @@
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'bun:test';
import { Client, Pool, type PoolConfig } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
createMcpServer,
createPostgresSymbolSearchPort,
createSearchSymbolsTool,
type SearchSymbolsResultPayload,
type SymbolSearchExecutor,
} from '../../libs/research/src/mcp/index';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('mcp-symbol-search-adapter-pg-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const VAULT_CUTOFF_DATE = '2024-06-30';
const VAULT_CUTOFF_TS = Date.UTC(2024, 5, 30, 0, 0, 0, 0);
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety database required');
}
return connectionString;
}
function createPgExecutor(pool: Pool): SymbolSearchExecutor {
return {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
return pool.query(
text,
params === undefined ? undefined : [...params]
) as unknown as Promise<{ readonly rows: readonly Row[] }>;
},
};
}
function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig {
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 schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`;
const options = [...existingOptions, schemaOptions].join(' ');
return {
connectionString: parsed.toString(),
options,
};
}
async function createIsolatedFixture(connectionString: string | undefined = url) {
const safeUrl = assertSafetyDatabaseUrl(connectionString);
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: safeUrl });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema));
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
const { rows: schemaRows } = await pool.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)}`
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', {
get: () => ({
connect: () => pool.connect(),
}),
});
await runPostgresMigrations(postgres, { track: 'master' });
await seedFixture(pool);
return { admin, pool, schema };
}
async function seedFixture(pool: Pool): Promise<void> {
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(`
INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy)
VALUES
('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('XNYS', 'XNYS', 'NYSE', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('XTSE', 'XTSE', 'TSX', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered')
ON CONFLICT (mic) DO NOTHING
`);
await client.query(`
INSERT INTO instrument (instrument_id, primary_isin, canonical_name, security_type, issuer_country)
OVERRIDING SYSTEM VALUE
VALUES
(101, 'CA1010000001', 'Alpha Oldco Canada', 'common', 'CA'),
(102, 'US1020000002', 'Gap Rename Corp', 'common', 'US'),
(103, 'US1030000003', 'Stealth Future Ventures', 'common', 'US'),
(104, 'CA1040000004', 'No History Metals', 'common', 'CA'),
(105, 'US1050000005', 'Overlap Equity Inc', 'common', 'US'),
(106, 'US1060000006', 'Post Cutoff IPO Inc', 'common', 'US'),
(107, 'CA1070000007', 'Unknown Start Corp', 'common', 'CA'),
(108, 'US1080000008', 'Delist Boundary Co', 'common', 'US'),
(109, 'US1090000009', 'Delist Boundary Active', 'common', 'US'),
(110, 'US1100000010', 'Delist Boundary Unspecified', 'common', 'US'),
(111, 'US1110000011', 'Delist Boundary Future', 'common', 'US'),
(112, 'US1120000012', '100% Pure_Wild\\Co', 'common', 'US'),
(113, 'US1130000013', 'Second Oldco Group', 'common', 'US'),
(114, 'US1140000014', 'Renamed Holdings Inc', 'common', 'US')
`);
await client.query(`
INSERT INTO listing (
listing_id, instrument_id, mic, ticker_root, class_suffix, currency,
listed_from, listed_to, delist_reason
)
OVERRIDING SYSTEM VALUE
VALUES
(101, 101, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active'),
(102, 102, 'XNYS', 'GAPNEW', '', 'USD', '2019-01-01', '2024-12-31', 'active'),
(103, 103, 'XNAS', 'FUTROOT', '', 'USD', '2020-01-01', NULL, NULL),
(104, 104, 'XTSE', 'NOHIST', 'A', 'CAD', '2021-03-15', '2024-06-28', 'active'),
(105, 105, 'XNYS', 'OVLP', '', 'USD', '2018-01-01', '2024-06-28', 'active'),
(106, 106, 'XNAS', 'IPO25', '', 'USD', '2024-07-01', NULL, 'active'),
(107, 107, 'XTSE', 'NULLSTART', '', 'CAD', NULL, NULL, NULL),
(108, 108, 'XNAS', 'DLST1', '', 'USD', '2015-01-01', '2024-06-30', 'merger_cash'),
(109, 109, 'XNAS', 'DLST2', '', 'USD', '2015-01-01', '2024-06-28', 'active'),
(110, 110, 'XNAS', 'DLST3', '', 'USD', '2015-01-01', '2024-06-28', NULL),
(111, 111, 'XNAS', 'DLST4', '', 'USD', '2015-01-01', '2024-09-15', 'bankruptcy_cancelled'),
(112, 112, 'XNYS', 'WILD', '', 'USD', '2020-01-01', '2024-06-28', 'active'),
(113, 113, 'XNAS', 'OLDCO2', '', 'USD', '2020-01-01', '2024-06-28', 'active'),
(114, 114, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active')
`);
await client.query(`
INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source)
VALUES
(114, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'),
(114, 'NEWCO', '2024-07-01', NULL, 'eod'),
(102, 'GAPOLD', '2019-01-01', '2024-05-31', 'eod'),
(102, 'GAPNEW', '2024-07-01', NULL, 'eod'),
(103, 'FUTROOT', '2024-07-15', NULL, 'eod'),
(105, 'OVLP1', '2018-01-01', NULL, 'eod'),
(105, 'OVLPZ', '2023-01-01', NULL, 'eod'),
(105, 'OVLPA', '2023-01-01', NULL, 'eod')
`);
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
describe('PostgreSQL symbol search safety guard', () => {
test('rejects unsafe database targets before connecting', () => {
expect(() => assertSafetyDatabaseUrl(undefined)).toThrow(
'Dedicated stock_bot_safety database required'
);
expect(() =>
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot')
).toThrow('Dedicated stock_bot_safety database required');
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');
});
test('preserves isolated schema search_path precedence over URL startup options', () => {
const schema = 'stock_bot_safety_fixture_options';
const urlWithOptions =
'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic';
const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema);
expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false);
const client = new Client(poolConfig);
const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } })
.connectionParameters.options;
expect(resolvedOptions).toBe(
`-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`
);
});
});
describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => {
test('enforces as-of-cutoff ticker resolution, root suppression, and listed_from bounds', async () => {
const f = await createIsolatedFixture();
const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) });
// (a)/(g) Post-cutoff rename: OLDCO is valid on 2024-06-30; NEWCO starts 2024-07-01 and is invisible even as ticker_root
const oldcoRows = await port.searchSymbols({
query: 'OLDCO',
limit: 1,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(oldcoRows.map(r => r.listingId)).toEqual([101, 113, 114]);
expect(oldcoRows[2]).toEqual({
listingId: 114,
instrumentId: 114,
ticker: 'OLDCO',
classSuffix: null,
name: 'Renamed Holdings Inc',
mic: 'XNAS',
currency: 'USD',
isin: 'US1140000014',
firstBarDate: '2018-01-02',
lastBarDate: '2024-12-31',
delistedAt: null,
});
const newcoRows = await port.searchSymbols({
query: 'NEWCO',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(newcoRows).toEqual([]);
// Expired-but-known fallback (step 3c): GAPNEW is future-only root, falls back to GAPOLD
const gapOldRows = await port.searchSymbols({
query: 'GAPOLD',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(gapOldRows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([
{ id: 102, ticker: 'GAPOLD' },
]);
const gapNewRows = await port.searchSymbols({
query: 'GAPNEW',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(gapNewRows).toEqual([]);
// (h) Future-only root with no prior history: excluded by root, name, and ISIN searches
expect(
await port.searchSymbols({
query: 'FUTROOT',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
})
).toEqual([]);
expect(
await port.searchSymbols({
query: 'Stealth Future',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
})
).toEqual([]);
expect(
await port.searchSymbols({
query: 'US1030000003',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
})
).toEqual([]);
// (i) No history rows at all: falls back to ticker_root
const noHistRows = await port.searchSymbols({
query: 'NOHIST',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(noHistRows).toEqual([
{
listingId: 104,
instrumentId: 104,
ticker: 'NOHIST',
classSuffix: 'A',
name: 'No History Metals',
mic: 'XTSE',
currency: 'CAD',
isin: 'CA1040000004',
firstBarDate: '2021-03-15',
lastBarDate: '2024-06-28',
delistedAt: null,
},
]);
// Overlapping valid history: latest valid_from wins, tie-breaking by ticker ASC (OVLPA < OVLPZ)
const overlapRows = await port.searchSymbols({
query: 'Overlap Equity',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(overlapRows).toHaveLength(1);
expect(overlapRows[0]!.listingId).toBe(105);
expect(overlapRows[0]!.ticker).toBe('OVLPA');
// (b) listed_from > cutoff excluded
expect(
await port.searchSymbols({
query: 'IPO25',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
})
).toEqual([]);
// (c) listed_from IS NULL included
const nullStartRows = await port.searchSymbols({
query: 'NULLSTART',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(nullStartRows).toHaveLength(1);
expect(nullStartRows[0]!.listingId).toBe(107);
expect(nullStartRows[0]!.firstBarDate).toBeNull();
expect(nullStartRows[0]!.lastBarDate).toBeNull();
expect(nullStartRows[0]!.delistedAt).toBeNull();
});
test('supports country filter, case-insensitive exact ISIN, literal wildcards, delisting semantics, explicit schema, and deterministic ordering', async () => {
const f = await createIsolatedFixture();
// Use admin pool (default search_path) with explicit schema option to verify schema quoting
const port = createPostgresSymbolSearchPort({
executor: createPgExecutor(f.admin),
schema: f.schema,
});
// (d) country: 'CA' returns only CA-venue listings
const caRows = await port.searchSymbols({
query: 'OLDCO',
limit: 20,
country: 'CA',
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([{ id: 101, mic: 'XTSE' }]);
// (e) Case-insensitive exact ISIN match with partial-ISIN negative
const isinRows = await port.searchSymbols({
query: 'ca1040000004',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(isinRows.map(r => r.listingId)).toEqual([104]);
const partialIsinRows = await port.searchSymbols({
query: 'CA104000',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(partialIsinRows).toEqual([]);
// Literal wildcard matching: %, _, and \ are escaped
const wildRows = await port.searchSymbols({
query: '100% Pure_Wild\\',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(wildRows.map(r => r.listingId)).toEqual([112]);
// Delisting boundary: 108 confirmed delisted on cutoff (2024-06-30), 109 active, 110 null reason, 111 future delist (2024-09-15)
const allDelist = await port.searchSymbols({
query: 'Delist Boundary',
limit: 1,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(allDelist.map(r => ({ id: r.listingId, delistedAt: r.delistedAt }))).toEqual([
{ id: 108, delistedAt: '2024-06-30' },
{ id: 109, delistedAt: null },
{ id: 110, delistedAt: null },
{ id: 111, delistedAt: '2024-09-15' },
]);
const activeAsOfCutoff = await port.searchSymbols({
query: 'Delist Boundary',
limit: 20,
includeDelisted: false,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(activeAsOfCutoff.map(r => r.listingId)).toEqual([109, 110, 111]);
// Repeated pinned query produces identical deterministic rows
const repeat = await port.searchSymbols({
query: 'Delist Boundary',
limit: 1,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(repeat).toEqual(allDelist);
});
test('composes with createSearchSymbolsTool through MCP for ranking, truncation, clamping, and future delisting masking', async () => {
const f = await createIsolatedFixture();
const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) });
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createSearchSymbolsTool({
port,
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
}),
],
});
const callTool = async (args: Record<string, unknown>): Promise<SearchSymbolsResultPayload> => {
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 'mcp-pg-1',
method: 'tools/call',
params: {
name: 'search_symbols',
arguments: args,
},
})
);
expect(raw).not.toBeNull();
const parsed = JSON.parse(raw!) as {
result: { isError?: boolean; content: Array<{ text: string }> };
};
expect(parsed.result.isError).toBeUndefined();
return JSON.parse(parsed.result.content[0]!.text) as SearchSymbolsResultPayload;
};
// Ranking & truncation: adapter returns ascending listing_id [101 (name), 113 (prefix), 114 (exact)];
// MCP tool must re-rank to exact ticker OLDCO (114) > prefix OLDCO2 (113) and drop name match ZOLD (101)
const oldcoPayload = await callTool({ query: 'OLDCO', limit: 2 });
expect(oldcoPayload.scope).toBe('vault_fenced');
expect(oldcoPayload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS);
expect(oldcoPayload.truncated).toBe(true);
expect(oldcoPayload.rowCount).toBe(2);
expect(oldcoPayload.rows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([
{ id: 114, ticker: 'OLDCO' },
{ id: 113, ticker: 'OLDCO2' },
]);
// Post-cutoff lastBarDate (2024-12-31) is clamped to vaultCutoffDate (2024-06-30)
expect(oldcoPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE);
// Future delisting (111: listed_to=2024-09-15, delist_reason=bankruptcy_cancelled) is masked to null and clamped
const futureDelistPayload = await callTool({
query: 'DLST4',
includeDelisted: false,
});
expect(futureDelistPayload.rowCount).toBe(1);
expect(futureDelistPayload.rows[0]!.listingId).toBe(111);
expect(futureDelistPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE);
expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull();
});
test('moves as-of resolution with the cutoff date, including a near-midnight UTC instant', async () => {
const f = await createIsolatedFixture();
const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) });
const search = (query: string, vaultCutoffTs: number, includeDelisted = true) =>
port.searchSymbols({ query, limit: 20, includeDelisted, vaultCutoffTs });
const lastMsOfCutoffDay = Date.UTC(2024, 5, 30, 23, 59, 59, 999);
const dayAfterCutoff = Date.UTC(2024, 6, 1, 0, 0, 0, 0);
// Last millisecond of 2024-06-30 UTC still resolves the pre-rename ticker.
const lateOld = await search('OLDCO', lastMsOfCutoffDay);
expect(lateOld.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([
{ id: 101, ticker: 'ZOLD' },
{ id: 113, ticker: 'OLDCO2' },
{ id: 114, ticker: 'OLDCO' },
]);
expect(await search('NEWCO', lastMsOfCutoffDay)).toEqual([]);
// One day later the rename, the GAPNEW start and the IPO become visible, and OLDCO no longer resolves to 114.
const nextOld = await search('OLDCO', dayAfterCutoff);
expect(nextOld.map(r => r.listingId)).toEqual([101, 113]);
const nextNew = await search('NEWCO', dayAfterCutoff);
expect(nextNew.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([
{ id: 114, ticker: 'NEWCO' },
]);
const nextGap = await search('GAPNEW', dayAfterCutoff);
expect(nextGap.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([
{ id: 102, ticker: 'GAPNEW' },
]);
expect(await search('GAPOLD', dayAfterCutoff)).toEqual([]);
expect((await search('IPO25', dayAfterCutoff)).map(r => r.listingId)).toEqual([106]);
// A cutoff on the future delisting date makes that delisting confirmed and filterable.
const onFutureDelist = await search('Delist Boundary', Date.UTC(2024, 8, 15), false);
expect(onFutureDelist.map(r => r.listingId)).toEqual([109, 110]);
});
test('projects identical calendar dates regardless of the session TimeZone', async () => {
const f = await createIsolatedFixture();
const client = await f.pool.connect();
try {
await client.query("SET TimeZone = 'Pacific/Kiritimati'");
const executor: SymbolSearchExecutor = {
query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
return client.query(
text,
params === undefined ? undefined : [...params]
) as unknown as Promise<{
readonly rows: readonly Row[];
}>;
},
};
const port = createPostgresSymbolSearchPort({ executor });
const rows = await port.searchSymbols({
query: 'Delist Boundary',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(
rows.map(r => ({
id: r.listingId,
first: r.firstBarDate,
last: r.lastBarDate,
delistedAt: r.delistedAt,
}))
).toEqual([
{ id: 108, first: '2015-01-01', last: '2024-06-30', delistedAt: '2024-06-30' },
{ id: 109, first: '2015-01-01', last: '2024-06-28', delistedAt: null },
{ id: 110, first: '2015-01-01', last: '2024-06-28', delistedAt: null },
{ id: 111, first: '2015-01-01', last: '2024-09-15', delistedAt: '2024-09-15' },
]);
} finally {
await client.query('RESET TimeZone');
client.release();
}
});
test('isolates fixture schema even when the safety database URL includes startup options', async () => {
const parsed = new URL(assertSafetyDatabaseUrl(url));
parsed.searchParams.set('options', '-c statement_timeout=30000 -c search_path=public');
const f = await createIsolatedFixture(parsed.toString());
const { rows } = await f.pool.query<{ current_schema: string | null }>(
'SELECT current_schema() AS current_schema'
);
expect(rows[0]?.current_schema).toBe(f.schema);
const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) });
const matches = await port.searchSymbols({
query: 'OLDCO',
limit: 20,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(matches.map(r => r.listingId)).toEqual([101, 113, 114]);
});
});

View file

@ -0,0 +1,283 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool, type PoolClient } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
type AppendFindingResult,
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
type FiledFindingRecord,
createFileFindingTool,
createMcpServer,
createPostgresTrialRefLookupPort,
type TrialRefExecutor,
} from '../../libs/research/src/mcp/index';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('mcp-trial-ref-adapter-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 MAX_BIGINT_REF = '9223372036854775807';
// 2^53 + 1 is not representable as a JS number; Number('9007199254740993') === 9007199254740992.
const ABOVE_SAFE_INT_REF = '9007199254740993';
const ABOVE_SAFE_INT_NEIGHBOR_REF = '9007199254740992';
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety database required');
}
return connectionString;
}
function createPgExecutor(queryable: Pool | PoolClient): TrialRefExecutor {
return {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
return queryable.query(
text,
params === undefined ? undefined : [...params]
) as unknown as Promise<{ readonly rows: readonly Row[] }>;
},
};
}
async function createIsolatedFixture() {
const safeUrl = assertSafetyDatabaseUrl(url);
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: safeUrl });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: safeUrl,
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
});
const readOnlyPool = new Pool({
connectionString: safeUrl,
options: `-c search_path=${schema} -c default_transaction_read_only=on -c statement_timeout=5000`,
});
cleanup.push(async () => {
await readOnlyPool.end();
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
// Bootstrap pre-additive tables needed by the research migration track.
for (const filename of [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',
'08-create-runs-table.sql',
]) {
await pool.query(readFileSync(`${initDir}${filename}`, 'utf8'));
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', {
get: () => ({
connect: () => pool.connect(),
}),
});
await runPostgresMigrations(postgres, { track: 'research' });
await seedTrials(pool);
return { admin, pool, readOnlyPool, schema };
}
async function seedTrials(pool: Pool): Promise<void> {
const trials: readonly (readonly [string, string])[] = [
['1', '2025-06-29'], // last research-visible day
['2', '2025-06-30'], // sample_end == cutoff: Vault-only
['3', '2025-07-15'], // sample_end after cutoff: Vault-only
[ABOVE_SAFE_INT_REF, '2024-01-31'],
[MAX_BIGINT_REF, '2020-01-31'],
];
for (const [trialId, sampleEnd] of trials) {
await pool.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::bigint, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64),
'2020-01-01'::date, $2::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`,
[trialId, sampleEnd]
);
}
}
describe.skipIf(!url)('PostgreSQL MCP trial-ref lookup adapter', () => {
test('exposes only trials with sample_end strictly before the UTC Vault cutoff date', async () => {
const f = await createIsolatedFixture();
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial('1')).toBe(true);
expect(await port.hasResearchVisibleTrial('2')).toBe(false);
expect(await port.hasResearchVisibleTrial('3')).toBe(false);
expect(await port.hasResearchVisibleTrial('4')).toBe(false); // unknown
expect(await port.hasResearchVisibleTrial(MAX_BIGINT_REF)).toBe(true);
});
test('matches BIGINT ids above 2^53 exactly without numeric coercion', async () => {
const f = await createIsolatedFixture();
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_REF)).toBe(true);
expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_NEIGHBOR_REF)).toBe(false);
});
test('moves the visibility boundary with the cutoff date, including a near-midnight UTC instant', async () => {
const f = await createIsolatedFixture();
const executor = createPgExecutor(f.pool);
const lastMsOfCutoffDay = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 59, 59, 999),
});
const nextDay = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0),
});
expect(await lastMsOfCutoffDay.hasResearchVisibleTrial('2')).toBe(false);
expect(await nextDay.hasResearchVisibleTrial('2')).toBe(true);
expect(await nextDay.hasResearchVisibleTrial('3')).toBe(false);
});
test('runs in a read-only session and is unaffected by the session TimeZone', async () => {
const f = await createIsolatedFixture();
const client = await f.readOnlyPool.connect();
try {
await client.query("SET TimeZone = 'Pacific/Kiritimati'");
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(client),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial('1')).toBe(true);
expect(await port.hasResearchVisibleTrial('2')).toBe(false);
} finally {
await client.query('RESET TimeZone');
client.release();
}
});
test('qualifies trial_ledger with an explicit schema when the session search_path does not include it', async () => {
const f = await createIsolatedFixture();
const client = await f.admin.connect();
try {
// Pin a search_path that cannot contain trial_ledger, independent of the shared public schema.
await client.query('SET search_path TO pg_catalog');
const unqualified = createPostgresTrialRefLookupPort({
executor: createPgExecutor(client),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
const qualified = createPostgresTrialRefLookupPort({
executor: createPgExecutor(client),
vaultCutoffTs: VAULT_CUTOFF_TS,
schema: f.schema,
});
expect(await qualified.hasResearchVisibleTrial('1')).toBe(true);
expect(await qualified.hasResearchVisibleTrial('2')).toBe(false);
// Missing relation must surface as a rejection, never as "not visible".
await expect(unqualified.hasResearchVisibleTrial('1')).rejects.toMatchObject({
code: '42P01',
});
} finally {
await client.query('RESET search_path');
client.release();
}
});
test('leaves trial_ledger untouched and never executes an injection-shaped ref', async () => {
const f = await createIsolatedFixture();
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial('1 OR 1=1')).toBe(false);
expect(await port.hasResearchVisibleTrial("1'; DELETE FROM trial_ledger; --")).toBe(false);
const { rows } = await f.pool.query<{ n: string }>('SELECT count(*)::text AS n FROM trial_ledger');
expect(rows[0]!.n).toBe('5');
});
test('files through createFileFindingTool only when every trial ref is research-visible', async () => {
const f = await createIsolatedFixture();
const trialLookup = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
const appended: FiledFindingRecord[] = [];
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createFileFindingTool({
port: {
async appendFinding(record: FiledFindingRecord): Promise<AppendFindingResult> {
appended.push(record);
return { status: 'created', id: record.id, createdAt: record.createdAt };
},
},
trialLookup,
newId: () => 'finding-pg-0001',
now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0),
}),
],
});
const call = async (trialRefs: readonly string[]) => {
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'file_finding',
arguments: {
kind: 'finding',
title: 'Pre-vault signal',
summary: 'Research-visible evidence only.',
trialRefs,
},
},
})
);
return (JSON.parse(raw!) as { result: { isError?: boolean; content: { text: string }[] } })
.result;
};
const mixed = await call(['1', '2']);
expect(mixed.isError).toBe(true);
expect(mixed.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
expect(appended).toHaveLength(0);
const visible = await call(['1', MAX_BIGINT_REF]);
expect(visible.isError).toBeUndefined();
expect(appended).toHaveLength(1);
expect(appended[0]!.trialRefs).toEqual(['1', MAX_BIGINT_REF]);
});
});

View file

@ -17,11 +17,11 @@
//! 12. `total_assets` (`DOUBLE`, `OPTIONAL`)
//! 13. `total_equity` (`DOUBLE`, `OPTIONAL`)
//! 14. `shares_outstanding` (`DOUBLE`, `OPTIONAL`)
//! 15. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`)
//! 16. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`)
//! 17. `ttm_revenue` (`DOUBLE`, `OPTIONAL`)
//! 18. `ttm_net_income` (`DOUBLE`, `OPTIONAL`)
//! 19. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`)
//! 15. `ttm_revenue` (`DOUBLE`, `OPTIONAL`)
//! 16. `ttm_net_income` (`DOUBLE`, `OPTIONAL`)
//! 17. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`)
//! 18. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`)
//! 19. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`)
//! 20. `ttm_has_estimated_lag` (`BOOLEAN`, `OPTIONAL`)
//!
//! Each physical row flattens `periods[0]` (the latest visible resolved period) and the
@ -500,21 +500,7 @@ pub fn fundamentals_pit_parquet_schema() -> Result<TypePtr, ParquetError> {
.with_repetition(Repetition::OPTIONAL)
.build()?,
),
// 15. ttm_period_end INT32 DATE OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32)
.with_repetition(Repetition::OPTIONAL)
.with_logical_type(Some(LogicalType::Date))
.build()?,
),
// 16. ttm_currency STRING OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::OPTIONAL)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
// 17-19. TTM flow sums DOUBLE OPTIONAL
// 15-17. TTM flow sums DOUBLE OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_revenue", PhysicalType::DOUBLE)
.with_repetition(Repetition::OPTIONAL)
@ -530,6 +516,20 @@ pub fn fundamentals_pit_parquet_schema() -> Result<TypePtr, ParquetError> {
.with_repetition(Repetition::OPTIONAL)
.build()?,
),
// 18. ttm_period_end INT32 DATE OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32)
.with_repetition(Repetition::OPTIONAL)
.with_logical_type(Some(LogicalType::Date))
.build()?,
),
// 19. ttm_currency STRING OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::OPTIONAL)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
// 20. ttm_has_estimated_lag BOOLEAN OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_has_estimated_lag", PhysicalType::BOOLEAN)
@ -998,43 +998,43 @@ impl YearWriter {
&self.buf.shares_outstanding_def,
)
.map_err(map_pq)?;
// 15. ttm_period_end (INT32, OPTIONAL, DATE)
write_optional_i32_col(
&mut rg_writer,
&self.buf.ttm_period_end_values,
&self.buf.ttm_period_end_def,
)
.map_err(map_pq)?;
// 16. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING)
write_optional_interned_str_col(
&mut rg_writer,
&self.buf.ttm_currency_ids,
&self.buf.ttm_currency_def,
&self.buf.ttm_currency_interner,
scratch,
)
.map_err(map_pq)?;
// 17. ttm_revenue (DOUBLE, OPTIONAL)
// 15. ttm_revenue (DOUBLE, OPTIONAL)
write_optional_f64_col(
&mut rg_writer,
&self.buf.ttm_revenue_values,
&self.buf.ttm_revenue_def,
)
.map_err(map_pq)?;
// 18. ttm_net_income (DOUBLE, OPTIONAL)
// 16. ttm_net_income (DOUBLE, OPTIONAL)
write_optional_f64_col(
&mut rg_writer,
&self.buf.ttm_net_income_values,
&self.buf.ttm_net_income_def,
)
.map_err(map_pq)?;
// 19. ttm_operating_cash_flow (DOUBLE, OPTIONAL)
// 17. ttm_operating_cash_flow (DOUBLE, OPTIONAL)
write_optional_f64_col(
&mut rg_writer,
&self.buf.ttm_operating_cash_flow_values,
&self.buf.ttm_operating_cash_flow_def,
)
.map_err(map_pq)?;
// 18. ttm_period_end (INT32, OPTIONAL, DATE)
write_optional_i32_col(
&mut rg_writer,
&self.buf.ttm_period_end_values,
&self.buf.ttm_period_end_def,
)
.map_err(map_pq)?;
// 19. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING)
write_optional_interned_str_col(
&mut rg_writer,
&self.buf.ttm_currency_ids,
&self.buf.ttm_currency_def,
&self.buf.ttm_currency_interner,
scratch,
)
.map_err(map_pq)?;
// 20. ttm_has_estimated_lag (BOOLEAN, OPTIONAL)
write_bool_col(
&mut rg_writer,

View file

@ -23,7 +23,8 @@ use crate::events::{
};
use crate::fundamentals::{
build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod,
FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm, StatutoryLagVenue, TtmFlowFields,
FundamentalsFields, FundamentalsPeriodSlot, FundamentalsSnapshot, FundamentalsTtm,
StatutoryLagVenue, TtmFlowFields,
};
use crate::split::ymd_to_epoch_days;
@ -113,11 +114,11 @@ struct DecodedFundamentalsPitRow {
total_assets: Option<f64>,
total_equity: Option<f64>,
shares_outstanding: Option<f64>,
ttm_period_end: Option<i32>,
ttm_currency: Option<String>,
ttm_revenue: Option<f64>,
ttm_net_income: Option<f64>,
ttm_operating_cash_flow: Option<f64>,
ttm_period_end: Option<i32>,
ttm_currency: Option<String>,
ttm_has_estimated_lag: Option<bool>,
}
@ -345,11 +346,11 @@ fn read_parquet_rows(path: &Path) -> Vec<DecodedFundamentalsPitRow> {
let total_assets = read_opt_f64(11);
let total_equity = read_opt_f64(12);
let shares_outstanding = read_opt_f64(13);
let ttm_period_end = read_opt_i32(14);
let ttm_currency = read_opt_str(15);
let ttm_revenue = read_opt_f64(16);
let ttm_net_income = read_opt_f64(17);
let ttm_operating_cash_flow = read_opt_f64(18);
let ttm_revenue = read_opt_f64(14);
let ttm_net_income = read_opt_f64(15);
let ttm_operating_cash_flow = read_opt_f64(16);
let ttm_period_end = read_opt_i32(17);
let ttm_currency = read_opt_str(18);
let ttm_has_estimated_lag = read_opt_bool(19);
for i in 0..rg_rows {
@ -368,11 +369,11 @@ fn read_parquet_rows(path: &Path) -> Vec<DecodedFundamentalsPitRow> {
total_assets: total_assets[i],
total_equity: total_equity[i],
shares_outstanding: shares_outstanding[i],
ttm_period_end: ttm_period_end[i],
ttm_currency: ttm_currency[i].clone(),
ttm_revenue: ttm_revenue[i],
ttm_net_income: ttm_net_income[i],
ttm_operating_cash_flow: ttm_operating_cash_flow[i],
ttm_period_end: ttm_period_end[i],
ttm_currency: ttm_currency[i].clone(),
ttm_has_estimated_lag: ttm_has_estimated_lag[i],
});
}
@ -381,6 +382,80 @@ fn read_parquet_rows(path: &Path) -> Vec<DecodedFundamentalsPitRow> {
out
}
fn assert_decoded_matches_snapshot_bit_for_bit(
actual: &DecodedFundamentalsPitRow,
snapshot: &FundamentalsSnapshot<i32>,
) {
let latest = snapshot
.periods
.first()
.expect("snapshot must have at least one period");
assert_eq!(actual.listing_id, snapshot.key);
assert_eq!(
actual.effective_known_at,
snapshot.effective_known_at_utc_micros
);
assert_eq!(actual.known_at_source, snapshot.known_at_source);
assert_eq!(actual.has_estimated_lag, snapshot.has_estimated_lag);
assert_eq!(actual.period_end, latest.period_end);
assert_eq!(actual.fiscal_period, latest.fiscal_period.as_str());
assert_eq!(actual.currency, latest.currency);
assert_eq!(actual.period_known_at, latest.known_at_utc_micros);
assert_eq!(
actual.revenue.map(f64::to_bits),
latest.fields.revenue.map(f64::to_bits)
);
assert_eq!(
actual.net_income.map(f64::to_bits),
latest.fields.net_income.map(f64::to_bits)
);
assert_eq!(
actual.operating_cash_flow.map(f64::to_bits),
latest.fields.operating_cash_flow.map(f64::to_bits)
);
assert_eq!(
actual.total_assets.map(f64::to_bits),
latest.fields.total_assets.map(f64::to_bits)
);
assert_eq!(
actual.total_equity.map(f64::to_bits),
latest.fields.total_equity.map(f64::to_bits)
);
assert_eq!(
actual.shares_outstanding.map(f64::to_bits),
latest.fields.shares_outstanding.map(f64::to_bits)
);
match &snapshot.ttm {
Some(ttm) => {
assert_eq!(
actual.ttm_revenue.map(f64::to_bits),
ttm.flows.revenue.map(f64::to_bits)
);
assert_eq!(
actual.ttm_net_income.map(f64::to_bits),
ttm.flows.net_income.map(f64::to_bits)
);
assert_eq!(
actual.ttm_operating_cash_flow.map(f64::to_bits),
ttm.flows.operating_cash_flow.map(f64::to_bits)
);
assert_eq!(actual.ttm_period_end, Some(ttm.ending_period_end));
assert_eq!(actual.ttm_currency.as_deref(), Some(ttm.currency.as_str()));
assert_eq!(actual.ttm_has_estimated_lag, Some(ttm.has_estimated_lag));
}
None => {
assert_eq!(actual.ttm_revenue, None);
assert_eq!(actual.ttm_net_income, None);
assert_eq!(actual.ttm_operating_cash_flow, None);
assert_eq!(actual.ttm_period_end, None);
assert_eq!(actual.ttm_currency, None);
assert_eq!(actual.ttm_has_estimated_lag, None);
}
}
}
fn assert_no_transient_files(dir: &Path) {
if !dir.exists() {
return;
@ -654,20 +729,6 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() {
None,
ConvertedType::NONE,
),
(
"ttm_period_end",
PhysicalType::INT32,
Repetition::OPTIONAL,
Some(LogicalType::Date),
ConvertedType::DATE,
),
(
"ttm_currency",
PhysicalType::BYTE_ARRAY,
Repetition::OPTIONAL,
Some(LogicalType::String),
ConvertedType::UTF8,
),
(
"ttm_revenue",
PhysicalType::DOUBLE,
@ -689,6 +750,20 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() {
None,
ConvertedType::NONE,
),
(
"ttm_period_end",
PhysicalType::INT32,
Repetition::OPTIONAL,
Some(LogicalType::Date),
ConvertedType::DATE,
),
(
"ttm_currency",
PhysicalType::BYTE_ARRAY,
Repetition::OPTIONAL,
Some(LogicalType::String),
ConvertedType::UTF8,
),
(
"ttm_has_estimated_lag",
PhysicalType::BOOLEAN,
@ -741,19 +816,19 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() {
assert_eq!(decoded[0].total_assets, None);
assert_eq!(decoded[0].total_equity, Some(220.0));
assert_eq!(decoded[0].shares_outstanding, None);
assert_eq!(decoded[0].ttm_period_end, None);
assert_eq!(decoded[0].ttm_currency, None);
assert_eq!(decoded[0].ttm_revenue, None);
assert_eq!(decoded[0].ttm_net_income, None);
assert_eq!(decoded[0].ttm_operating_cash_flow, None);
assert_eq!(decoded[0].ttm_period_end, None);
assert_eq!(decoded[0].ttm_currency, None);
assert_eq!(decoded[0].ttm_has_estimated_lag, None);
// Row 1: ttm_has_estimated_lag = Some(false)
assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30)));
assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD"));
assert_eq!(decoded[1].ttm_revenue, Some(370.0));
assert_eq!(decoded[1].ttm_net_income, Some(37.0));
assert_eq!(decoded[1].ttm_operating_cash_flow, Some(55.0));
assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30)));
assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD"));
assert_eq!(decoded[1].ttm_has_estimated_lag, Some(false));
// Row 2: ttm_has_estimated_lag = Some(true), partial missing TTM flow, statutory lag source.
@ -761,16 +836,273 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() {
assert!(decoded[2].has_estimated_lag);
assert_eq!(decoded[2].fiscal_period, "FY");
assert_eq!(decoded[2].currency, "CAD");
assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30)));
assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD"));
assert_eq!(decoded[2].ttm_revenue, Some(450.0));
assert_eq!(decoded[2].ttm_net_income, None);
assert_eq!(decoded[2].ttm_operating_cash_flow, Some(60.0));
assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30)));
assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD"));
assert_eq!(decoded[2].ttm_has_estimated_lag, Some(true));
assert_no_transient_files(&tmp.path().join("fundamentals_pit"));
}
#[test]
fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero() {
let tmp = TempDirGuard::new("builder-roundtrip-bits");
let venues = BTreeMap::from([
(10_i32, StatutoryLagVenue::UsTsx),
(20_i32, StatutoryLagVenue::TsxvCse),
]);
let observations = vec![
// Listing 10: 5 consecutive quarters (Q1 2023 .. Q1 2024).
// Q1..Q4 2023 all have distinct non-null flow values so Q4 2023's snapshot carries
// three distinct non-null TTM flows (catching any positional TTM column transposition).
// Q1 2024 omits operating_cash_flow so its snapshot has ttm_operating_cash_flow = None
// while ttm_revenue and ttm_net_income remain populated and distinct.
obs(
10,
day(2023, 3, 31),
FiscalPeriod::Quarterly,
"USD",
Some(day(2023, 5, 2)),
FundamentalsFields {
revenue: Some(95.5),
net_income: Some(9.25),
operating_cash_flow: Some(17.75),
total_assets: Some(960.0),
total_equity: Some(380.0),
shares_outstanding: Some(49_500_000.0),
},
),
obs(
10,
day(2023, 6, 30),
FiscalPeriod::Quarterly,
"USD",
Some(day(2023, 8, 2)),
FundamentalsFields {
revenue: Some(101.25),
net_income: Some(11.5),
operating_cash_flow: Some(19.75),
total_assets: Some(1_000.0),
total_equity: Some(400.0),
shares_outstanding: Some(50_000_000.0),
},
),
obs(
10,
day(2023, 9, 30),
FiscalPeriod::Quarterly,
"USD",
Some(day(2023, 11, 3)),
FundamentalsFields {
revenue: Some(110.5),
net_income: Some(12.25),
operating_cash_flow: Some(21.0),
total_assets: None,
total_equity: Some(415.0),
shares_outstanding: Some(50_100_000.0),
},
),
obs(
10,
day(2023, 12, 31),
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 2, 14)),
FundamentalsFields {
revenue: Some(125.0),
net_income: Some(14.0),
operating_cash_flow: Some(22.5),
total_assets: Some(1_120.0),
total_equity: None,
shares_outstanding: Some(50_200_000.0),
},
),
obs(
10,
day(2024, 3, 31),
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 5, 1)),
FundamentalsFields {
revenue: Some(130.75),
net_income: Some(16.5),
operating_cash_flow: None,
total_assets: Some(1_150.0),
total_equity: Some(440.0),
shares_outstanding: None,
},
),
// Listing 20: unlinked observation -> statutory_lag_estimate (+60d for TSXV/CSE),
// ttm == None.
obs(
20,
day(2024, 3, 31),
FiscalPeriod::Quarterly,
"CAD",
None,
FundamentalsFields {
revenue: Some(42.5),
net_income: Some(-3.5),
operating_cash_flow: None,
total_assets: Some(25.0),
total_equity: Some(12.5),
shares_outstanding: Some(8_000_000.0),
},
),
];
let filings = vec![
filing(10, "2023-05-02T16:05:00 EDT", "10-Q"),
filing(10, "2023-08-02T16:10:00 EDT", "10-Q"),
filing(10, "2023-11-03T16:05:00 EDT", "10-Q"),
filing(10, "2024-02-14T16:15:00 EST", "10-Q"),
filing(10, "2024-05-01T16:20:00 EDT", "10-Q"),
];
let built = build_fundamentals_rows(observations, filings, &venues);
let mut snapshots = build_fundamentals_snapshots(&built.rows, 4).expect("build snapshots");
assert_eq!(snapshots.len(), 6);
// Append a direct snapshot carrying signed negative zero (-0.0) vs positive zero (+0.0) in
// statement fields (builder normalizes -0.0; this verifies the Parquet writer preserves exact
// IEEE-754 bit patterns without altering them).
snapshots.push(FundamentalsSnapshot {
key: 30_i32,
effective_known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0),
known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG,
has_estimated_lag: true,
periods: vec![FundamentalsPeriodSlot {
period_end: day(2024, 3, 31),
fiscal_period: FiscalPeriod::Quarterly,
currency: "CAD".to_string(),
known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0),
known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG,
has_estimated_lag: true,
fields: FundamentalsFields {
revenue: Some(-0.0_f64),
net_income: Some(0.0_f64),
operating_cash_flow: None,
total_assets: Some(10.0),
total_equity: None,
shares_outstanding: Some(1_000_000.0),
},
}],
ttm: None,
});
let rows_from_ref: Vec<FundamentalsPitParquetRow> = snapshots
.iter()
.map(FundamentalsPitParquetRow::from)
.collect();
let rows_from_owned: Vec<FundamentalsPitParquetRow> = snapshots
.clone()
.into_iter()
.map(FundamentalsPitParquetRow::from)
.collect();
assert_eq!(rows_from_ref, rows_from_owned);
let stats = write_fundamentals_pit_dataset(
tmp.path(),
&rows_from_ref,
FundamentalsPitWriteOptions {
row_group_rows: 2,
zstd_level: DEFAULT_ZSTD_LEVEL,
},
)
.expect("write builder snapshots");
let expected_by_year = BTreeMap::from([(2023, 3), (2024, 4)]);
assert_eq!(stats.rows_written, 7);
assert_eq!(stats.files_written, 2);
assert_eq!(stats.row_groups_written, 4);
assert_eq!(stats.rows_by_year, expected_by_year);
let mut total_bytes = 0u64;
for (&year, &expected_count) in &expected_by_year {
let path = tmp
.path()
.join(format!("fundamentals_pit/year={year:04}/part.parquet"));
assert!(path.is_file(), "missing {}", path.display());
total_bytes += fs::metadata(&path).expect("metadata").len();
let decoded = read_parquet_rows(&path);
let expected_snapshots: Vec<&FundamentalsSnapshot<i32>> = snapshots
.iter()
.filter(|s| partition_year_utc(s.effective_known_at_utc_micros) == year)
.collect();
assert_eq!(decoded.len(), expected_count);
assert_eq!(decoded.len(), expected_snapshots.len());
for (actual_row, snap) in decoded.iter().zip(expected_snapshots.iter()) {
assert_decoded_matches_snapshot_bit_for_bit(actual_row, snap);
}
if year == 2024 {
// Q4 2023 snapshot (filed 2024-02-14): all three TTM flows present and distinct.
let full_ttm = decoded
.iter()
.find(|r| r.listing_id == 10 && r.period_end == day(2023, 12, 31))
.expect("listing 10 Q4 2023 row");
assert_eq!(full_ttm.ttm_revenue, Some(432.25));
assert_eq!(full_ttm.ttm_net_income, Some(47.0));
assert_eq!(full_ttm.ttm_operating_cash_flow, Some(81.0));
assert_eq!(full_ttm.ttm_period_end, Some(day(2023, 12, 31)));
assert_eq!(full_ttm.ttm_currency.as_deref(), Some("USD"));
assert_eq!(full_ttm.ttm_has_estimated_lag, Some(false));
// Q1 2024 snapshot (filed 2024-05-01): partial null TTM flow.
let partial_ttm = decoded
.iter()
.find(|r| r.listing_id == 10 && r.period_end == day(2024, 3, 31))
.expect("listing 10 Q1 2024 row");
assert_eq!(partial_ttm.ttm_revenue, Some(467.5));
assert_eq!(partial_ttm.ttm_net_income, Some(54.25));
assert_eq!(partial_ttm.ttm_operating_cash_flow, None);
assert_eq!(partial_ttm.ttm_period_end, Some(day(2024, 3, 31)));
assert_eq!(partial_ttm.ttm_currency.as_deref(), Some("USD"));
assert_eq!(partial_ttm.ttm_has_estimated_lag, Some(false));
// Listing 20: statutory lag provenance and ttm == None.
let est_row = decoded
.iter()
.find(|r| r.listing_id == 20)
.expect("listing 20 row");
assert_eq!(est_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
assert!(est_row.has_estimated_lag);
assert_eq!(est_row.ttm_revenue, None);
assert_eq!(est_row.ttm_net_income, None);
assert_eq!(est_row.ttm_operating_cash_flow, None);
assert_eq!(est_row.ttm_period_end, None);
assert_eq!(est_row.ttm_currency, None);
assert_eq!(est_row.ttm_has_estimated_lag, None);
// Listing 30: exact IEEE-754 -0.0 vs +0.0 bit preservation across Parquet write/read.
let signed_zero_row = decoded
.iter()
.find(|r| r.listing_id == 30)
.expect("listing 30 row");
assert_eq!(
signed_zero_row.revenue.map(f64::to_bits),
Some((-0.0_f64).to_bits())
);
assert_ne!(
signed_zero_row.revenue.map(f64::to_bits),
Some(0.0_f64.to_bits())
);
assert_eq!(
signed_zero_row.net_income.map(f64::to_bits),
Some(0.0_f64.to_bits())
);
}
}
assert_eq!(stats.bytes_written, total_bytes);
assert_no_transient_files(&tmp.path().join("fundamentals_pit"));
}
#[test]
fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm() {
let listing_id = 42_i32;
@ -1033,6 +1365,11 @@ fn utc_year_partitioning_interleaved_listings_and_midnight_boundary() {
let path_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet");
assert!(path_2023.is_file());
assert!(path_2024.is_file());
assert_eq!(
stats.bytes_written,
fs::metadata(&path_2023).expect("meta 2023").len()
+ fs::metadata(&path_2024).expect("meta 2024").len()
);
let decoded_2023 = read_parquet_rows(&path_2023);
let decoded_2024 = read_parquet_rows(&path_2024);
@ -1264,7 +1601,6 @@ fn publish_failure_on_later_year_rolls_back_replaced_and_new_partitions() {
assert_no_transient_files(&tmp.path().join("fundamentals_pit"));
}
// ---------------------------------------------------------------------------------------------
// QA additions (T-143): full-row round-trip equality, builder estimated-lag provenance,
// partial-rewrite semantics, deterministic bytes, and remaining typed validation errors.
@ -1291,11 +1627,11 @@ fn expected_decoded(row: &FundamentalsPitParquetRow) -> DecodedFundamentalsPitRo
total_assets: latest.fields.total_assets,
total_equity: latest.fields.total_equity,
shares_outstanding: latest.fields.shares_outstanding,
ttm_period_end: ttm.map(|t| t.ending_period_end),
ttm_currency: ttm.map(|t| t.currency.clone()),
ttm_revenue: ttm.and_then(|t| t.flows.revenue),
ttm_net_income: ttm.and_then(|t| t.flows.net_income),
ttm_operating_cash_flow: ttm.and_then(|t| t.flows.operating_cash_flow),
ttm_period_end: ttm.map(|t| t.ending_period_end),
ttm_currency: ttm.map(|t| t.currency.clone()),
ttm_has_estimated_lag: ttm.map(|t| t.has_estimated_lag),
}
}
@ -1594,11 +1930,11 @@ fn builder_statutory_lag_snapshots_keep_estimated_provenance_on_disk() {
assert_eq!(decoded[1].operating_cash_flow, None);
// Only two quarters exist, so TTM is unavailable and every ttm_* column is null.
for r in &decoded {
assert_eq!(r.ttm_period_end, None);
assert_eq!(r.ttm_currency, None);
assert_eq!(r.ttm_revenue, None);
assert_eq!(r.ttm_net_income, None);
assert_eq!(r.ttm_operating_cash_flow, None);
assert_eq!(r.ttm_period_end, None);
assert_eq!(r.ttm_currency, None);
assert_eq!(r.ttm_has_estimated_lag, None);
}
}