T-139: M2.4a — Versioned Feature Library core: declarative DuckDB SQL feature definitions + registerSignal registry + versioned Parquet batch-plan runner over an injected DuckDbExecutor in libs/research/src/feature-library.ts (pure, no new deps)

This commit is contained in:
Studio 2026-12-01 21:07:01 -05:00
commit 108f96c681
43 changed files with 17589 additions and 417 deletions

View file

@ -1,102 +1,115 @@
# QuestDB Client Library
A comprehensive QuestDB client library for the Stock Bot trading platform, optimized for time-series data, market analytics, and high-performance queries.
## Features
- **Time-Series Optimized**: Built specifically for time-series data patterns
- **Dual Protocol Support**: HTTP REST API and PostgreSQL wire protocol
- **InfluxDB Line Protocol**: High-performance data ingestion
- **SQL Analytics**: Full SQL support for complex analytics
- **Schema Management**: Automatic table creation and partitioning
- **Performance Monitoring**: Query performance tracking and optimization
- **Health Monitoring**: Connection health monitoring and metrics
## Usage
```typescript
import { QuestDBClient } from '@stock-bot/questdb';
// Initialize client
const questClient = new QuestDBClient();
await questClient.connect();
// Insert market data using InfluxDB Line Protocol
await questClient.insert('ohlcv', {
symbol: 'AAPL',
open: 150.00,
high: 152.00,
low: 149.50,
close: 151.50,
volume: 1000000,
timestamp: new Date()
});
// Query with SQL
const prices = await questClient.query(`
SELECT symbol, close, timestamp
FROM ohlcv
WHERE symbol = 'AAPL'
AND timestamp > dateadd('d', -1, now())
ORDER BY timestamp DESC
`);
// Time-series aggregations
const dailyStats = await questClient.aggregate('ohlcv')
.select(['symbol', 'avg(close) as avg_price'])
.where('symbol = ?', ['AAPL'])
.groupBy('symbol')
.sampleBy('1d', 'timestamp')
.execute();
```
## Data Types
The client provides typed access to the following time-series data:
- **ohlcv**: OHLCV candlestick data
- **trades**: Individual trade executions
- **quotes**: Bid/ask quote data
- **indicators**: Technical indicator values
- **performance**: Portfolio performance metrics
- **risk_metrics**: Risk calculation results
## Configuration
Configure using environment variables:
```env
QUESTDB_HOST=localhost
QUESTDB_HTTP_PORT=9000
QUESTDB_PG_PORT=8812
QUESTDB_INFLUX_PORT=9009
```
## Time-Series Features
QuestDB excels at:
- **High-frequency data**: Millions of data points per second
- **Time-based partitioning**: Automatic partitioning by time
- **ASOF JOINs**: Time-series specific joins
- **SAMPLE BY**: Time-based aggregations
- **LATEST BY**: Get latest values by key
## Performance
The client includes performance optimizations:
- Connection pooling for HTTP and PostgreSQL protocols
- Batch insertions for high throughput
- Compressed data transfer
- Query result caching
- Automatic schema optimization
## Health Monitoring
Built-in health monitoring:
```typescript
const health = await questClient.getHealth();
console.log(health.status); // 'healthy' | 'degraded' | 'unhealthy'
```
# QuestDB Client Library
A QuestDB 10.2.0 client library for the Stock Bot trading platform, optimized for time-series data, parameterized PGWire queries, and intraday bar storage.
## Features
- **Time-Series Optimized**: Built for QuestDB 10.2.0 (`LATEST ON`, `SAMPLE BY`, `ASOF JOIN`)
- **Parameterized PGWire Queries**: All value filters bind `$1..$n` placeholders; structured identifiers and intervals are strictly validated
- **Contract DDL**: Offline DDL generator for M2 intraday tables (`bars_1m`, `fx_1m`, `bar_revisions`) with `SYMBOL CAPACITY ... [NO]CACHE`, `PARTITION BY MONTH WAL`, and `DEDUP UPSERT KEYS`
- **Typed `bars_1m` Range Reader**: `readBars1m()` binds `listing_id` as canonical decimal string, returns `INT32` `listing_id` values, and projects `ts` and `known_at` as lossless UTC epoch microseconds (`bigint`)
- **InfluxDB Line Protocol**: Batch ingestion writer
- **Health Monitoring**: Connection health monitoring and metrics
## Usage
### Parameterized Queries & `LATEST ON`
```typescript
import { QuestDBClient, QuestDBQueryBuilder } from '@stock-bot/questdb';
const questClient = new QuestDBClient({
host: 'localhost',
httpPort: 9000,
pgPort: 8812,
influxPort: 9009,
database: 'qdb',
});
await questClient.connect();
// Parameterized PGWire query via query builder
const { sql, params } = QuestDBQueryBuilder.create(questClient)
.select('listing_id', 'ts', 'close', 'volume')
.from('bars_1m')
.where('listing_id = $1', ['1042'])
.latestOn('ts', 'listing_id')
.buildParameterized();
// sql:
// SELECT listing_id, ts, close, volume FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id
// params: ['1042']
// Execute directly (forwards both SQL and bound params)
const latestBars = await questClient.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', {
where: 'session = $1',
params: ['RTH'],
});
// Override the designated timestamp column explicitly
const latestRevisions = await questClient.latestBy(
'bar_revisions',
['listing_id', 'revised_at', 'new_close'],
'listing_id',
{ timestampColumn: 'revised_at' }
);
// Time-series aggregations with bound filters
const hourlyStats = await questClient
.aggregate('ohlcv_data')
.selectAgg({ avg_close: 'avg(close)' })
.whereSymbol('AAPL')
.whereLastHours(24)
.groupBy('symbol')
.sampleBy('1h')
.execute();
```
### Reading `bars_1m` Ranges
```typescript
import { readBars1m } from '@stock-bot/questdb';
// Queries `[from, to)` ordered by `ts ASC`, binding listingId as decimal string SYMBOL
// and converting returned `listing_id` back to signed INT32.
const bars = await readBars1m(
questClient,
1042,
new Date('2024-01-02T14:30:00.000Z'),
new Date('2024-01-02T21:00:00.000Z')
);
```
> **Storage-layer read semantics**: `readBars1m` returns all stored bars in `[from, to)` with `ts` and `known_at` projected via `CAST(... AS LONG)` as UTC epoch microseconds (`bigint`, preserving all 6 fractional digits independent of host timezone) without applying replay cutoffs. Research callers (`MarketDataStore`) remain responsible for as-of availability filtering and Vault fencing.
### M2 Intraday Contract DDL (Offline)
```typescript
import { getM2IntradayDDL } from '@stock-bot/questdb';
const ddl = getM2IntradayDDL();
// ddl.bars_1m -> CREATE TABLE IF NOT EXISTS bars_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, listing_id)
// ddl.fx_1m -> CREATE TABLE IF NOT EXISTS fx_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, pair)
// ddl.bar_revisions -> CREATE TABLE IF NOT EXISTS bar_revisions (...) TIMESTAMP(revised_at) PARTITION BY MONTH WAL
```
M2 intraday tables are opt-in and are not auto-created during `QuestDBClient.connect()`.
## Configuration
Configure using environment variables:
```env
QUESTDB_HOST=localhost
QUESTDB_HTTP_PORT=9000
QUESTDB_PG_PORT=8812
QUESTDB_INFLUX_PORT=9009
```
## Time-Series Features
QuestDB 10.2.0 supports:
- **High-frequency data**: Millions of data points per second
- **Time-based partitioning**: Monthly WAL partitions for intraday tables
- **ASOF JOINs**: Time-series specific joins
- **SAMPLE BY**: Time-based aggregations
- **LATEST ON**: Get latest values per partition key (`LATEST ON <ts> PARTITION BY <keys>`)

View file

@ -3,15 +3,193 @@ import { Pool } from 'pg';
import type { LoggerLike } from '@stock-bot/logger';
import { QuestDBHealthMonitor } from './health';
import { QuestDBInfluxWriter } from './influx-writer';
import { QuestDBQueryBuilder } from './query-builder';
import {
assertIdentifier,
assertSampleInterval,
assertSelectColumn,
QuestDBQueryBuilder,
rebaseWhereCondition,
} from './query-builder';
import { QuestDBSchemaManager } from './schema';
import type {
Bar1mRow,
LatestByOptions,
QueryResult,
QuestDBClientConfig,
QuestDBConnectionOptions,
QuestDBQueryable,
TableNames,
} from './types';
const INT32_MIN = -2147483648;
const INT32_MAX = 2147483647;
const CANONICAL_INT_RE = /^-?(?:0|[1-9]\d*)$/;
const ISO_UTC_OR_OFFSET_RE =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|([+-])(\d{2}):(\d{2}))$/;
const ALLOWED_PARTITIONS = new Set(['NONE', 'HOUR', 'DAY', 'MONTH', 'YEAR']);
function formatInt32ListingId(listingId: number): string {
if (!Number.isInteger(listingId) || listingId < INT32_MIN || listingId > INT32_MAX) {
throw new RangeError(
`Invalid listingId: expected signed INT32 integer, received ${String(listingId)}`
);
}
return String(listingId === 0 ? 0 : listingId);
}
function parseInt32ListingSymbol(raw: unknown): number {
if (typeof raw !== 'string' || !CANONICAL_INT_RE.test(raw)) {
throw new Error(`Malformed bars_1m listing_id SYMBOL value: "${String(raw)}"`);
}
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed < INT32_MIN || parsed > INT32_MAX) {
throw new RangeError(`Out-of-range bars_1m listing_id SYMBOL value: "${raw}"`);
}
return parsed;
}
function toUtcIsoString(value: Date | string, label: string): string {
if (value instanceof Date) {
if (Number.isNaN(value.getTime())) {
throw new Error(`Invalid ${label} timestamp: Date is NaN`);
}
return value.toISOString();
}
if (typeof value === 'string') {
const trimmed = value.trim();
const match = ISO_UTC_OR_OFFSET_RE.exec(trimmed);
if (!match) {
throw new Error(
`Invalid ${label} timestamp: expected ISO-8601 string with explicit UTC or offset timezone, received "${value}"`
);
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const hour = Number(match[4]);
const minute = Number(match[5]);
const second = Number(match[6]);
const frac = match[7];
const tz = match[8];
const baseUtcMs = Date.UTC(year, month - 1, day, hour, minute, second);
const check = new Date(baseUtcMs);
if (
check.getUTCFullYear() !== year ||
check.getUTCMonth() !== month - 1 ||
check.getUTCDate() !== day ||
check.getUTCHours() !== hour ||
check.getUTCMinutes() !== minute ||
check.getUTCSeconds() !== second
) {
throw new Error(`Invalid ${label} timestamp calendar date/time: "${value}"`);
}
if (tz === 'Z') {
return trimmed;
}
const sign = match[9] === '+' ? 1 : -1;
const offsetHours = Number(match[10]);
const offsetMinutes = Number(match[11]);
if (offsetHours > 23 || offsetMinutes > 59) {
throw new Error(`Invalid ${label} timestamp timezone offset: "${value}"`);
}
const adjustedUtcMs = baseUtcMs - sign * (offsetHours * 60 + offsetMinutes) * 60_000;
const utcDate = new Date(adjustedUtcMs);
const isoSeconds = utcDate.toISOString().slice(0, 19);
return frac ? `${isoSeconds}.${frac}Z` : `${isoSeconds}Z`;
}
throw new Error(`Invalid ${label} timestamp: "${String(value)}"`);
}
function parseUtcEpochMicros(raw: unknown, field: string): bigint {
if (typeof raw === 'bigint') {
return raw;
}
if (typeof raw === 'string' && CANONICAL_INT_RE.test(raw)) {
return BigInt(raw);
}
if (typeof raw === 'number' && Number.isSafeInteger(raw)) {
return BigInt(raw);
}
throw new Error(`Invalid bars_1m ${field} UTC epoch microseconds: "${String(raw)}"`);
}
function parseRequiredFiniteNumber(raw: unknown, field: string): number {
const value =
typeof raw === 'number'
? raw
: typeof raw === 'string' && raw.trim().length > 0
? Number(raw)
: Number.NaN;
if (!Number.isFinite(value)) {
throw new Error(`Invalid bars_1m ${field} value: "${String(raw)}"`);
}
return value;
}
function parseNullableFiniteNumber(raw: unknown, field: string): number | null {
if (raw === null || raw === undefined) {
return null;
}
return parseRequiredFiniteNumber(raw, field);
}
function parseNullableString(raw: unknown, field: string): string | null {
if (raw === null || raw === undefined) {
return null;
}
if (typeof raw === 'string') {
return raw;
}
throw new Error(`Invalid bars_1m ${field} value: expected string or null`);
}
/**
* Read 1-minute bars for a single listing over `[from, to)` ordered by `ts ASC` from `bars_1m`.
*
* Binds `listingId` as its canonical decimal string (`SYMBOL`) and converts returned `listing_id`
* values back to signed `INT32` numbers at the boundary (`design/DATA-CONTRACTS.md` §3.B).
*
* Storage-layer read: preserves `known_at` on each row without applying replay cutoffs.
* Research callers (`MarketDataStore`) remain responsible for as-of availability and Vault fencing.
*/
export async function readBars1m(
client: QuestDBQueryable,
listingId: number,
from: Date | string,
to: Date | string
): Promise<Bar1mRow[]> {
const listingIdParam = formatInt32ListingId(listingId);
const fromIso = toUtcIsoString(from, 'from');
const toIso = toUtcIsoString(to, 'to');
const sql =
'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' +
'FROM bars_1m ' +
'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' +
'ORDER BY ts ASC';
const result = await client.query<Record<string, unknown>>(sql, [listingIdParam, fromIso, toIso]);
return result.rows.map(row => ({
listing_id: parseInt32ListingSymbol(row.listing_id),
open: parseRequiredFiniteNumber(row.open, 'open'),
high: parseRequiredFiniteNumber(row.high, 'high'),
low: parseRequiredFiniteNumber(row.low, 'low'),
close: parseRequiredFiniteNumber(row.close, 'close'),
volume: parseRequiredFiniteNumber(row.volume, 'volume'),
vwap: parseNullableFiniteNumber(row.vwap, 'vwap'),
session: parseNullableString(row.session, 'session'),
source: parseNullableString(row.source, 'source'),
known_at: parseUtcEpochMicros(row.known_at_us, 'known_at'),
ts: parseUtcEpochMicros(row.ts_us, 'ts'),
}));
}
/**
* QuestDB Client for Stock Bot
*
@ -231,72 +409,125 @@ export class QuestDBClient {
}
/**
* Execute a time-series specific query with SAMPLE BY
* Execute a time-series specific query with SAMPLE BY.
* `where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `params`.
*/
async sampleBy<T = QueryResultRow>(
table: TableNames,
table: TableNames | string,
columns: string[],
interval: string,
_timeColumn: string = 'timestamp',
timeColumn: string = 'timestamp',
where?: string,
params?: unknown[]
): Promise<QueryResult<T>> {
const columnsStr = columns.join(', ');
const whereClause = where ? `WHERE ${where}` : '';
const validTable = assertIdentifier(table, 'table name');
if (columns.length === 0) {
throw new Error('SELECT columns cannot be empty');
}
const validColumns = columns.map(col => assertSelectColumn(col));
const validInterval = assertSampleInterval(interval);
assertIdentifier(timeColumn, 'timestamp column');
const sql = `
SELECT ${columnsStr}
FROM ${table}
${whereClause}
SAMPLE BY ${interval}
ALIGN TO CALENDAR
`;
let whereClause = '';
const boundParams = params ? [...params] : [];
if (where !== undefined) {
const validatedWhere = rebaseWhereCondition(where, boundParams, 0);
whereClause = `WHERE ${validatedWhere}`;
} else if (boundParams.length > 0) {
throw new Error('params provided to sampleBy without a where clause');
}
return await this.query<T>(sql, params);
const sql = [
`SELECT ${validColumns.join(', ')}`,
`FROM ${validTable}`,
whereClause,
`SAMPLE BY ${validInterval}`,
'ALIGN TO CALENDAR',
]
.filter(Boolean)
.join(' ');
return await this.query<T>(sql, boundParams.length > 0 ? boundParams : undefined);
}
/**
* Get latest values by symbol using LATEST BY
* Get latest rows per partition key using QuestDB 10.2.0 `LATEST ON`.
* Defaults to `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` otherwise.
* `options.where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `options.params`.
*/
async latestBy<T = QueryResultRow>(
table: TableNames,
table: TableNames | string,
columns: string | string[] = '*',
keyColumns: string | string[] = 'symbol'
keyColumns: string | string[] = 'symbol',
options?: LatestByOptions
): Promise<QueryResult<T>> {
const columnsStr = Array.isArray(columns) ? columns.join(', ') : columns;
const keyColumnsStr = Array.isArray(keyColumns) ? keyColumns.join(', ') : keyColumns;
const cols = Array.isArray(columns) ? columns : [columns];
if (cols.length === 0) {
throw new Error('SELECT columns cannot be empty');
}
const keys = Array.isArray(keyColumns) ? keyColumns : [keyColumns];
const sql = `
SELECT ${columnsStr}
FROM ${table}
LATEST BY ${keyColumnsStr}
`;
const builder = this.queryBuilder().select(...cols).from(table);
return await this.query<T>(sql);
if (options?.where !== undefined) {
builder.where(options.where, options.params);
} else if (options?.params && options.params.length > 0) {
throw new Error('params provided to latestBy without a where clause');
}
if (options?.timestampColumn !== undefined) {
builder.latestOn(options.timestampColumn, ...keys);
} else {
builder.latestBy(...keys);
}
return await builder.execute<T>();
}
/**
* Execute ASOF JOIN for time-series correlation
* Execute ASOF JOIN for time-series correlation.
* `joinCondition` and `where` are treated as trusted SQL fragments.
*/
async asofJoin<T = QueryResultRow>(
leftTable: TableNames,
rightTable: TableNames,
leftTable: TableNames | string,
rightTable: TableNames | string,
joinCondition: string,
columns?: string[],
where?: string,
params?: unknown[]
): Promise<QueryResult<T>> {
const columnsStr = columns ? columns.join(', ') : '*';
const whereClause = where ? `WHERE ${where}` : '';
const validLeft = assertIdentifier(leftTable, 'left table name');
const validRight = assertIdentifier(rightTable, 'right table name');
if (typeof joinCondition !== 'string' || joinCondition.trim().length === 0) {
throw new Error('ASOF JOIN condition must be a non-empty SQL fragment');
}
let columnsStr = '*';
if (columns !== undefined) {
if (columns.length === 0) {
throw new Error('SELECT columns cannot be empty');
}
columnsStr = columns.map(col => assertSelectColumn(col)).join(', ');
}
const sql = `
SELECT ${columnsStr}
FROM ${leftTable}
ASOF JOIN ${rightTable} ON ${joinCondition}
${whereClause}
`;
let whereClause = '';
const boundParams = params ? [...params] : [];
if (where !== undefined) {
const validatedWhere = rebaseWhereCondition(where, boundParams, 0);
whereClause = `WHERE ${validatedWhere}`;
} else if (boundParams.length > 0) {
throw new Error('params provided to asofJoin without a where clause');
}
return await this.query<T>(sql, params);
const sql = [
`SELECT ${columnsStr}`,
`FROM ${validLeft}`,
`ASOF JOIN ${validRight} ON ${joinCondition}`,
whereClause,
]
.filter(Boolean)
.join(' ');
return await this.query<T>(sql, boundParams.length > 0 ? boundParams : undefined);
}
/**
@ -320,9 +551,7 @@ export class QuestDBClient {
* Get table information
*/
async getTableInfo(tableName: string): Promise<QueryResultRow[]> {
const result = await this.query(`SELECT * FROM table_columns WHERE table_name = ?`, [
tableName,
]);
const result = await this.query('SELECT * FROM table_columns($1)', [tableName]);
return result.rows;
}
@ -374,8 +603,9 @@ export class QuestDBClient {
* Optimize table by rebuilding partitions
*/
async optimizeTable(tableName: string): Promise<void> {
await this.query(`VACUUM TABLE ${tableName}`);
this.logger.debug(`Optimized table: ${tableName}`);
const validTable = assertIdentifier(tableName, 'table name');
await this.query(`VACUUM TABLE ${validTable}`);
this.logger.debug(`Optimized table: ${validTable}`);
}
/**
@ -387,14 +617,19 @@ export class QuestDBClient {
partitionBy: string = 'DAY',
timestampColumn: string = 'timestamp'
): Promise<void> {
const validTable = assertIdentifier(tableName, 'table name');
const validTimestamp = assertIdentifier(timestampColumn, 'timestamp column');
if (!ALLOWED_PARTITIONS.has(partitionBy)) {
throw new Error(`Invalid PARTITION BY value: "${String(partitionBy)}"`);
}
const sql = `
CREATE TABLE IF NOT EXISTS ${tableName} (
CREATE TABLE IF NOT EXISTS ${validTable} (
${columns}
) TIMESTAMP(${timestampColumn}) PARTITION BY ${partitionBy}
) TIMESTAMP(${validTimestamp}) PARTITION BY ${partitionBy}
`;
await this.query(sql);
this.logger.info(`Created table: ${tableName}`);
this.logger.info(`Created table: ${validTable}`);
}
/**

View file

@ -5,27 +5,39 @@
* InfluxDB Line Protocol, SQL queries, and PostgreSQL wire protocol.
*/
export { QuestDBClient } from './client';
export { QuestDBClient, readBars1m } from './client';
export { QuestDBHealthMonitor } from './health';
export { QuestDBQueryBuilder } from './query-builder';
export { QuestDBInfluxWriter } from './influx-writer';
export { QuestDBSchemaManager } from './schema';
export {
formatCreateTableSQL,
getM2IntradayDDL,
M2_INTRADAY_SCHEMAS,
QuestDBSchemaManager,
type M2IntradayTableName,
} from './schema';
// Types
export type {
Bar1mRow,
ColumnSchema,
InsertResult,
LatestByOptions,
OHLCVData,
ParameterizedQuery,
PerformanceData,
QueryResult,
QuestDBClientConfig,
QuestDBConnectionOptions,
QuestDBHealthStatus,
QuestDBMetrics,
TableNames,
OHLCVData,
TradeData,
QuestDBQueryable,
QuoteData,
IndicatorData,
PerformanceData,
RiskMetrics,
QueryResult,
InsertResult,
TableNames,
TableSchema,
TradeData,
IndicatorData,
} from './types';
// Note: Factory functions removed - instantiate directly with new QuestDBClient()

View file

@ -1,32 +1,272 @@
import type { QueryResultRow } from 'pg';
import { getLogger } from '@stock-bot/logger';
import type { QueryResult, TableNames, TimeRange } from './types';
import type {
ParameterizedQuery,
QueryResult,
QuestDBQueryable,
TableNames,
TimeRange,
} from './types';
// Interface to avoid circular dependency
interface QuestDBClientInterface {
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
const SAMPLE_INTERVAL_RE = /^\d+[UTsmhdwMy]$/;
/**
* Validate a SQL identifier (table, column, alias, or timestamp column).
*/
export function assertIdentifier(value: string, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_RE.test(value)) {
throw new Error(`Invalid ${label}: "${String(value)}"`);
}
return value;
}
/**
* Validate a projection column (literal `*` or strict SQL identifier).
*/
export function assertSelectColumn(value: string): string {
if (value === '*') {
return value;
}
return assertIdentifier(value, 'SELECT column');
}
/**
* Validate a QuestDB SAMPLE BY interval (e.g. `1m`, `5m`, `1h`, `1d`).
*/
export function assertSampleInterval(value: string): string {
if (typeof value !== 'string' || !SAMPLE_INTERVAL_RE.test(value)) {
throw new Error(`Invalid SAMPLE BY interval: "${String(value)}"`);
}
return value;
}
/**
* Validate a SQL sort direction.
*/
export function assertSortDirection(value: string): 'ASC' | 'DESC' {
if (value !== 'ASC' && value !== 'DESC') {
throw new Error(`Invalid ORDER BY direction: "${String(value)}"`);
}
return value;
}
/**
* Resolve the default designated timestamp column for a QuestDB table.
*/
export function defaultTimestampColumnForTable(table: string): string {
switch (table) {
case 'bars_1m':
case 'fx_1m':
return 'ts';
case 'bar_revisions':
return 'revised_at';
default:
return 'timestamp';
}
}
/**
* Offset fragment-local `$1..$k` placeholders in a trusted SQL WHERE fragment by `offset`.
* Preserves repeated references and ignores `$n` inside single/double quotes and SQL comments.
* Rejects `$0`, out-of-range placeholders, and unused parameters.
*/
export function rebaseWhereCondition(
condition: string,
params: readonly unknown[] = [],
offset: number = 0
): string {
if (typeof condition !== 'string' || condition.trim().length === 0) {
throw new Error('WHERE condition must be a non-empty SQL string');
}
const usedIndices = new Set<number>();
let out = '';
let i = 0;
while (i < condition.length) {
const ch = condition.charAt(i);
const next = condition.charAt(i + 1);
// Single-quoted string literal ('...' with '' escape)
if (ch === "'") {
out += ch;
i += 1;
let closed = false;
while (i < condition.length) {
const cur = condition.charAt(i);
out += cur;
i += 1;
if (cur === "'") {
if (condition.charAt(i) === "'") {
out += "'";
i += 1;
} else {
closed = true;
break;
}
}
}
if (!closed) {
throw new Error('Unterminated string literal in WHERE condition');
}
continue;
}
// Double-quoted identifier ("..." with "" escape)
if (ch === '"') {
out += ch;
i += 1;
let closed = false;
while (i < condition.length) {
const cur = condition.charAt(i);
out += cur;
i += 1;
if (cur === '"') {
if (condition.charAt(i) === '"') {
out += '"';
i += 1;
} else {
closed = true;
break;
}
}
}
if (!closed) {
throw new Error('Unterminated quoted identifier in WHERE condition');
}
continue;
}
// Line comment (-- ... \n); terminate at EOF so subsequent clauses are never swallowed
if (ch === '-' && next === '-') {
out += '--';
i += 2;
let sawNewline = false;
while (i < condition.length) {
const cur = condition.charAt(i);
out += cur;
i += 1;
if (cur === '\n') {
sawNewline = true;
break;
}
}
if (!sawNewline) {
out += '\n';
}
continue;
}
// Block comment (/* ... */)
if (ch === '/' && next === '*') {
out += '/*';
i += 2;
let closed = false;
while (i < condition.length) {
if (condition.charAt(i) === '*' && condition.charAt(i + 1) === '/') {
out += '*/';
i += 2;
closed = true;
break;
}
out += condition.charAt(i);
i += 1;
}
if (!closed) {
throw new Error('Unterminated block comment in WHERE condition');
}
continue;
}
// Parameter placeholder ($1, $2, ..., $10, ...)
if (ch === '$' && next >= '0' && next <= '9') {
const prev = i > 0 ? condition.charAt(i - 1) : '';
const isPartOfIdentifier = /[A-Za-z0-9_]/.test(prev);
if (!isPartOfIdentifier) {
let j = i + 1;
while (j < condition.length) {
const digit = condition.charAt(j);
if (digit < '0' || digit > '9') {
break;
}
j += 1;
}
const digits = condition.slice(i + 1, j);
const index = Number(digits);
if (!Number.isSafeInteger(index) || index < 1) {
throw new Error(`Invalid parameter placeholder $${digits}: placeholders are 1-based`);
}
if (index > params.length) {
throw new Error(
`Parameter placeholder $${index} is out of range for ${params.length} provided parameter(s)`
);
}
usedIndices.add(index);
out += `$${offset + index}`;
i = j;
continue;
}
}
out += ch;
i += 1;
}
for (let idx = 1; idx <= params.length; idx += 1) {
if (!usedIndices.has(idx)) {
throw new Error(`Unused parameter at index ${idx} in WHERE condition`);
}
}
return out;
}
interface WherePredicate {
sql: string;
params: unknown[];
}
interface LatestOnClause {
timestampColumn?: string;
partitionBy: string[];
}
function assertValidDate(value: Date, label: string): Date {
if (!(value instanceof Date) || Number.isNaN(value.getTime())) {
throw new Error(`Invalid ${label}: expected a valid Date`);
}
return value;
}
function assertPositiveInteger(value: number, label: string): number {
if (!Number.isInteger(value) || value <= 0) {
throw new Error(`Invalid ${label}: expected a positive integer, received ${String(value)}`);
}
return value;
}
/**
* QuestDB Query Builder
*
* Provides a fluent interface for building optimized time-series queries
* with support for QuestDB-specific functions and optimizations.
* Provides a fluent interface for building parameterized PGWire time-series queries
* with support for QuestDB 10.2.0 SQL clauses (`LATEST ON`, `SAMPLE BY`).
*/
export class QuestDBQueryBuilder {
private readonly logger: ReturnType<typeof getLogger>;
private query!: {
select: string[];
from: string;
where: string[];
where: WherePredicate[];
groupBy: string[];
orderBy: string[];
limit?: number;
sampleBy?: string;
latestBy?: string[];
latestOn?: LatestOnClause;
timeRange?: TimeRange;
};
constructor(private readonly client: QuestDBClientInterface) {
constructor(private readonly client: QuestDBQueryable) {
this.logger = getLogger('questdb-query-builder');
this.reset();
}
@ -41,193 +281,263 @@ export class QuestDBQueryBuilder {
where: [],
groupBy: [],
orderBy: [],
limit: undefined,
sampleBy: undefined,
latestBy: undefined,
latestOn: undefined,
timeRange: undefined,
};
return this;
}
/**
* Start a new query
*/
public static create(client: QuestDBClientInterface): QuestDBQueryBuilder {
public static create(client: QuestDBQueryable): QuestDBQueryBuilder {
return new QuestDBQueryBuilder(client);
}
/**
* Select columns
* Select columns (`*` or validated SQL identifiers)
*/
public select(...columns: string[]): QuestDBQueryBuilder {
this.query.select.push(...columns);
const validated = columns.map(col => assertSelectColumn(col));
this.query.select.push(...validated);
return this;
}
/**
* Select with aggregation functions
* Select with aggregation functions.
* Aliases are validated as SQL identifiers; aggregation expressions are treated as trusted SQL fragments.
*/
public selectAgg(aggregations: Record<string, string>): QuestDBQueryBuilder {
Object.entries(aggregations).forEach(([alias, expression]) => {
this.query.select.push(`${expression} as ${alias}`);
const validatedEntries = Object.entries(aggregations).map(([alias, expression]) => {
const validAlias = assertIdentifier(alias, 'aggregation alias');
if (typeof expression !== 'string' || expression.trim().length === 0) {
throw new Error(`Invalid aggregation expression for alias "${validAlias}"`);
}
return `${expression} as ${validAlias}`;
});
this.query.select.push(...validatedEntries);
return this;
}
/**
* From table (validated SQL identifier)
*/
public from(table: TableNames | string): QuestDBQueryBuilder {
this.query.from = assertIdentifier(table, 'table name');
return this;
}
/**
* Raw WHERE predicate (trusted SQL fragment escape hatch).
* Supports fragment-local `$1..$n` placeholders, which are renumbered automatically during build.
*/
public where(condition: string, params?: unknown[]): QuestDBQueryBuilder {
const boundParams = params ? [...params] : [];
// Validate fragment syntax and parameter indices eagerly before mutating builder state.
rebaseWhereCondition(condition, boundParams, 0);
this.query.where.push({ sql: condition, params: boundParams });
return this;
}
/**
* Where symbol equals (bound parameter)
*/
public whereSymbol(symbol: string): QuestDBQueryBuilder {
this.query.where.push({ sql: 'symbol = $1', params: [symbol] });
return this;
}
/**
* Where symbols in list (one bound parameter per element; rejects empty lists)
*/
public whereSymbolIn(symbols: string[]): QuestDBQueryBuilder {
if (symbols.length === 0) {
throw new Error('whereSymbolIn requires at least one symbol');
}
const placeholders = symbols.map((_, index) => `$${index + 1}`).join(', ');
this.query.where.push({
sql: `symbol IN (${placeholders})`,
params: [...symbols],
});
return this;
}
/**
* From table
*/
public from(table: TableNames | string): QuestDBQueryBuilder {
this.query.from = table;
return this;
}
/**
* Where condition
*/
public where(condition: string): QuestDBQueryBuilder {
this.query.where.push(condition);
return this;
}
/**
* Where symbol equals
*/
public whereSymbol(symbol: string): QuestDBQueryBuilder {
this.query.where.push(`symbol = '${symbol}'`);
return this;
}
/**
* Where symbols in list
*/
public whereSymbolIn(symbols: string[]): QuestDBQueryBuilder {
const symbolList = symbols.map(s => `'${s}'`).join(', ');
this.query.where.push(`symbol IN (${symbolList})`);
return this;
}
/**
* Where exchange equals
* Where exchange equals (bound parameter)
*/
public whereExchange(exchange: string): QuestDBQueryBuilder {
this.query.where.push(`exchange = '${exchange}'`);
this.query.where.push({ sql: 'exchange = $1', params: [exchange] });
return this;
}
/**
* Time range filter
* Time range filter with inclusive bounds (bound UTC ISO-8601 parameters)
*/
public whereTimeRange(startTime: Date, endTime: Date): QuestDBQueryBuilder {
this.query.timeRange = { startTime, endTime };
this.query.where.push(
`timestamp >= '${startTime.toISOString()}' AND timestamp <= '${endTime.toISOString()}'`
);
const validStart = assertValidDate(startTime, 'startTime');
const validEnd = assertValidDate(endTime, 'endTime');
this.query.timeRange = { startTime: validStart, endTime: validEnd };
this.query.where.push({
sql: 'timestamp >= $1 AND timestamp <= $2',
params: [validStart.toISOString(), validEnd.toISOString()],
});
return this;
}
/**
* Last N hours
* Last N hours (bound negative hour offset)
*/
public whereLastHours(hours: number): QuestDBQueryBuilder {
this.query.where.push(`timestamp > dateadd('h', -${hours}, now())`);
const validHours = assertPositiveInteger(hours, 'hours');
this.query.where.push({
sql: "timestamp > dateadd('h', $1, now())",
params: [-validHours],
});
return this;
}
/**
* Last N days
* Last N days (bound negative day offset)
*/
public whereLastDays(days: number): QuestDBQueryBuilder {
this.query.where.push(`timestamp > dateadd('d', -${days}, now())`);
const validDays = assertPositiveInteger(days, 'days');
this.query.where.push({
sql: "timestamp > dateadd('d', $1, now())",
params: [-validDays],
});
return this;
}
/**
* Group by columns
* Group by columns (validated SQL identifiers)
*/
public groupBy(...columns: string[]): QuestDBQueryBuilder {
this.query.groupBy.push(...columns);
const validated = columns.map(col => assertIdentifier(col, 'GROUP BY column'));
this.query.groupBy.push(...validated);
return this;
}
/**
* Order by column
* Order by column (validated identifier and direction)
*/
public orderBy(column: string, direction: 'ASC' | 'DESC' = 'ASC'): QuestDBQueryBuilder {
this.query.orderBy.push(`${column} ${direction}`);
const validColumn = assertIdentifier(column, 'ORDER BY column');
const validDirection = assertSortDirection(direction);
this.query.orderBy.push(`${validColumn} ${validDirection}`);
return this;
}
/**
* Order by timestamp descending (most recent first)
*/
public orderByTimeDesc(): QuestDBQueryBuilder {
this.query.orderBy.push('timestamp DESC');
public orderByTimeDesc(timestampColumn: string = 'timestamp'): QuestDBQueryBuilder {
const validColumn = assertIdentifier(timestampColumn, 'ORDER BY column');
this.query.orderBy.push(`${validColumn} DESC`);
return this;
}
/**
* Limit results
* Limit results (bound non-negative integer parameter)
*/
public limit(count: number): QuestDBQueryBuilder {
if (!Number.isInteger(count) || count < 0) {
throw new Error(`Invalid LIMIT count: expected a non-negative integer, received ${String(count)}`);
}
this.query.limit = count;
return this;
}
/**
* Sample by time interval (QuestDB specific)
* Sample by time interval (QuestDB specific, validated interval)
*/
public sampleBy(interval: string): QuestDBQueryBuilder {
this.query.sampleBy = interval;
this.query.sampleBy = assertSampleInterval(interval);
return this;
}
/**
* Latest by columns (QuestDB specific)
* QuestDB 10.2.0 `LATEST ON <timestamp> PARTITION BY <keys>` with explicit timestamp column.
*/
public latestBy(...columns: string[]): QuestDBQueryBuilder {
this.query.latestBy = columns;
public latestOn(timestampColumn: string, ...partitionByColumns: string[]): QuestDBQueryBuilder {
const validTs = assertIdentifier(timestampColumn, 'LATEST ON timestamp column');
if (partitionByColumns.length === 0) {
throw new Error('latestOn requires at least one partition column');
}
const validKeys = partitionByColumns.map(col =>
assertIdentifier(col, 'LATEST ON partition column')
);
this.query.latestOn = {
timestampColumn: validTs,
partitionBy: validKeys,
};
return this;
}
/**
* Build and execute the query
* Convenience wrapper emitting `LATEST ON <table default timestamp> PARTITION BY <keys>`.
* Uses `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` for legacy tables.
*/
public latestBy(...partitionByColumns: string[]): QuestDBQueryBuilder {
if (partitionByColumns.length === 0) {
throw new Error('latestBy requires at least one partition column');
}
const validKeys = partitionByColumns.map(col =>
assertIdentifier(col, 'LATEST ON partition column')
);
this.query.latestOn = {
timestampColumn: undefined,
partitionBy: validKeys,
};
return this;
}
/**
* Build and execute the parameterized query
*/
public async execute<T = QueryResultRow>(): Promise<QueryResult<T>> {
const sql = this.build();
this.logger.debug('Executing query', { sql });
let built: ParameterizedQuery | undefined;
try {
const result = await this.client.query<T>(sql);
this.reset(); // Reset for next query
return result;
built = this.buildParameterized();
this.logger.debug('Executing query', { sql: built.sql, paramCount: built.params.length });
return await this.client.query<T>(built.sql, built.params);
} catch (error) {
this.logger.error('Query execution failed', { sql, error });
this.reset(); // Reset even on error
this.logger.error('Query execution failed', { sql: built?.sql, error });
throw error;
} finally {
this.reset();
}
}
/**
* Build the SQL query string
* Build the parameterized SQL query and ordered parameter list (`$1..$n`).
*/
public build(): string {
public buildParameterized(): ParameterizedQuery {
if (!this.query.from) {
throw new Error('FROM clause is required');
}
if (this.query.select.length === 0) {
this.query.select.push('*');
}
const selectColumns = this.query.select.length > 0 ? this.query.select : ['*'];
const params: unknown[] = [];
let sql = `SELECT ${this.query.select.join(', ')} FROM ${this.query.from}`;
let sql = `SELECT ${selectColumns.join(', ')} FROM ${this.query.from}`;
// Add WHERE clause
// Add WHERE clause with consecutively renumbered $1..$n placeholders
if (this.query.where.length > 0) {
sql += ` WHERE ${this.query.where.join(' AND ')}`;
const renderedPredicates = this.query.where.map(predicate => {
const rebased = rebaseWhereCondition(predicate.sql, predicate.params, params.length);
params.push(...predicate.params);
return rebased;
});
sql += ` WHERE ${renderedPredicates.join(' AND ')}`;
}
// Add LATEST BY (QuestDB specific - must come before GROUP BY)
if (this.query.latestBy && this.query.latestBy.length > 0) {
sql += ` LATEST BY ${this.query.latestBy.join(', ')}`;
// Add LATEST ON (QuestDB 10.2.0 - placed after WHERE, before SAMPLE BY / GROUP BY)
if (this.query.latestOn && this.query.latestOn.partitionBy.length > 0) {
const tsColumn =
this.query.latestOn.timestampColumn ?? defaultTimestampColumnForTable(this.query.from);
sql += ` LATEST ON ${tsColumn} PARTITION BY ${this.query.latestOn.partitionBy.join(', ')}`;
}
// Add SAMPLE BY (QuestDB specific)
@ -245,27 +555,36 @@ export class QuestDBQueryBuilder {
sql += ` ORDER BY ${this.query.orderBy.join(', ')}`;
}
// Add LIMIT
if (this.query.limit) {
sql += ` LIMIT ${this.query.limit}`;
// Add LIMIT (bound parameter)
if (this.query.limit !== undefined) {
params.push(this.query.limit);
sql += ` LIMIT $${params.length}`;
}
return sql;
return { sql, params };
}
/**
* Get the built query without executing
* Build the SQL query string (placeholder view of `buildParameterized().sql`)
*/
public build(): string {
return this.buildParameterized().sql;
}
/**
* Get the built query string without executing
*/
public toSQL(): string {
return this.build();
}
// Predefined query methods for common use cases
/**
* Get latest OHLCV data for symbols
*/
public static latestOHLCV(
client: QuestDBClientInterface,
client: QuestDBQueryable,
symbols: string[],
exchange?: string
): QuestDBQueryBuilder {
@ -282,11 +601,12 @@ export class QuestDBQueryBuilder {
return builder;
}
/**
* Get OHLCV data with time sampling
*/
public static ohlcvTimeSeries(
client: QuestDBClientInterface,
client: QuestDBQueryable,
symbol: string,
interval: string,
hours: number = 24
@ -305,11 +625,12 @@ export class QuestDBQueryBuilder {
.sampleBy(interval)
.orderByTimeDesc();
}
/**
* Get market analytics data
*/
public static marketAnalytics(
client: QuestDBClientInterface,
client: QuestDBQueryable,
symbols: string[],
hours: number = 1
): QuestDBQueryBuilder {
@ -329,11 +650,12 @@ export class QuestDBQueryBuilder {
.orderBy('symbol')
.orderByTimeDesc();
}
/**
* Get performance metrics for a time range
*/
public static performanceMetrics(
client: QuestDBClientInterface,
client: QuestDBQueryable,
startTime: Date,
endTime: Date
): QuestDBQueryBuilder {
@ -348,11 +670,12 @@ export class QuestDBQueryBuilder {
.whereTimeRange(startTime, endTime)
.sampleBy('1m');
}
/**
* Get trade execution data
*/
public static tradeExecutions(
client: QuestDBClientInterface,
client: QuestDBQueryable,
symbol?: string,
hours: number = 24
): QuestDBQueryBuilder {

View file

@ -1,11 +1,147 @@
import type { QueryResultRow } from 'pg';
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import type { QueryResult, TableSchema } from './types';
import { assertIdentifier } from './query-builder';
import type { ColumnSchema, QuestDBQueryable, TableSchema } from './types';
// Interface to avoid circular dependency
interface QuestDBClientInterface {
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
export type M2IntradayTableName = 'bars_1m' | 'fx_1m' | 'bar_revisions';
/**
* Contract schemas for M2 QuestDB 10.2.0 intraday tables (`design/DATA-CONTRACTS.md` §3.B).
* Kept opt-in (outside `QuestDBSchemaManager.initializeDatabase()`).
*/
export const M2_INTRADAY_SCHEMAS: Readonly<Record<M2IntradayTableName, TableSchema>> = {
bars_1m: {
tableName: 'bars_1m',
columns: [
{ name: 'listing_id', type: 'SYMBOL', capacity: 65536, cache: false },
{ name: 'open', type: 'DOUBLE' },
{ name: 'high', type: 'DOUBLE' },
{ name: 'low', type: 'DOUBLE' },
{ name: 'close', type: 'DOUBLE' },
{ name: 'volume', type: 'DOUBLE' },
{ name: 'vwap', type: 'DOUBLE' },
{ name: 'session', type: 'SYMBOL', capacity: 8, cache: true },
{ name: 'source', type: 'SYMBOL', capacity: 8, cache: true },
{ name: 'known_at', type: 'TIMESTAMP' },
{ name: 'ts', type: 'TIMESTAMP', designated: true },
],
partitionBy: 'MONTH',
wal: true,
dedupUpsertKeys: ['ts', 'listing_id'],
},
fx_1m: {
tableName: 'fx_1m',
columns: [
{ name: 'pair', type: 'SYMBOL', capacity: 32, cache: true },
{ name: 'open', type: 'DOUBLE' },
{ name: 'high', type: 'DOUBLE' },
{ name: 'low', type: 'DOUBLE' },
{ name: 'close', type: 'DOUBLE' },
{ name: 'source', type: 'SYMBOL', capacity: 8, cache: true },
{ name: 'ts', type: 'TIMESTAMP', designated: true },
],
partitionBy: 'MONTH',
wal: true,
dedupUpsertKeys: ['ts', 'pair'],
},
bar_revisions: {
tableName: 'bar_revisions',
columns: [
{ name: 'listing_id', type: 'SYMBOL', capacity: 65536, cache: false },
{ name: 'timeframe', type: 'SYMBOL', capacity: 8, cache: true },
{ name: 'bar_ts', type: 'TIMESTAMP' },
{ name: 'prev_close', type: 'DOUBLE' },
{ name: 'new_close', type: 'DOUBLE' },
{ name: 'prev_volume', type: 'DOUBLE' },
{ name: 'new_volume', type: 'DOUBLE' },
{ name: 'revised_at', type: 'TIMESTAMP', designated: true },
],
partitionBy: 'MONTH',
wal: true,
},
};
function formatColumnDDL(col: ColumnSchema): string {
const name = assertIdentifier(col.name, 'column name');
let def = `${name} ${col.type}`;
if (col.type === 'SYMBOL') {
if (col.capacity !== undefined) {
if (!Number.isInteger(col.capacity) || col.capacity <= 0) {
throw new Error(
`Invalid SYMBOL capacity for column "${name}": expected positive integer, received ${String(col.capacity)}`
);
}
def += ` CAPACITY ${col.capacity}`;
}
if (col.cache === true) {
def += ' CACHE';
} else if (col.cache === false) {
def += ' NOCACHE';
}
}
return def;
}
/**
* Pure QuestDB CREATE TABLE DDL formatter shared by legacy schemas and M2 contract tables.
*/
export function formatCreateTableSQL(schema: TableSchema): string {
const tableName = assertIdentifier(schema.tableName, 'table name');
if (!schema.columns || schema.columns.length === 0) {
throw new Error('At least one column is required');
}
const columnNames = new Set(schema.columns.map(col => assertIdentifier(col.name, 'column name')));
// QuestDB's column grammar has no PostgreSQL-style NOT NULL constraint.
// nullable remains descriptive metadata; the designated timestamp is declared below.
const columns = schema.columns.map(formatColumnDDL).join(', ');
let sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns})`;
const timestampColumns = schema.columns.filter(col => col.designated);
if (timestampColumns.length > 1) {
throw new Error('Only one designated timestamp column is allowed');
}
const timestampColumn = timestampColumns[0];
if (timestampColumn) {
sql += ` TIMESTAMP(${assertIdentifier(timestampColumn.name, 'designated timestamp column')})`;
}
if (schema.partitionBy) {
sql += ` PARTITION BY ${schema.partitionBy}`;
}
if (schema.wal) {
sql += ' WAL';
}
if (schema.dedupUpsertKeys && schema.dedupUpsertKeys.length > 0) {
const keys = schema.dedupUpsertKeys.map(key => {
const validKey = assertIdentifier(key, 'DEDUP UPSERT key');
if (!columnNames.has(validKey)) {
throw new Error(`DEDUP UPSERT key "${validKey}" does not exist on table "${tableName}"`);
}
return validKey;
});
sql += ` DEDUP UPSERT KEYS(${keys.join(', ')})`;
}
return sql;
}
/**
* Return the QuestDB 10.2.0 DDL statements for `bars_1m`, `fx_1m`, and `bar_revisions`.
* Pure offline helper; requires no database connection.
*/
export function getM2IntradayDDL(): Record<M2IntradayTableName, string> {
return {
bars_1m: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.bars_1m),
fx_1m: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.fx_1m),
bar_revisions: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.bar_revisions),
};
}
/**
@ -17,7 +153,7 @@ interface QuestDBClientInterface {
export class QuestDBSchemaManager {
private readonly logger: ReturnType<typeof getLogger>;
private readonly schemas: Map<string, TableSchema> = new Map();
constructor(private readonly client: QuestDBClientInterface) {
constructor(private readonly client: QuestDBQueryable) {
this.logger = getLogger('questdb-schema-manager');
this.initializeSchemas();
}
@ -195,13 +331,14 @@ export class QuestDBSchemaManager {
* Drop a table
*/
public async dropTable(tableName: string): Promise<void> {
const sql = `DROP TABLE IF EXISTS ${tableName}`;
const validTable = assertIdentifier(tableName, 'table name');
const sql = `DROP TABLE IF EXISTS ${validTable}`;
try {
await this.client.query(sql);
this.logger.warn(`Table ${tableName} dropped`);
this.logger.warn(`Table ${validTable} dropped`);
} catch (error) {
this.logger.error(`Failed to drop table ${tableName}`, error);
this.logger.error(`Failed to drop table ${validTable}`, error);
throw error;
}
}
@ -211,13 +348,12 @@ export class QuestDBSchemaManager {
*/
public async tableExists(tableName: string): Promise<boolean> {
try {
const result = await this.client.query(`
SELECT COUNT(*) as count
FROM information_schema.tables
WHERE table_name = '${tableName}'
`);
const result = await this.client.query<{ count: number | string }>(
'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1',
[tableName]
);
return result.rows.length > 0 && at(result.rows, 0).count > 0;
return result.rows.length > 0 && Number(at(result.rows, 0).count) > 0;
} catch (error) {
this.logger.error(`Error checking if table exists: ${tableName}`, error);
return false;
@ -269,18 +405,19 @@ export class QuestDBSchemaManager {
* Get table statistics
*/
public async getTableStats(tableName: string): Promise<QueryResultRow | undefined> {
const validTable = assertIdentifier(tableName, 'table name');
try {
const result = await this.client.query(`
SELECT
COUNT(*) as row_count,
MIN(timestamp) as min_timestamp,
MAX(timestamp) as max_timestamp
FROM ${tableName}
FROM ${validTable}
`);
return result.rows[0] || {};
} catch (error) {
this.logger.error(`Failed to get table stats for ${tableName}`, error);
this.logger.error(`Failed to get table stats for ${validTable}`, error);
throw error;
}
}
@ -289,11 +426,12 @@ export class QuestDBSchemaManager {
* Truncate table (remove all data but keep structure)
*/
public async truncateTable(tableName: string): Promise<void> {
const validTable = assertIdentifier(tableName, 'table name');
try {
await this.client.query(`TRUNCATE TABLE ${tableName}`);
this.logger.warn(`Table ${tableName} truncated`);
await this.client.query(`TRUNCATE TABLE ${validTable}`);
this.logger.warn(`Table ${validTable} truncated`);
} catch (error) {
this.logger.error(`Failed to truncate table ${tableName}`, error);
this.logger.error(`Failed to truncate table ${validTable}`, error);
throw error;
}
}
@ -311,27 +449,7 @@ export class QuestDBSchemaManager {
* Build CREATE TABLE SQL statement
*/
private buildCreateTableSQL(schema: TableSchema): string {
// QuestDB's column grammar has no PostgreSQL-style NOT NULL constraint.
// nullable remains descriptive metadata; the designated timestamp is declared
// below. See https://questdb.com/docs/query/sql/create-table/.
const columns = schema.columns
.map(col => `${col.name} ${col.type}`)
.join(', ');
let sql = `CREATE TABLE IF NOT EXISTS ${schema.tableName} (${columns})`;
// Add designated timestamp
const timestampColumn = schema.columns.find(col => col.designated);
if (timestampColumn) {
sql += ` TIMESTAMP(${timestampColumn.name})`;
}
// Add partition by
if (schema.partitionBy) {
sql += ` PARTITION BY ${schema.partitionBy}`;
}
return sql;
return formatCreateTableSQL(schema);
}
/**

View file

@ -62,7 +62,54 @@ export type TableNames =
| 'risk_metrics'
| 'market_events'
| 'strategy_signals'
| 'portfolio_snapshots';
| 'portfolio_snapshots'
| 'bars_1m'
| 'fx_1m'
| 'bar_revisions';
/**
* Shared minimal query executor interface for QuestDB helpers.
*/
export interface QuestDBQueryable {
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
}
/**
* Parameterized PGWire SQL query and ordered bound parameters ($1..$n).
*/
export interface ParameterizedQuery {
sql: string;
params: unknown[];
}
/**
* Options for QuestDBClient.latestBy().
*/
export interface LatestByOptions {
timestampColumn?: string;
where?: string;
params?: unknown[];
}
/**
* Typed 1-minute bar row returned from QuestDB `bars_1m`.
* - `listing_id` is stored as decimal string SYMBOL in QuestDB and converted to INT32 at read boundary.
* - `known_at` and `ts` are lossless UTC epoch microseconds (`bigint`) projected via `CAST(... AS LONG)`
* to preserve all 6 fractional digits and avoid PGWire local-timezone `Date` coercion.
*/
export interface Bar1mRow {
listing_id: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
vwap: number | null;
session: string | null;
source: string | null;
known_at: bigint;
ts: bigint;
}
/**
* Time-Series Data Types
@ -214,12 +261,14 @@ export interface TableSchema {
tableName: string;
columns: ColumnSchema[];
partitionBy?: 'NONE' | 'HOUR' | 'DAY' | 'MONTH' | 'YEAR';
wal?: boolean;
dedupUpsertKeys?: string[];
orderBy?: string[];
indices?: IndexDefinition[];
dedup?: boolean;
}
interface ColumnSchema {
export interface ColumnSchema {
name: string;
type:
| 'SYMBOL'
@ -235,6 +284,7 @@ interface ColumnSchema {
nullable?: boolean;
designated?: boolean; // For designated timestamp column
capacity?: number; // For SYMBOL type
cache?: boolean; // For SYMBOL type: true -> CACHE, false -> NOCACHE
indexed?: boolean;
}

View file

@ -0,0 +1,305 @@
import { describe, expect, it } from 'bun:test';
import type { QueryResultRow } from 'pg';
import {
formatCreateTableSQL,
QuestDBClient,
QuestDBQueryBuilder,
QuestDBSchemaManager,
readBars1m,
type QueryResult,
type QuestDBQueryable,
} from '../src';
interface RecordedQuery {
sql: string;
params: unknown[] | undefined;
}
class RecordingClient implements QuestDBQueryable {
public readonly calls: RecordedQuery[] = [];
public async query<T = QueryResultRow>(
sql: string,
params?: unknown[]
): Promise<QueryResult<T>> {
this.calls.push({ sql, params });
return { rows: [] as T[], rowCount: 0, executionTime: 0 };
}
}
function clientRoutedTo(fake: RecordingClient): QuestDBClient {
const client = new QuestDBClient(
{ host: 'questdb.test.local', httpPort: 9000, pgPort: 8812, influxPort: 9009, database: 'qdb' },
{ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }
);
(client as unknown as { query: QuestDBQueryable['query'] }).query = fake.query.bind(fake);
return client;
}
describe('QuestDB query layer edge cases (QA)', () => {
describe('predefined builders', () => {
it('latestOHLCV binds symbols and exchange and emits LATEST ON timestamp after WHERE', () => {
const fake = new RecordingClient();
const hostile = "AAPL' OR '1'='1";
const { sql, params } = QuestDBQueryBuilder.latestOHLCV(
fake,
[hostile, 'MSFT'],
'NASDAQ'
).buildParameterized();
expect(sql).toBe(
'SELECT symbol, timestamp, open, high, low, close, volume FROM ohlcv_data ' +
'WHERE symbol IN ($1, $2) AND exchange = $3 ' +
'LATEST ON timestamp PARTITION BY symbol ORDER BY timestamp DESC'
);
expect(params).toEqual([hostile, 'MSFT', 'NASDAQ']);
expect(sql).not.toContain(hostile);
});
it('ohlcvTimeSeries and tradeExecutions bind values in placeholder order', () => {
const fake = new RecordingClient();
const series = QuestDBQueryBuilder.ohlcvTimeSeries(fake, 'AAPL', '5m', 12).buildParameterized();
expect(series.sql).toBe(
'SELECT first(open) as first_open, max(high) as max_high, min(low) as min_low, ' +
'last(close) as last_close, sum(volume) as sum_volume FROM ohlcv_data ' +
"WHERE symbol = $1 AND timestamp > dateadd('h', $2, now()) SAMPLE BY 5m ORDER BY timestamp DESC"
);
expect(series.params).toEqual(['AAPL', -12]);
const trades = QuestDBQueryBuilder.tradeExecutions(fake, 'AAPL', 3).buildParameterized();
expect(trades.sql).toBe(
'SELECT symbol, timestamp, side, quantity, price, execution_time FROM trade_executions ' +
"WHERE timestamp > dateadd('h', $1, now()) AND symbol = $2 ORDER BY timestamp DESC"
);
expect(trades.params).toEqual([-3, 'AAPL']);
});
it('ohlcvTimeSeries rejects a hostile SAMPLE BY interval at build time', () => {
const fake = new RecordingClient();
expect(() => QuestDBQueryBuilder.ohlcvTimeSeries(fake, 'AAPL', '1h; DROP TABLE x')).toThrow(
/Invalid SAMPLE BY interval/
);
expect(fake.calls).toHaveLength(0);
});
});
describe('builder input validation', () => {
it('binds LIMIT 0 instead of silently dropping it and rejects negative or fractional limits', () => {
const fake = new RecordingClient();
expect(QuestDBQueryBuilder.create(fake).from('t').limit(0).buildParameterized()).toEqual({
sql: 'SELECT * FROM t LIMIT $1',
params: [0],
});
expect(() => QuestDBQueryBuilder.create(fake).limit(-1)).toThrow(/LIMIT/);
expect(() => QuestDBQueryBuilder.create(fake).limit(1.5)).toThrow(/LIMIT/);
});
it('rejects non-positive relative windows and invalid dates', () => {
const fake = new RecordingClient();
expect(() => QuestDBQueryBuilder.create(fake).whereLastHours(0)).toThrow(/hours/);
expect(() => QuestDBQueryBuilder.create(fake).whereLastDays(-2)).toThrow(/days/);
expect(() =>
QuestDBQueryBuilder.create(fake).whereTimeRange(new Date('nope'), new Date())
).toThrow(/startTime/);
});
it('rejects unterminated quotes and block comments in raw where() before mutating state', () => {
const fake = new RecordingClient();
const builder = QuestDBQueryBuilder.create(fake).from('bars_1m');
expect(() => builder.where("session = 'RTH", [])).toThrow(/Unterminated string/);
expect(() => builder.where('"session = $1', ['RTH'])).toThrow(/Unterminated quoted/);
expect(() => builder.where('session = $1 /* open', ['RTH'])).toThrow(/Unterminated block/);
// Rejected fragments must not leak into the next build.
expect(builder.where('session = $1', ['RTH']).buildParameterized()).toEqual({
sql: 'SELECT * FROM bars_1m WHERE session = $1',
params: ['RTH'],
});
});
it('keeps doubled quotes inside literals and still rebases the following placeholder', () => {
const fake = new RecordingClient();
const { sql, params } = QuestDBQueryBuilder.create(fake)
.from('bars_1m')
.whereSymbol('X')
.where("note = 'it''s $1' AND close > $1", [10])
.buildParameterized();
expect(sql).toBe("SELECT * FROM bars_1m WHERE symbol = $1 AND note = 'it''s $1' AND close > $2");
expect(params).toEqual(['X', 10]);
});
});
describe('QuestDBClient helpers', () => {
it('reject params without a where fragment before sending a query', async () => {
const fake = new RecordingClient();
const client = clientRoutedTo(fake);
await expect(
client.sampleBy('bars_1m', ['ts', 'close'], '1h', 'ts', undefined, ['RTH'])
).rejects.toThrow(/without a where/);
await expect(
client.asofJoin('bars_1m', 'fx_1m', 'bars_1m.ts = fx_1m.ts', undefined, undefined, [1])
).rejects.toThrow(/without a where/);
await expect(
client.latestBy('bars_1m', '*', 'listing_id', { params: ['RTH'] })
).rejects.toThrow(/without a where/);
await expect(client.sampleBy('bars_1m', ['ts'], '1h', 'ts; --')).rejects.toThrow(
/Invalid timestamp column/
);
await expect(
client.createTable('bars_1m', 'ts TIMESTAMP', 'DAY; DROP TABLE x', 'ts')
).rejects.toThrow(/PARTITION BY/);
await expect(client.optimizeTable('bars_1m; DROP TABLE x')).rejects.toThrow(
/Invalid table name/
);
expect(fake.calls).toHaveLength(0);
});
it('asofJoin binds where params and keeps SQL on validated identifiers', async () => {
const fake = new RecordingClient();
const client = clientRoutedTo(fake);
await client.asofJoin(
'bars_1m',
'fx_1m',
'bars_1m.ts = fx_1m.ts',
['close'],
'listing_id = $1 AND pair = $2',
['1042', 'USDCAD']
);
expect(fake.calls).toEqual([
{
sql:
'SELECT close FROM bars_1m ASOF JOIN fx_1m ON bars_1m.ts = fx_1m.ts ' +
'WHERE listing_id = $1 AND pair = $2',
params: ['1042', 'USDCAD'],
},
]);
});
});
describe('schema DDL', () => {
it('leaves legacy startup DDL unchanged (no CAPACITY, CACHE, WAL or DEDUP)', async () => {
const fake = new RecordingClient();
await new QuestDBSchemaManager(fake).createAllTables();
const ddl = fake.calls.map(call => call.sql);
expect(ddl).toHaveLength(6);
expect(ddl[0]).toBe(
'CREATE TABLE IF NOT EXISTS ohlcv_data (symbol SYMBOL, exchange SYMBOL, timestamp TIMESTAMP, ' +
'open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume LONG, data_source SYMBOL) ' +
'TIMESTAMP(timestamp) PARTITION BY DAY'
);
for (const statement of ddl) {
expect(statement).not.toMatch(/CAPACITY|CACHE|WAL|DEDUP|bars_1m|fx_1m|bar_revisions/);
}
});
it('formatCreateTableSQL rejects hostile identifiers, bad capacities and multiple designated timestamps', () => {
expect(() =>
formatCreateTableSQL({
tableName: 'bars_1m; DROP TABLE x',
columns: [{ name: 'ts', type: 'TIMESTAMP', designated: true }],
})
).toThrow(/Invalid table name/);
expect(() =>
formatCreateTableSQL({
tableName: 't',
columns: [{ name: 'ts TIMESTAMP); --', type: 'TIMESTAMP' }],
})
).toThrow(/Invalid column name/);
expect(() =>
formatCreateTableSQL({
tableName: 't',
columns: [{ name: 's', type: 'SYMBOL', capacity: 0 }],
})
).toThrow(/capacity/);
expect(() =>
formatCreateTableSQL({
tableName: 't',
columns: [
{ name: 'a', type: 'TIMESTAMP', designated: true },
{ name: 'b', type: 'TIMESTAMP', designated: true },
],
})
).toThrow(/Only one designated/);
});
});
describe('readBars1m bound normalisation', () => {
it('converts offset bounds to UTC with fractional digits intact, across a day boundary', async () => {
const fake = new RecordingClient();
await readBars1m(fake, -0, '2024-01-01T23:30:00.5-05:00', '2024-01-02T09:30:00.000123+05:30');
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]?.params).toEqual([
'0',
'2024-01-02T04:30:00.5Z',
'2024-01-02T04:00:00.000123Z',
]);
});
it('binds negative INT32 listing ids and parses negative SYMBOL values back', async () => {
const fake = new RecordingClient();
(fake as unknown as { query: QuestDBQueryable['query'] }).query = async <T,>(
sql: string,
params?: unknown[]
) => {
fake.calls.push({ sql, params });
return {
rows: [
{
listing_id: '-2147483648',
open: 1,
high: 1,
low: 1,
close: 1,
volume: 1,
vwap: null,
session: null,
source: null,
known_at_us: '1704205800000000',
ts_us: '1704205800000000',
},
] as T[],
rowCount: 1,
executionTime: 0,
};
};
const rows = await readBars1m(
fake,
-2147483648,
'2024-01-02T14:30:00Z',
'2024-01-02T14:31:00Z'
);
expect(fake.calls[0]?.params?.[0]).toBe('-2147483648');
expect(rows[0]?.listing_id).toBe(-2147483648);
expect(rows[0]?.vwap).toBeNull();
});
it('rejects impossible calendar dates, out-of-range offsets and NaN dates before querying', async () => {
const fake = new RecordingClient();
const to = '2024-03-01T00:00:00Z';
await expect(readBars1m(fake, 1, '2024-02-30T00:00:00Z', to)).rejects.toThrow(/calendar/);
await expect(readBars1m(fake, 1, '2024-02-01T00:00:00+24:00', to)).rejects.toThrow(
/offset/
);
await expect(readBars1m(fake, 1, new Date('nope'), to)).rejects.toThrow(/NaN/);
await expect(readBars1m(fake, 1, '2024-02-01T00:00:00.1234567Z', to)).rejects.toThrow(
/timezone/
);
expect(fake.calls).toHaveLength(0);
});
});
});

View file

@ -0,0 +1,658 @@
import { describe, expect, it } from 'bun:test';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { QueryResultRow } from 'pg';
import {
formatCreateTableSQL,
getM2IntradayDDL,
QuestDBClient,
QuestDBQueryBuilder,
QuestDBSchemaManager,
readBars1m,
type QueryResult,
type QuestDBQueryable,
} from '../src';
interface RecordedQuery {
sql: string;
params: unknown[] | undefined;
}
class FakeQuestDBClient implements QuestDBQueryable {
public readonly calls: RecordedQuery[] = [];
private nextRows: unknown[] = [];
private nextError: Error | null = null;
public setRows(rows: unknown[]): void {
this.nextRows = rows;
}
public failNext(error: Error): void {
this.nextError = error;
}
public async query<T = QueryResultRow>(
sql: string,
params?: unknown[]
): Promise<QueryResult<T>> {
this.calls.push({ sql, params });
if (this.nextError) {
const err = this.nextError;
this.nextError = null;
throw err;
}
return {
rows: this.nextRows as T[],
rowCount: this.nextRows.length,
executionTime: 1,
};
}
}
function createClientWithFakeQuery(fake: FakeQuestDBClient): QuestDBClient {
const client = new QuestDBClient(
{
host: 'questdb.test.local',
httpPort: 9000,
pgPort: 8812,
influxPort: 9009,
database: 'qdb',
},
{
info: () => {},
warn: () => {},
error: () => {},
debug: () => {},
}
);
// Route PGWire query execution to the recording fake without opening a network socket.
(client as unknown as { query: QuestDBQueryable['query'] }).query = fake.query.bind(fake);
return client;
}
function normalizeSql(sql: string): string {
return sql
.replace(/--[^\n]*/g, '')
.replace(/;/g, '')
.replace(/\s+/g, ' ')
.replace(/\(\s+/g, '(')
.replace(/\s+\)/g, ')')
.replace(/\s+,/g, ',')
.trim();
}
describe('QuestDB 10.2.0 query layer', () => {
describe('LATEST ON clause generation', () => {
it('emits LATEST ON after WHERE with explicit timestamp and partition key', async () => {
const fake = new FakeQuestDBClient();
const builder = QuestDBQueryBuilder.create(fake)
.select('listing_id', 'ts', 'close')
.from('bars_1m')
.where('listing_id = $1', ['1042'])
.latestOn('ts', 'listing_id');
const built = builder.buildParameterized();
expect(built.sql).toBe(
'SELECT listing_id, ts, close FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id'
);
expect(built.params).toEqual(['1042']);
expect(builder.build()).toBe(built.sql);
expect(builder.toSQL()).toBe(built.sql);
await builder.execute();
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]).toEqual({
sql: built.sql,
params: ['1042'],
});
});
it('preserves multi-key PARTITION BY ordering', () => {
const fake = new FakeQuestDBClient();
const sql = QuestDBQueryBuilder.create(fake)
.select('listing_id', 'session', 'ts', 'close')
.from('bars_1m')
.latestOn('ts', 'listing_id', 'session')
.build();
expect(sql).toBe(
'SELECT listing_id, session, ts, close FROM bars_1m LATEST ON ts PARTITION BY listing_id, session'
);
});
it('resolves table-appropriate default timestamps for latestBy()', () => {
const fake = new FakeQuestDBClient();
expect(QuestDBQueryBuilder.create(fake).from('bars_1m').latestBy('listing_id').build()).toBe(
'SELECT * FROM bars_1m LATEST ON ts PARTITION BY listing_id'
);
expect(QuestDBQueryBuilder.create(fake).from('fx_1m').latestBy('pair').build()).toBe(
'SELECT * FROM fx_1m LATEST ON ts PARTITION BY pair'
);
expect(
QuestDBQueryBuilder.create(fake).from('bar_revisions').latestBy('listing_id').build()
).toBe('SELECT * FROM bar_revisions LATEST ON revised_at PARTITION BY listing_id');
expect(QuestDBQueryBuilder.create(fake).from('ohlcv_data').latestBy('symbol').build()).toBe(
'SELECT * FROM ohlcv_data LATEST ON timestamp PARTITION BY symbol'
);
});
it('routes QuestDBClient.latestBy() through the builder with timestamp override and bound filters', async () => {
const fake = new FakeQuestDBClient();
const client = createClientWithFakeQuery(fake);
await client.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', {
where: 'session = $1',
params: ['RTH'],
});
await client.latestBy('bar_revisions', '*', ['listing_id', 'timeframe']);
await client.latestBy('bars_1m', 'close', 'listing_id', {
timestampColumn: 'known_at',
});
expect(fake.calls).toEqual([
{
sql: 'SELECT listing_id, ts, close FROM bars_1m WHERE session = $1 LATEST ON ts PARTITION BY listing_id',
params: ['RTH'],
},
{
sql: 'SELECT * FROM bar_revisions LATEST ON revised_at PARTITION BY listing_id, timeframe',
params: [],
},
{
sql: 'SELECT close FROM bars_1m LATEST ON known_at PARTITION BY listing_id',
params: [],
},
]);
});
});
describe('parameterized predicates and placeholder renumbering', () => {
it('binds all filter values and keeps hostile input out of SQL', () => {
const fake = new FakeQuestDBClient();
const hostile = "x' OR '1'='1";
const start = new Date('2024-01-02T14:30:00.000Z');
const end = new Date('2024-01-02T15:30:00.000Z');
const { sql, params } = QuestDBQueryBuilder.create(fake)
.select('symbol', 'exchange', 'timestamp', 'close')
.from('ohlcv_data')
.whereSymbol(hostile)
.whereSymbolIn(['AAPL', 'MSFT'])
.whereExchange('NASDAQ')
.whereTimeRange(start, end)
.whereLastHours(6)
.whereLastDays(2)
.limit(25)
.buildParameterized();
expect(sql).toBe(
'SELECT symbol, exchange, timestamp, close FROM ohlcv_data ' +
"WHERE symbol = $1 AND symbol IN ($2, $3) AND exchange = $4 AND timestamp >= $5 AND timestamp <= $6 AND timestamp > dateadd('h', $7, now()) AND timestamp > dateadd('d', $8, now()) " +
'LIMIT $9'
);
expect(sql).not.toContain(hostile);
expect(sql).not.toContain('AAPL');
expect(sql).not.toContain('NASDAQ');
expect(params).toEqual([
hostile,
'AAPL',
'MSFT',
'NASDAQ',
'2024-01-02T14:30:00.000Z',
'2024-01-02T15:30:00.000Z',
-6,
-2,
25,
]);
});
it('renumbers raw where() fragments consecutively across repeated, multi-digit, quoted, and commented placeholders', () => {
const fake = new FakeQuestDBClient();
const tenParams = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p10'];
const tenPred =
'c1=$1 AND c2=$2 AND c3=$3 AND c4=$4 AND c5=$5 AND c6=$6 AND c7=$7 AND c8=$8 AND c9=$9 AND c10=$10';
const { sql, params } = QuestDBQueryBuilder.create(fake)
.from('ohlcv_data')
.limit(10)
.whereSymbol('SPY')
.where(
"note = '$1' AND \"col_$2\" = $1 AND close >= $1 -- ignore $3\n/* ignore $4 */ AND volume > $2",
[100.5, 5000]
)
.where(tenPred, tenParams)
.buildParameterized();
expect(sql).toBe(
'SELECT * FROM ohlcv_data WHERE symbol = $1 ' +
'AND note = \'$1\' AND "col_$2" = $2 AND close >= $2 -- ignore $3\n/* ignore $4 */ AND volume > $3 ' +
'AND c1=$4 AND c2=$5 AND c3=$6 AND c4=$7 AND c5=$8 AND c6=$9 AND c7=$10 AND c8=$11 AND c9=$12 AND c10=$13 ' +
'LIMIT $14'
);
expect(params).toHaveLength(14);
expect(params).toEqual(['SPY', 100.5, 5000, ...tenParams, 10]);
});
it('rejects empty IN lists and malformed/mismatched where() placeholders before querying', () => {
const fake = new FakeQuestDBClient();
expect(() => QuestDBQueryBuilder.create(fake).whereSymbolIn([])).toThrow(
/at least one symbol/i
);
expect(() => QuestDBQueryBuilder.create(fake).where('close > $0', [1])).toThrow(/1-based/i);
expect(() => QuestDBQueryBuilder.create(fake).where('close > $2', [1])).toThrow(
/out of range/i
);
expect(() => QuestDBQueryBuilder.create(fake).where('close > $1', [1, 2])).toThrow(
/Unused parameter/i
);
expect(() => QuestDBQueryBuilder.create(fake).where('close > 10', [1])).toThrow(
/Unused parameter/i
);
expect(() => QuestDBQueryBuilder.create(fake).where(' ')).toThrow(/non-empty/i);
expect(fake.calls).toHaveLength(0);
});
it('resets builder cleanly for reuse after execution and after rejection', async () => {
const fake = new FakeQuestDBClient();
const builder = QuestDBQueryBuilder.create(fake);
fake.failNext(new Error('simulated wire failure'));
await expect(builder.from('ohlcv_data').whereSymbol('AAPL').execute()).rejects.toThrow(
'simulated wire failure'
);
// Builder must be reset after failed execute()
const nextBuilt = builder.select('close').from('bars_1m').where('listing_id = $1', ['7']).buildParameterized();
expect(nextBuilt).toEqual({
sql: 'SELECT close FROM bars_1m WHERE listing_id = $1',
params: ['7'],
});
await builder.execute();
expect(fake.calls).toHaveLength(2);
expect(fake.calls[1]).toEqual(nextBuilt);
// Builder is reset again after successful execute()
expect(() => builder.build()).toThrow('FROM clause is required');
});
it('terminates trailing line comments with a newline before subsequent predicates, LATEST ON, and SAMPLE BY', async () => {
const fake = new FakeQuestDBClient();
const client = createClientWithFakeQuery(fake);
const builderResult = QuestDBQueryBuilder.create(fake)
.select('listing_id', 'ts', 'close')
.from('bars_1m')
.where('session = $1 -- regular session', ['RTH'])
.where('close > $1 -- minimum price', [100])
.latestOn('ts', 'listing_id')
.buildParameterized();
expect(builderResult.sql).toBe(
'SELECT listing_id, ts, close FROM bars_1m ' +
'WHERE session = $1 -- regular session\n ' +
'AND close > $2 -- minimum price\n ' +
'LATEST ON ts PARTITION BY listing_id'
);
expect(builderResult.params).toEqual(['RTH', 100]);
await client.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', {
where: 'session = $1 -- regular session',
params: ['RTH'],
});
await client.sampleBy(
'bars_1m',
['ts', 'close'],
'1h',
'ts',
'session = $1 -- regular session',
['RTH']
);
expect(fake.calls).toEqual([
{
sql:
'SELECT listing_id, ts, close FROM bars_1m ' +
'WHERE session = $1 -- regular session\n ' +
'LATEST ON ts PARTITION BY listing_id',
params: ['RTH'],
},
{
sql:
'SELECT ts, close FROM bars_1m ' +
'WHERE session = $1 -- regular session\n ' +
'SAMPLE BY 1h ALIGN TO CALENDAR',
params: ['RTH'],
},
]);
});
});
describe('identifier and interval validation', () => {
it('rejects hostile table, column, alias, latestOn, sort, and sampleBy inputs before querying', async () => {
const fake = new FakeQuestDBClient();
const client = createClientWithFakeQuery(fake);
expect(() => QuestDBQueryBuilder.create(fake).from('bars_1m; DROP TABLE x')).toThrow(
/Invalid table name/i
);
expect(() => QuestDBQueryBuilder.create(fake).select('close; --')).toThrow(
/Invalid SELECT column/i
);
expect(() =>
QuestDBQueryBuilder.create(fake).selectAgg({ 'bad alias': 'avg(close)' })
).toThrow(/Invalid aggregation alias/i);
expect(() => QuestDBQueryBuilder.create(fake).latestOn('ts; --', 'listing_id')).toThrow(
/Invalid LATEST ON timestamp column/i
);
expect(() => QuestDBQueryBuilder.create(fake).latestOn('ts', 'listing_id; DROP')).toThrow(
/Invalid LATEST ON partition column/i
);
expect(() => QuestDBQueryBuilder.create(fake).orderBy('ts', 'UP' as 'ASC')).toThrow(
/Invalid ORDER BY direction/i
);
expect(() => QuestDBQueryBuilder.create(fake).sampleBy('1h; DROP TABLE x')).toThrow(
/Invalid SAMPLE BY interval/i
);
expect(() => QuestDBQueryBuilder.create(fake).sampleBy('1x')).toThrow(
/Invalid SAMPLE BY interval/i
);
await expect(
client.sampleBy('bars_1m', ['ts', 'close'], 'bad_interval')
).rejects.toThrow(/Invalid SAMPLE BY interval/i);
await expect(
client.latestBy('bars_1m; DROP TABLE x', '*', 'listing_id')
).rejects.toThrow(/Invalid table name/i);
await expect(
client.asofJoin('bars_1m', 'fx_1m; DROP', 'bars_1m.ts = fx_1m.ts')
).rejects.toThrow(/Invalid right table name/i);
expect(fake.calls).toHaveLength(0);
});
it('binds table name in QuestDBSchemaManager.tableExists() via tables()', async () => {
const fake = new FakeQuestDBClient();
fake.setRows([{ count: 1 }]);
const manager = new QuestDBSchemaManager(fake);
const hostileTable = "bars_1m' OR '1'='1";
const exists = await manager.tableExists(hostileTable);
expect(exists).toBe(true);
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]).toEqual({
sql: 'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1',
params: [hostileTable],
});
});
it('binds table name in QuestDBClient.getTableInfo() via table_columns($1)', async () => {
const fake = new FakeQuestDBClient();
const client = createClientWithFakeQuery(fake);
fake.setRows([{ column: 'ts', type: 'TIMESTAMP' }]);
const rows = await client.getTableInfo('bars_1m');
expect(rows).toEqual([{ column: 'ts', type: 'TIMESTAMP' }]);
expect(fake.calls).toEqual([
{
sql: 'SELECT * FROM table_columns($1)',
params: ['bars_1m'],
},
]);
});
});
describe('M2 intraday contract DDL', () => {
it('matches design/DATA-CONTRACTS.md §3.B exactly after whitespace and comment normalization', () => {
const contractPath = resolve(import.meta.dir, '../../../../design/DATA-CONTRACTS.md');
const contractDoc = readFileSync(contractPath, 'utf8');
const sectionMatch = contractDoc.match(
/### B\. QuestDB `10\.2\.0`[\s\S]*?```sql\n([\s\S]*?)```/
);
expect(sectionMatch).not.toBeNull();
const contractStatements = sectionMatch![1]!
.split(';')
.map(normalizeSql)
.filter(Boolean);
expect(contractStatements).toHaveLength(3);
const generated = getM2IntradayDDL();
expect(normalizeSql(generated.bars_1m)).toBe(contractStatements[0]!);
expect(normalizeSql(generated.fx_1m)).toBe(contractStatements[1]!);
expect(normalizeSql(generated.bar_revisions)).toBe(contractStatements[2]!);
expect(generated.bars_1m).toContain('listing_id SYMBOL CAPACITY 65536 NOCACHE');
expect(generated.bars_1m).toContain('session SYMBOL CAPACITY 8 CACHE');
expect(generated.bars_1m).toContain('source SYMBOL CAPACITY 8 CACHE');
expect(generated.bars_1m).toContain('TIMESTAMP(ts) PARTITION BY MONTH WAL');
expect(generated.bars_1m).toContain('DEDUP UPSERT KEYS(ts, listing_id)');
expect(generated.fx_1m).toContain('pair SYMBOL CAPACITY 32 CACHE');
expect(generated.fx_1m).toContain('TIMESTAMP(ts) PARTITION BY MONTH WAL');
expect(generated.fx_1m).toContain('DEDUP UPSERT KEYS(ts, pair)');
expect(generated.bar_revisions).toContain('listing_id SYMBOL CAPACITY 65536 NOCACHE');
expect(generated.bar_revisions).toContain('TIMESTAMP(revised_at) PARTITION BY MONTH WAL');
expect(generated.bar_revisions).not.toContain('DEDUP');
});
it('keeps M2 intraday tables opt-in outside legacy startup initialization', () => {
const fake = new FakeQuestDBClient();
const manager = new QuestDBSchemaManager(fake);
const startupNames = manager.getSchemaNames();
expect(startupNames).not.toContain('bars_1m');
expect(startupNames).not.toContain('fx_1m');
expect(startupNames).not.toContain('bar_revisions');
// Shared formatter also validates dedup keys exist on the table
expect(() =>
formatCreateTableSQL({
tableName: 'bad_table',
columns: [{ name: 'ts', type: 'TIMESTAMP', designated: true }],
dedupUpsertKeys: ['ts', 'missing_col'],
})
).toThrow(/does not exist/i);
});
});
describe('readBars1m storage reader', () => {
it('sends one parameterized [from, to) query with UTC epoch-microsecond projection and converts listing_id to INT32', async () => {
const fake = new FakeQuestDBClient();
// 2024-01-02T14:30:00.000000Z = 1704205800000000 us
// 2024-01-02T14:31:00.000700Z = 1704205860000700 us (6 fractional digits preserved)
// 2024-01-02T14:31:00.000000Z = 1704205860000000 us
// 2024-01-02T14:32:00.123456Z = 1704205920123456 us
const fixtureRows = [
{
listing_id: '1042',
open: 185.1,
high: 185.5,
low: 184.9,
close: 185.4,
volume: 12500,
vwap: 185.28,
session: 'RTH',
source: 'eod_unadj',
known_at_us: '1704205860000700',
ts_us: '1704205800000000',
},
{
listing_id: '1042',
open: 185.4,
high: 185.6,
low: 185.3,
close: 185.55,
volume: 0,
vwap: null,
session: 'RTH',
source: 'ib_live',
known_at_us: 1704205920123456n,
ts_us: 1704205860000000,
},
];
fake.setRows(fixtureRows);
const from = new Date('2024-01-02T14:30:00.000Z');
const to = new Date('2024-01-02T14:32:00.000Z');
const firstRead = await readBars1m(fake, 1042, from, to);
const secondRead = await readBars1m(fake, 1042, from, to);
expect(fake.calls).toHaveLength(2);
expect(fake.calls[0]).toEqual({
sql:
'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' +
'FROM bars_1m ' +
'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' +
'ORDER BY ts ASC',
params: ['1042', '2024-01-02T14:30:00.000Z', '2024-01-02T14:32:00.000Z'],
});
expect(firstRead).toEqual(secondRead);
expect(firstRead).toEqual([
{
listing_id: 1042,
open: 185.1,
high: 185.5,
low: 184.9,
close: 185.4,
volume: 12500,
vwap: 185.28,
session: 'RTH',
source: 'eod_unadj',
known_at: 1704205860000700n,
ts: 1704205800000000n,
},
{
listing_id: 1042,
open: 185.4,
high: 185.6,
low: 185.3,
close: 185.55,
volume: 0,
vwap: null,
session: 'RTH',
source: 'ib_live',
known_at: 1704205920123456n,
ts: 1704205860000000n,
},
]);
expect(typeof firstRead[0]!.listing_id).toBe('number');
// Verify sub-millisecond ordering is preserved (14:31:00.000700Z > 14:31:00.000000Z)
expect(firstRead[0]!.known_at > 1704205860000000n).toBe(true);
});
it('preserves 6-digit microsecond bounds and produces identical results under non-UTC TZ', async () => {
const fake = new FakeQuestDBClient();
fake.setRows([
{
listing_id: '1042',
open: 185.1,
high: 185.5,
low: 184.9,
close: 185.4,
volume: 12500,
vwap: 185.28,
session: 'RTH',
source: 'eod_unadj',
known_at_us: '1704205860000700',
ts_us: '1704205800000000',
},
]);
const previousTz = process.env.TZ;
try {
process.env.TZ = 'UTC';
const utcRows = await readBars1m(
fake,
1042,
'2024-01-02T14:30:00.000000Z',
'2024-01-02T14:31:00.000700Z'
);
process.env.TZ = 'America/Toronto';
const torontoRows = await readBars1m(
fake,
1042,
'2024-01-02T14:30:00.000000Z',
'2024-01-02T14:31:00.000700Z'
);
expect(torontoRows).toEqual(utcRows);
expect(torontoRows[0]!.known_at).toBe(1704205860000700n);
expect(torontoRows[0]!.ts).toBe(1704205800000000n);
expect(fake.calls[0]?.params).toEqual([
'1042',
'2024-01-02T14:30:00.000000Z',
'2024-01-02T14:31:00.000700Z',
]);
expect(fake.calls[1]?.params).toEqual(fake.calls[0]?.params);
} finally {
if (previousTz === undefined) {
delete process.env.TZ;
} else {
process.env.TZ = previousTz;
}
}
// Reject timezone-naive string bounds that would depend on host local timezone
await expect(
readBars1m(fake, 1042, '2024-01-02T14:30:00', '2024-01-02T14:35:00Z')
).rejects.toThrow(/timezone/i);
});
it('returns empty array when no bars exist in range', async () => {
const fake = new FakeQuestDBClient();
fake.setRows([]);
const rows = await readBars1m(
fake,
0,
'2024-01-02T14:30:00.000Z',
'2024-01-02T14:35:00.000Z'
);
expect(rows).toEqual([]);
expect(fake.calls[0]?.params).toEqual([
'0',
'2024-01-02T14:30:00.000Z',
'2024-01-02T14:35:00.000Z',
]);
});
it('rejects invalid input listingIds and malformed returned SYMBOL listing_id values', async () => {
const fake = new FakeQuestDBClient();
const from = new Date('2024-01-02T14:30:00.000Z');
const to = new Date('2024-01-02T14:35:00.000Z');
await expect(readBars1m(fake, 1.5, from, to)).rejects.toThrow(/INT32/i);
await expect(readBars1m(fake, 2147483648, from, to)).rejects.toThrow(/INT32/i);
expect(fake.calls).toHaveLength(0);
for (const badSymbol of ['abc', '007', '12.5', '2147483648', null]) {
fake.setRows([
{
listing_id: badSymbol,
open: 1,
high: 2,
low: 1,
close: 2,
volume: 10,
vwap: 1.5,
session: 'RTH',
source: 'eod_unadj',
known_at_us: '1704205800000000',
ts_us: '1704205800000000',
},
]);
await expect(readBars1m(fake, 42, from, to)).rejects.toThrow(/listing_id SYMBOL/i);
}
});
});
});

View file

@ -252,19 +252,20 @@ describe('QuestDB', () => {
const builder = new QuestDBQueryBuilder(mockClient);
const query = builder
const { sql, params } = builder
.select('symbol', 'close', 'volume')
.from('ohlcv_data')
.whereSymbol('AAPL')
.orderBy('timestamp', 'DESC')
.limit(100)
.build();
.buildParameterized();
expect(query).toContain('SELECT symbol, close, volume');
expect(query).toContain('FROM ohlcv_data');
expect(query).toContain("symbol = 'AAPL'");
expect(query).toContain('ORDER BY timestamp DESC');
expect(query).toContain('LIMIT 100');
expect(sql).toContain('SELECT symbol, close, volume');
expect(sql).toContain('FROM ohlcv_data');
expect(sql).toContain('symbol = $1');
expect(sql).toContain('ORDER BY timestamp DESC');
expect(sql).toContain('LIMIT $2');
expect(params).toEqual(['AAPL', 100]);
});
it('should build query with time range', () => {

View file

@ -218,8 +218,33 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
- **Injected exchange calendars:** `resolveExchangeCalendars({ listingIds, fromDate, toDate })` supplies actual exchange session close timestamps (including half-days) for `buildEventStudyInput` so events are anchored without synthesizing calendars from bars.
- **Returns, benchmark & Vault fence:** Models daily close-to-close returns with no execution or transaction costs (`adjustment` defaults to `'raw'`; `benchmark` defaults to `'equal_weight'` using available eligible listing returns, or `'none'` for unbenchmarked returns). Enforces `scope: 'vault_fenced'`, clamps `to`/`asOf` strictly below `vaultCutoffTs`, resolves named universes strictly pre-start, defensively excludes any bar or event on or after the Vault cutoff date (or with `known_at > asOf`), and writes eligible trials exclusively to the injected `trial_ledger` (`stage = 'event_study'`) under the server-injected `principalId`.
### `file_finding` Tool (Append-Only)
- **`createFileFindingTool({ port, trialLookup, newId, now })`** — Files an append-only empirical `finding` or `dead_end` record linked to 1–32 research-visible `trial_ledger` references (`trialRefs`, capped at 256 chars each) and 0–32 optional opaque snapshot identifiers (`evidenceRefs`, never dereferenced by the tool). Trims and enforces hard limits (`title` ≤ 256, `summary` ≤ 4,096, `idempotencyKey` ≤ 128), applies array bounds before case-sensitive deduplication and sorting, and rejects unknown fields with a fixed message.
- **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`.
### Remaining M2 MCP Items (Later Tasks)
- Additional research tools: `search_symbols`, `analyze_signal`, `file_finding`, and `read_knowledge`.
- SSE/HTTP transport wrapper in `apps/stock/web-api`.
- Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters.
## Versioned Feature Library
Exported from both `@stock-bot/research` and `@stock-bot/research/feature-library` (`libs/research/src/feature-library.ts`). The module is pure, dependency-free, and browser-safe (zero `node:*` imports, zero DuckDB driver dependency); SQL execution is injected via `DuckDbExecutor` (`{ run(sql), query(sql, params) }`).
### API & Immutability
- **`validateFeatureDefinition(def)`** — Fail-closed validator for declarative `duckdb_sql` feature definitions using a single quote-aware tokenizer shared with hashing and placeholder expansion. Accepts a single `SELECT` or non-recursive `WITH ... SELECT` statement projecting exactly `(listing_id, ts, known_at, value)` in contract order. Rejects `WITH RECURSIVE`, semicolons, comments, caller bind markers (`?`, `$1`, `:name`), prohibited DDL/DML/admin keywords (`COPY`, `ATTACH`, `INSERT`, `CREATE`, `PRAGMA`, `SET`, etc.), external readers (`read_parquet`, `read_csv`, `glob`, etc.), quoted file paths/URIs, catalog relations, table functions, and non-allow-listed functions. Relation sources are restricted to declared `{{input:<dataset>}}` placeholders (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`), in-scope non-recursive CTEs, and validated subqueries; every declared input must be used and every placeholder must be declared.
- **`featureRef(def)` / `parseFeatureRef(ref)`** — Formats and parses canonical `<name>@v<version>` refs (`^[a-z][a-z0-9_]{0,62}$` and positive safe integer version; rejects non-canonical forms such as `ret_1d@v01`).
- **`featureDefinitionHash(def)`** — Deterministic 64-char SHA-256 hex digest over `{ name, version, kind, sql (canonical tokens), inputs (sorted), warmupBars, knownAtRule }`. Invariant across inter-token whitespace, object key order, and input array order; preserves whitespace inside string literals. `family` and `description` are stored as metadata from the first registration.
- **`createFeatureRegistry()`** — In-memory registry exposing `registerSignal(def)` (D11), `get(ref)`, and `list()`. Re-registering an identical hash is idempotent; re-registering `<name>@v<version>` with a different hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. Defensive copies isolate stored definitions from caller mutation.
- **`planFeatureBatch(def, { curatedRoot, fromYear, toYear, vaultCutoffDate })`** — Validates `curatedRoot`, four-digit ordered years, and strict UTC `YYYY-MM-DD` `vaultCutoffDate` via `applyVaultFence`. Plans one yearly ZSTD Parquet write to `<curatedRoot>/features/<name>/v<version>/year=YYYY/part.parquet` through the last year with any pre-cutoff time (a January 1 cutoff excludes that calendar year; an entirely post-cutoff range throws `VAULT_RANGE_VIOLATION`). Expands `{{input:<dataset>}}` scans with bound upper availability predicates (`ts <= ? AND known_at <= ?`, `known_at <= ?`, or `effective_known_at <= ?` for `fundamentals_pit`) strictly `< vaultCutoffDate` (last included microsecond `.999999Z`) before authored SQL runs, preserving earlier history for SQL-owned warm-up.
- **`runFeatureBatch(def, opts, executor)`** — Validates and plans upfront (0 executor calls on invalid inputs), awaits `executor.query(sql, params)` sequentially in year order, and returns `{ ref, definitionHash, knownAtRule, warmupBars, inputs, writes }`. On write failure, stops immediately and throws `FeatureLibraryError('BATCH_WRITE_FAILED')` exposing `cause`, `failedYear`, `completedYears`, and `completedWrites` (earlier completed files may remain on disk for operator inspection before retry).
- **`RET_1D_V1`** — Built-in `ret_1d@v1` example computing 1-day listing-partitioned raw-close return `(close / LAG(close)) - 1.0` with `known_at = ts` and `warmupBars: 1` (omitting rows without a positive prior close).
### Operational & Research Governance Notes
- **Executor & directory requirements:** Callers running plans against DuckDB must configure the executor session timezone to UTC (`TZ=UTC`) and ensure output parent directories (`<curatedRoot>/features/<name>/v<version>/year=YYYY/`) exist before executing `COPY`.
- **Point-in-time & `adj_factors` snapshots:** Feature definitions own per-observation availability (`knownAtRule` and projected `known_at`). Because `adj_factors` stores cumulative suffix products, features referencing `{{input:adj_factors}}` require a caller-verified, immutable point-in-time snapshot compatible with `vaultCutoffDate`.
- **Economic ownership & evidence:** The Quant research role owns each feature's economic specification. `RET_1D_V1` uses a zero-return comparison baseline with no execution or transaction cost model. Any future research claim built on materialized features must retain the feature `ref` and `definitionHash`, immutable dataset identifier, sample window, `vaultCutoffDate`, baseline, and execution assumptions.

View file

@ -11,6 +11,7 @@
"./dataset-contracts": "./src/dataset-contracts.ts",
"./datasets": "./src/datasets.ts",
"./event-panel": "./src/event-panel.ts",
"./feature-library": "./src/feature-library.ts",
"./market-data-store": "./src/market-data-store.ts",
"./market-data-store-duckdb": "./src/market-data-store-duckdb.ts",
"./mcp": "./src/mcp/index.ts",

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,7 @@
// The default entrypoint is browser safe; server validation is an explicit subpath.
export * from './dataset-contracts';
export * from './event-panel';
export * from './feature-library';
export * from './market-data-store';
export * from './market-data-store-duckdb';
export * from './signal-panel';

View file

@ -3,4 +3,7 @@ export * from './server';
export * from './stdio';
export * from './tools/analyze-signal';
export * from './tools/event-study';
export * from './tools/file-finding';
export * from './tools/query-data';
export * from './tools/read-knowledge';
export * from './tools/search-symbols';

View file

@ -0,0 +1,416 @@
import { z } from 'zod';
import type { McpToolCallResult } from '../protocol';
import { type McpToolEntry, defineMcpTool } from '../server';
import { type FindingRecord, READ_KNOWLEDGE_MAX_TEXT_LENGTH } from './read-knowledge';
import { MAX_ECMASCRIPT_EPOCH_MS } from './vault-fenced-input';
/** Supported filing kinds for `file_finding` (per D12 in `design/PLATFORM-PLAN.md`). */
export const FILE_FINDING_KINDS = ['finding', 'dead_end'] as const;
export type FileFindingKind = (typeof FILE_FINDING_KINDS)[number];
/** Initial server-assigned review status for every newly filed finding or dead end. */
export const FILE_FINDING_INITIAL_STATUS = 'pending_review' as const;
export type FileFindingInitialStatus = typeof FILE_FINDING_INITIAL_STATUS;
/** Hard maximum character length of a trimmed `file_finding` title. */
export const FILE_FINDING_MAX_TITLE_LENGTH = 256;
/** Hard maximum character length of a trimmed `file_finding` summary. */
export const FILE_FINDING_MAX_SUMMARY_LENGTH = READ_KNOWLEDGE_MAX_TEXT_LENGTH;
/** Hard maximum character length of a trimmed trial or evidence reference string. */
export const FILE_FINDING_MAX_REF_LENGTH = 256;
/** Hard maximum number of raw `trialRefs` accepted before deduplication. */
export const FILE_FINDING_MAX_TRIAL_REFS = 32;
/** Hard maximum number of raw `evidenceRefs` accepted before deduplication. */
export const FILE_FINDING_MAX_EVIDENCE_REFS = 32;
/** Hard maximum character length of a trimmed `idempotencyKey`. */
export const FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH = 128;
/** Fixed validation message used when unknown keys are supplied (never echoes caller keys). */
export const FILE_FINDING_ERROR_UNKNOWN_KEYS = 'Unrecognized field(s) are not allowed.';
/** Fixed tool error message when one or more trial refs are unknown or Vault-only. */
export const FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF =
'One or more referenced trials are unavailable in the research-visible trial ledger.';
/** Fixed tool error message when an idempotency key is reused with a different payload. */
export const FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT =
'Idempotency key conflict: the provided idempotency key was already used with a different finding payload.';
/** Fixed tool error message when trial lookup, metadata generation, or append fails. */
export const FILE_FINDING_ERROR_FILING_FAILED =
'Failed to file finding due to a storage or lookup error.';
/**
* Append-only finding or dead-end record passed to {@link FindingWritePort.appendFinding}.
*
* Extends {@link FindingRecord} with `kind` and fixes `status` to `'pending_review'`
* so filed records are directly readable via `read_knowledge` while director approval
* happens out-of-band.
*/
export interface FiledFindingRecord extends FindingRecord {
readonly kind: FileFindingKind;
readonly status: FileFindingInitialStatus;
}
/** Normalized caller-supplied fields compared for idempotency equality. */
export type FiledFindingComparablePayload = Pick<
FiledFindingRecord,
'kind' | 'title' | 'summary' | 'trialRefs' | 'evidenceRefs'
>;
/**
* Discriminated outcome returned by {@link FindingWritePort.appendFinding}.
*
* - `'created'`: A new record was appended.
* - `'replayed'`: An existing record with the same `idempotencyKey` and
* identical normalized payload (`kind`, `title`, `summary`, `trialRefs`,
* `evidenceRefs`) was found; zero rows were appended and the stored `id`
* and `createdAt` are returned.
* - `'conflict'`: An existing record with the same `idempotencyKey` has a
* different normalized payload; zero rows were appended.
*/
export type AppendFindingResult =
| {
readonly status: 'created';
readonly id: string;
readonly createdAt: string;
}
| {
readonly status: 'replayed';
readonly id: string;
readonly createdAt: string;
}
| {
readonly status: 'conflict';
};
/**
* Append-only write port injected into {@link createFileFindingTool}.
*
* Port contract:
* - Append-only by construction: exposes only {@link appendFinding} (no update
* or delete methods).
* - When `idempotencyKey` is supplied, the port must atomically compare and
* append within its configured key namespace:
* - Compare normalized `kind`, `title`, `summary`, `trialRefs`, and
* `evidenceRefs` (excluding server-generated `id`, `createdAt`, and `status`).
* - On an identical payload match, return `{ status: 'replayed', id, createdAt }`
* with the originally stored `id` and `createdAt` without appending a new row.
* - On a payload mismatch, return `{ status: 'conflict' }` and append zero rows.
* - When `idempotencyKey` is omitted (`undefined`), each call is independent and
* appends a new row, returning `{ status: 'created', id, createdAt }`.
*/
export interface FindingWritePort {
appendFinding(
record: FiledFindingRecord,
idempotencyKey?: string
): Promise<AppendFindingResult>;
}
/**
* Read-only trial visibility lookup port injected into {@link createFileFindingTool}.
*
* Bound at composition to the caller's research-visible `trial_ledger` and active
* Vault boundary. Accepts opaque string refs (for example, decimal `trialId` strings
* from `trial_ledger` receipts without numeric coercion) and returns `true` only when
* the trial exists and is research-visible. Unknown and Vault-only refs both return
* `false`.
*/
export interface TrialRefLookupPort {
hasResearchVisibleTrial(trialRef: string): Promise<boolean> | boolean;
}
/** Server-side injected configuration for {@link createFileFindingTool}. */
export interface FileFindingToolOptions {
readonly port: FindingWritePort;
readonly trialLookup: TrialRefLookupPort;
readonly newId: () => string;
readonly now: () => Date | number;
}
/** Structured JSON receipt serialized into the `file_finding` MCP text result. */
export interface FileFindingResultPayload {
readonly id: string;
readonly createdAt: string;
readonly created: boolean;
}
function compareStrings(a: string, b: string): number {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
function normalizeRefSet(refs: readonly string[]): readonly string[] {
const unique = Array.from(new Set(refs));
unique.sort(compareStrings);
return unique;
}
function areStringArraysEqual(a: readonly string[], b: readonly string[]): boolean {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* Compares two normalized filing payloads for idempotency equality across
* `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` (excluding
* server-generated `id`, `createdAt`, and `status`).
*/
export function areFiledFindingPayloadsEqual(
a: FiledFindingComparablePayload,
b: FiledFindingComparablePayload
): boolean {
return (
a.kind === b.kind &&
a.title === b.title &&
a.summary === b.summary &&
areStringArraysEqual(a.trialRefs, b.trialRefs) &&
areStringArraysEqual(a.evidenceRefs, b.evidenceRefs)
);
}
const refStringSchema = z.string().trim().min(1).max(FILE_FINDING_MAX_REF_LENGTH);
/**
* Strict Zod input schema for the `file_finding` MCP tool.
*
* Intentionally omits server-controlled fields (`id`, `status`, `createdAt`) and
* Vault/holdout fields (`scope`, `vault_evaluation_only`, `vaultCutoffTs`).
* `.strict(FILE_FINDING_ERROR_UNKNOWN_KEYS)` rejects any unknown keys with a fixed
* message so caller-supplied key names are never echoed.
*
* `title` and `summary` must describe research-visible evidence only; `evidenceRefs`
* are opaque snapshot identifiers that the tool stores without dereferencing.
*/
export const fileFindingInputSchema = z
.object({
kind: z
.enum(FILE_FINDING_KINDS, {
errorMap: () => ({ message: "Expected 'finding' or 'dead_end'." }),
})
.describe("Filing classification: 'finding' or 'dead_end'."),
title: z
.string()
.trim()
.min(1)
.max(FILE_FINDING_MAX_TITLE_LENGTH)
.describe(
`Short title describing research-visible evidence (trimmed, 1–${FILE_FINDING_MAX_TITLE_LENGTH} characters).`
),
summary: z
.string()
.trim()
.min(1)
.max(FILE_FINDING_MAX_SUMMARY_LENGTH)
.describe(
`Concise summary of research-visible evidence only; never include Vault holdout observations (trimmed, 1–${FILE_FINDING_MAX_SUMMARY_LENGTH} characters).`
),
trialRefs: z
.array(refStringSchema)
.min(1)
.max(FILE_FINDING_MAX_TRIAL_REFS)
.transform(normalizeRefSet)
.describe(
`Opaque research-visible trial_ledger references (1–${FILE_FINDING_MAX_TRIAL_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; deduplicated case-sensitively and sorted).`
),
evidenceRefs: z
.array(refStringSchema)
.max(FILE_FINDING_MAX_EVIDENCE_REFS)
.default([])
.transform(normalizeRefSet)
.describe(
`Optional opaque snapshot or artifact identifiers never dereferenced by the tool (0–${FILE_FINDING_MAX_EVIDENCE_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; defaults to empty list, deduplicated case-sensitively and sorted).`
),
idempotencyKey: z
.string()
.trim()
.min(1)
.max(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH)
.optional()
.describe(
`Optional retry idempotency key (trimmed, 1–${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH} characters).`
),
})
.strict(FILE_FINDING_ERROR_UNKNOWN_KEYS);
export type FileFindingInput = z.infer<typeof fileFindingInputSchema>;
function toolError(message: string): McpToolCallResult {
return {
content: [{ type: 'text', text: message }],
isError: true,
};
}
function validateNonEmptyString(value: unknown): string | null {
if (typeof value !== 'string' || value.trim().length === 0) {
return null;
}
return value;
}
function formatUtcIsoTimestamp(raw: Date | number): string | null {
const epochMs = raw instanceof Date ? raw.getTime() : raw;
if (
typeof epochMs !== 'number' ||
!Number.isFinite(epochMs) ||
Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS
) {
return null;
}
return new Date(epochMs).toISOString();
}
function validateFactoryOptions(options: FileFindingToolOptions): FileFindingToolOptions {
if (typeof options !== 'object' || options === null) {
throw new Error('Invalid `options`: expected a FileFindingToolOptions object.');
}
if (
typeof options.port !== 'object' ||
options.port === null ||
typeof options.port.appendFinding !== 'function'
) {
throw new Error(
'Invalid `port`: expected a FindingWritePort implementing `appendFinding`.'
);
}
if (
typeof options.trialLookup !== 'object' ||
options.trialLookup === null ||
typeof options.trialLookup.hasResearchVisibleTrial !== 'function'
) {
throw new Error(
'Invalid `trialLookup`: expected a TrialRefLookupPort implementing `hasResearchVisibleTrial`.'
);
}
if (typeof options.newId !== 'function') {
throw new Error('Invalid `newId`: expected a function returning a non-empty finding ID.');
}
if (typeof options.now !== 'function') {
throw new Error('Invalid `now`: expected a clock function returning a Date or epoch ms.');
}
return options;
}
/**
* Creates the append-only `file_finding` MCP tool backed by an injected
* {@link FindingWritePort} and read-only {@link TrialRefLookupPort}.
*
* Verifies every unique `trialRef` against the research-visible trial ledger
* before generating server-controlled metadata (`id`, `createdAt`,
* `status: 'pending_review'`) or calling `appendFinding`. Returns only the
* explicitly projected `{ id, createdAt, created }` receipt on success and fixed
* sanitized `isError` messages on failure.
*/
export function createFileFindingTool(options: FileFindingToolOptions): McpToolEntry {
const validated = validateFactoryOptions(options);
const { port, trialLookup, newId, now } = validated;
return defineMcpTool({
name: 'file_finding',
description:
'File an append-only empirical finding or dead end linked to research-visible trial ledger references for director review.',
inputSchema: fileFindingInputSchema,
async handler(input: FileFindingInput): Promise<McpToolCallResult> {
// Verify every unique research-visible trial ref before generating metadata or writing.
for (let i = 0; i < input.trialRefs.length; i += 1) {
const trialRef = input.trialRefs[i] as string;
let visible: unknown;
try {
visible = await trialLookup.hasResearchVisibleTrial(trialRef);
} catch {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
if (typeof visible !== 'boolean') {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
if (!visible) {
return toolError(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
}
}
let id: string | null;
let createdAt: string | null;
try {
id = validateNonEmptyString(newId());
createdAt = formatUtcIsoTimestamp(now());
} catch {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
if (id === null || createdAt === null) {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
const record: FiledFindingRecord = {
id,
kind: input.kind,
title: input.title,
status: FILE_FINDING_INITIAL_STATUS,
createdAt,
summary: input.summary,
trialRefs: [...input.trialRefs],
evidenceRefs: [...input.evidenceRefs],
};
let outcome: AppendFindingResult;
try {
outcome = await port.appendFinding(record, input.idempotencyKey);
} catch {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
if (typeof outcome !== 'object' || outcome === null) {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
if (outcome.status === 'conflict') {
return toolError(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT);
}
if (outcome.status !== 'created' && outcome.status !== 'replayed') {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
const receiptId = validateNonEmptyString(outcome.id);
const receiptCreatedAt = validateNonEmptyString(outcome.createdAt);
if (receiptId === null || receiptCreatedAt === null) {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
const payload: FileFindingResultPayload = {
id: receiptId,
createdAt: receiptCreatedAt,
created: outcome.status === 'created',
};
return {
content: [{ type: 'text', text: JSON.stringify(payload) }],
};
},
});
}

View file

@ -0,0 +1,588 @@
import { z } from 'zod';
import type { McpToolCallResult } from '../protocol';
import { type McpToolEntry, defineMcpTool } from '../server';
/** Concrete knowledge sources returned in `read_knowledge` rows and source counts. */
export const READ_KNOWLEDGE_RECORD_SOURCES = ['library', 'findings', 'provider_caveats'] as const;
export type ReadKnowledgeRecordSource = (typeof READ_KNOWLEDGE_RECORD_SOURCES)[number];
/** Supported `source` selector values for `read_knowledge`. */
export const READ_KNOWLEDGE_SOURCES = [...READ_KNOWLEDGE_RECORD_SOURCES, 'all'] as const;
export type ReadKnowledgeSource = (typeof READ_KNOWLEDGE_SOURCES)[number];
/** Default maximum number of matching records returned by `read_knowledge`. */
export const READ_KNOWLEDGE_DEFAULT_LIMIT = 20;
/** Hard maximum number of matching records returned by `read_knowledge`. */
export const READ_KNOWLEDGE_MAX_LIMIT = 100;
/** Hard maximum character length of a trimmed `read_knowledge` query string. */
export const READ_KNOWLEDGE_MAX_QUERY_LENGTH = 64;
/** Hard maximum character length per projected text field (`body`, `summary`, `caveat`). */
export const READ_KNOWLEDGE_MAX_TEXT_LENGTH = 4096;
/** Methodology or literature card record returned by {@link KnowledgePort.listLibraryCards}. */
export interface LibraryCardRecord {
readonly id: string;
readonly title: string;
readonly tags: readonly string[];
readonly summary: string;
readonly body: string;
}
/** Empirical Stock Bot finding record returned by {@link KnowledgePort.listFindings}. */
export interface FindingRecord {
readonly id: string;
readonly title: string;
readonly status: string;
readonly createdAt: string;
readonly summary: string;
readonly trialRefs: readonly string[];
readonly evidenceRefs: readonly string[];
}
/** Provider dataset caveat record returned by {@link KnowledgePort.listProviderCaveats}. */
export interface ProviderCaveatRecord {
readonly id: string;
readonly provider: string;
readonly dataset: string;
readonly caveat: string;
readonly createdAt: string;
}
/** Applicable parsed selectors passed to {@link KnowledgePort.listLibraryCards}. */
export interface LibraryCardQuery {
readonly id?: string;
readonly query?: string;
readonly tags?: readonly string[];
}
/** Applicable parsed selectors passed to {@link KnowledgePort.listFindings}. */
export interface FindingQuery {
readonly id?: string;
readonly query?: string;
}
/** Applicable parsed selectors passed to {@link KnowledgePort.listProviderCaveats}. */
export interface ProviderCaveatQuery {
readonly id?: string;
readonly query?: string;
readonly provider?: string;
}
/**
* Read-only knowledge lookup port injected into {@link createReadKnowledgeTool}.
*
* Port contract:
* - Read-only by construction: exposes only lookup methods and never mutates backing stores.
* - Callers and concrete adapters must supply research-visible records and references only;
* holdout observations and vault-only evidence must be excluded from the research corpus.
* - Return all eligible candidates (with IDs unique within each source) without pre-slicing
* so the tool controls deterministic global ranking and the global `limit`.
*/
export interface KnowledgePort {
listLibraryCards(q: LibraryCardQuery): Promise<readonly LibraryCardRecord[]>;
listFindings(q: FindingQuery): Promise<readonly FindingRecord[]>;
listProviderCaveats(q: ProviderCaveatQuery): Promise<readonly ProviderCaveatRecord[]>;
}
/**
* Strict Zod input schema for the `read_knowledge` MCP tool.
*
* Intentionally omits `scope`, `vault_evaluation_only`, and `vaultCutoffTs`;
* `.strict()` rejects any unknown keys.
*/
export const readKnowledgeInputSchema = z
.object({
source: z
.enum(READ_KNOWLEDGE_SOURCES)
.default('all')
.describe(
'Knowledge source to query: library, findings, provider_caveats, or all (default all).'
),
query: z
.string()
.trim()
.min(1)
.max(READ_KNOWLEDGE_MAX_QUERY_LENGTH)
.optional()
.describe(
`Optional case-insensitive substring query (trimmed, 1–${READ_KNOWLEDGE_MAX_QUERY_LENGTH} characters). Ignored when id is supplied.`
),
id: z
.string()
.trim()
.min(1)
.optional()
.describe(
'Optional exact case-sensitive card or record ID selector. Takes precedence over query when supplied.'
),
tags: z
.array(z.string().trim().min(1))
.min(1)
.optional()
.describe(
'Optional tag filter applied only to library cards (case-insensitive all-tag match; findings and provider_caveats are unaffected when source is all).'
),
provider: z
.string()
.trim()
.min(1)
.optional()
.describe(
'Optional provider filter applied only to provider_caveats (case-insensitive exact match; library and findings are unaffected when source is all).'
),
limit: z
.number()
.int()
.min(1)
.max(READ_KNOWLEDGE_MAX_LIMIT)
.default(READ_KNOWLEDGE_DEFAULT_LIMIT)
.describe(
`Maximum number of ranked records to return (default ${READ_KNOWLEDGE_DEFAULT_LIMIT}, max ${READ_KNOWLEDGE_MAX_LIMIT}).`
),
})
.strict();
export type ReadKnowledgeInput = z.infer<typeof readKnowledgeInputSchema>;
/** Server-side injected configuration for {@link createReadKnowledgeTool}. */
export interface ReadKnowledgeToolOptions {
readonly port: KnowledgePort;
}
/** Source-labeled library card row emitted by `read_knowledge`. */
export interface ReadKnowledgeLibraryRow {
readonly source: 'library';
readonly id: string;
readonly title: string;
readonly tags: readonly string[];
readonly summary: string;
readonly body: string;
readonly truncated: boolean;
}
/** Source-labeled empirical finding row emitted by `read_knowledge`. */
export interface ReadKnowledgeFindingRow {
readonly source: 'findings';
readonly id: string;
readonly title: string;
readonly status: string;
readonly createdAt: string;
readonly summary: string;
readonly trialRefs: readonly string[];
readonly evidenceRefs: readonly string[];
readonly truncated: boolean;
}
/** Source-labeled provider caveat row emitted by `read_knowledge`. */
export interface ReadKnowledgeProviderCaveatRow {
readonly source: 'provider_caveats';
readonly id: string;
readonly provider: string;
readonly dataset: string;
readonly caveat: string;
readonly createdAt: string;
readonly truncated: boolean;
}
/** Discriminated union of rows emitted by `read_knowledge`. */
export type ReadKnowledgeRow =
| ReadKnowledgeLibraryRow
| ReadKnowledgeFindingRow
| ReadKnowledgeProviderCaveatRow;
/** Per-source counts of returned rows after applying the global `limit`. */
export interface ReadKnowledgeSourceCounts {
readonly library: number;
readonly findings: number;
readonly provider_caveats: number;
}
/** Structured JSON payload serialized into the `read_knowledge` MCP text result. */
export interface ReadKnowledgeResultPayload {
readonly rowCount: number;
readonly sources: ReadKnowledgeSourceCounts;
readonly rows: readonly ReadKnowledgeRow[];
}
const SOURCE_ORDER: Readonly<Record<ReadKnowledgeRecordSource, number>> = {
library: 0,
findings: 1,
provider_caveats: 2,
};
function compareStrings(a: string, b: string): number {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
function validateRequiredString(value: unknown, field: string): string {
if (typeof value !== 'string') {
throw new Error(`Invalid port string for "${field}".`);
}
return value;
}
function validateStringArray(value: unknown, field: string): readonly string[] {
if (!Array.isArray(value)) {
throw new Error(`Invalid port string array for "${field}".`);
}
const result: string[] = [];
for (let i = 0; i < value.length; i += 1) {
const entry: unknown = value[i];
if (typeof entry !== 'string') {
throw new Error(`Invalid port string array entry for "${field}".`);
}
result.push(entry);
}
return result;
}
function truncateText(value: string): { readonly text: string; readonly truncated: boolean } {
if (value.length <= READ_KNOWLEDGE_MAX_TEXT_LENGTH) {
return { text: value, truncated: false };
}
return {
text: value.slice(0, READ_KNOWLEDGE_MAX_TEXT_LENGTH),
truncated: true,
};
}
function validateLibraryCard(raw: LibraryCardRecord): LibraryCardRecord {
if (typeof raw !== 'object' || raw === null) {
throw new Error('Invalid library card record returned by port.');
}
return {
id: validateRequiredString(raw.id, 'id'),
title: validateRequiredString(raw.title, 'title'),
tags: validateStringArray(raw.tags, 'tags'),
summary: validateRequiredString(raw.summary, 'summary'),
body: validateRequiredString(raw.body, 'body'),
};
}
function validateFinding(raw: FindingRecord): FindingRecord {
if (typeof raw !== 'object' || raw === null) {
throw new Error('Invalid finding record returned by port.');
}
return {
id: validateRequiredString(raw.id, 'id'),
title: validateRequiredString(raw.title, 'title'),
status: validateRequiredString(raw.status, 'status'),
createdAt: validateRequiredString(raw.createdAt, 'createdAt'),
summary: validateRequiredString(raw.summary, 'summary'),
trialRefs: validateStringArray(raw.trialRefs, 'trialRefs'),
evidenceRefs: validateStringArray(raw.evidenceRefs, 'evidenceRefs'),
};
}
function validateProviderCaveat(raw: ProviderCaveatRecord): ProviderCaveatRecord {
if (typeof raw !== 'object' || raw === null) {
throw new Error('Invalid provider caveat record returned by port.');
}
return {
id: validateRequiredString(raw.id, 'id'),
provider: validateRequiredString(raw.provider, 'provider'),
dataset: validateRequiredString(raw.dataset, 'dataset'),
caveat: validateRequiredString(raw.caveat, 'caveat'),
createdAt: validateRequiredString(raw.createdAt, 'createdAt'),
};
}
function matchesAllTags(
cardTags: readonly string[],
requiredLowerTags: readonly string[]
): boolean {
const cardLowerTags = new Set(cardTags.map(tag => tag.toLowerCase()));
for (let i = 0; i < requiredLowerTags.length; i += 1) {
if (!cardLowerTags.has(requiredLowerTags[i] as string)) {
return false;
}
}
return true;
}
function rankLibraryCard(
card: LibraryCardRecord,
exactId: string | undefined,
normalizedQuery: string | null,
requiredLowerTags: readonly string[] | null
): number | null {
if (requiredLowerTags !== null && !matchesAllTags(card.tags, requiredLowerTags)) {
return null;
}
if (exactId !== undefined) {
return card.id === exactId ? 0 : null;
}
if (normalizedQuery === null) {
return 2;
}
const titleMatches = card.title.toLowerCase().includes(normalizedQuery);
const tagMatches = card.tags.some(tag => tag.toLowerCase().includes(normalizedQuery));
const summaryMatches = card.summary.toLowerCase().includes(normalizedQuery);
if (!titleMatches && !tagMatches && !summaryMatches) {
return null;
}
return titleMatches ? 1 : 2;
}
function rankFinding(
finding: FindingRecord,
exactId: string | undefined,
normalizedQuery: string | null
): number | null {
if (exactId !== undefined) {
return finding.id === exactId ? 0 : null;
}
if (normalizedQuery === null) {
return 2;
}
const titleMatches = finding.title.toLowerCase().includes(normalizedQuery);
const summaryMatches = finding.summary.toLowerCase().includes(normalizedQuery);
if (!titleMatches && !summaryMatches) {
return null;
}
return titleMatches ? 1 : 2;
}
function rankProviderCaveat(
caveat: ProviderCaveatRecord,
exactId: string | undefined,
normalizedQuery: string | null,
normalizedProvider: string | null
): number | null {
if (normalizedProvider !== null && caveat.provider.toLowerCase() !== normalizedProvider) {
return null;
}
if (exactId !== undefined) {
return caveat.id === exactId ? 0 : null;
}
if (normalizedQuery === null) {
return 2;
}
const datasetMatches = caveat.dataset.toLowerCase().includes(normalizedQuery);
const providerMatches = caveat.provider.toLowerCase().includes(normalizedQuery);
const caveatMatches = caveat.caveat.toLowerCase().includes(normalizedQuery);
if (!datasetMatches && !providerMatches && !caveatMatches) {
return null;
}
return datasetMatches ? 1 : 2;
}
function projectLibraryCard(card: LibraryCardRecord): ReadKnowledgeLibraryRow {
const summary = truncateText(card.summary);
const body = truncateText(card.body);
return {
source: 'library',
id: card.id,
title: card.title,
tags: [...card.tags],
summary: summary.text,
body: body.text,
truncated: summary.truncated || body.truncated,
};
}
function projectFinding(finding: FindingRecord): ReadKnowledgeFindingRow {
const summary = truncateText(finding.summary);
return {
source: 'findings',
id: finding.id,
title: finding.title,
status: finding.status,
createdAt: finding.createdAt,
summary: summary.text,
trialRefs: [...finding.trialRefs],
evidenceRefs: [...finding.evidenceRefs],
truncated: summary.truncated,
};
}
function projectProviderCaveat(caveat: ProviderCaveatRecord): ReadKnowledgeProviderCaveatRow {
const caveatText = truncateText(caveat.caveat);
return {
source: 'provider_caveats',
id: caveat.id,
provider: caveat.provider,
dataset: caveat.dataset,
caveat: caveatText.text,
createdAt: caveat.createdAt,
truncated: caveatText.truncated,
};
}
function validateFactoryOptions(options: ReadKnowledgeToolOptions): KnowledgePort {
if (typeof options !== 'object' || options === null) {
throw new Error('Invalid `options`: expected a ReadKnowledgeToolOptions object.');
}
const { port } = options;
if (
typeof port !== 'object' ||
port === null ||
typeof port.listLibraryCards !== 'function' ||
typeof port.listFindings !== 'function' ||
typeof port.listProviderCaveats !== 'function'
) {
throw new Error(
'Invalid `port`: expected a KnowledgePort implementing `listLibraryCards`, `listFindings`, and `listProviderCaveats`.'
);
}
return port;
}
interface RankedCandidate {
readonly rank: number;
readonly row: ReadKnowledgeRow;
}
/**
* Creates the read-only `read_knowledge` MCP tool backed by an injected
* {@link KnowledgePort}.
*
* Queries only the selected source(s), applies exact-ID or case-insensitive
* text matching and source-specific filters (`tags` for library cards,
* `provider` for provider caveats), ranks deterministically (exact ID > title
* match > ascending ID, breaking cross-source ties in `library`, `findings`,
* `provider_caveats` order), applies `limit` after ranking, and caps long text
* fields independently with `truncated: true`.
*/
export function createReadKnowledgeTool(options: ReadKnowledgeToolOptions): McpToolEntry {
const port = validateFactoryOptions(options);
return defineMcpTool({
name: 'read_knowledge',
description:
'Read-only lookup across methodology library cards, empirical findings, and provider dataset caveats.',
inputSchema: readKnowledgeInputSchema,
async handler(input: ReadKnowledgeInput): Promise<McpToolCallResult> {
const wantLibrary = input.source === 'all' || input.source === 'library';
const wantFindings = input.source === 'all' || input.source === 'findings';
const wantCaveats = input.source === 'all' || input.source === 'provider_caveats';
const baseQuery: FindingQuery =
input.id !== undefined
? { id: input.id }
: input.query !== undefined
? { query: input.query }
: {};
const libraryQuery: LibraryCardQuery = {
...baseQuery,
...(input.tags !== undefined ? { tags: input.tags } : {}),
};
const findingQuery: FindingQuery = baseQuery;
const caveatQuery: ProviderCaveatQuery = {
...baseQuery,
...(input.provider !== undefined ? { provider: input.provider } : {}),
};
const [rawLibrary, rawFindings, rawCaveats] = await Promise.all([
(async () => (wantLibrary ? port.listLibraryCards(libraryQuery) : null))(),
(async () => (wantFindings ? port.listFindings(findingQuery) : null))(),
(async () => (wantCaveats ? port.listProviderCaveats(caveatQuery) : null))(),
]);
const normalizedQuery =
input.id === undefined && input.query !== undefined ? input.query.toLowerCase() : null;
const requiredLowerTags =
input.tags !== undefined ? input.tags.map(tag => tag.toLowerCase()) : null;
const normalizedProvider =
input.provider !== undefined ? input.provider.toLowerCase() : null;
const eligible: RankedCandidate[] = [];
if (rawLibrary !== null) {
if (!Array.isArray(rawLibrary)) {
throw new Error('Invalid library cards response returned by port.');
}
for (let i = 0; i < rawLibrary.length; i += 1) {
const card = validateLibraryCard(rawLibrary[i] as LibraryCardRecord);
const rank = rankLibraryCard(card, input.id, normalizedQuery, requiredLowerTags);
if (rank !== null) {
eligible.push({ rank, row: projectLibraryCard(card) });
}
}
}
if (rawFindings !== null) {
if (!Array.isArray(rawFindings)) {
throw new Error('Invalid findings response returned by port.');
}
for (let i = 0; i < rawFindings.length; i += 1) {
const finding = validateFinding(rawFindings[i] as FindingRecord);
const rank = rankFinding(finding, input.id, normalizedQuery);
if (rank !== null) {
eligible.push({ rank, row: projectFinding(finding) });
}
}
}
if (rawCaveats !== null) {
if (!Array.isArray(rawCaveats)) {
throw new Error('Invalid provider caveats response returned by port.');
}
for (let i = 0; i < rawCaveats.length; i += 1) {
const caveat = validateProviderCaveat(rawCaveats[i] as ProviderCaveatRecord);
const rank = rankProviderCaveat(caveat, input.id, normalizedQuery, normalizedProvider);
if (rank !== null) {
eligible.push({ rank, row: projectProviderCaveat(caveat) });
}
}
}
eligible.sort((a, b) => {
if (a.rank !== b.rank) {
return a.rank - b.rank;
}
const idCmp = compareStrings(a.row.id, b.row.id);
if (idCmp !== 0) {
return idCmp;
}
return SOURCE_ORDER[a.row.source] - SOURCE_ORDER[b.row.source];
});
const limitCount = Math.min(eligible.length, input.limit);
const rows: ReadKnowledgeRow[] = [];
let libraryCount = 0;
let findingsCount = 0;
let providerCaveatsCount = 0;
for (let i = 0; i < limitCount; i += 1) {
const row = (eligible[i] as RankedCandidate).row;
rows.push(row);
if (row.source === 'library') {
libraryCount += 1;
} else if (row.source === 'findings') {
findingsCount += 1;
} else {
providerCaveatsCount += 1;
}
}
const payload: ReadKnowledgeResultPayload = {
rowCount: rows.length,
sources: {
library: libraryCount,
findings: findingsCount,
provider_caveats: providerCaveatsCount,
},
rows,
};
return {
content: [{ type: 'text', text: JSON.stringify(payload) }],
};
},
});
}

View file

@ -0,0 +1,359 @@
import { z } from 'zod';
import { MarketDataStoreValidationError, type VaultFenceContext } from '../../market-data-store';
import type { McpToolCallResult } from '../protocol';
import { type McpToolEntry, defineMcpTool } from '../server';
import { utcDateOf, validateVaultCutoffTs } from './vault-fenced-input';
/** Default maximum number of matching listings returned by `search_symbols`. */
export const SEARCH_SYMBOLS_DEFAULT_LIMIT = 20;
/** Hard maximum number of matching listings returned by `search_symbols`. */
export const SEARCH_SYMBOLS_MAX_LIMIT = 100;
/** Hard maximum character length of a trimmed `search_symbols` query string. */
export const SEARCH_SYMBOLS_MAX_QUERY_LENGTH = 64;
/** Supported exchange country filters for `search_symbols`. */
export const SEARCH_SYMBOLS_COUNTRIES = ['US', 'CA'] as const;
export type SymbolSearchCountry = (typeof SEARCH_SYMBOLS_COUNTRIES)[number];
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];
/**
* Security-master projection returned by {@link SymbolSearchPort} and emitted
* (after Vault fencing) by the `search_symbols` MCP tool.
*
* Field provenance (M1 security master DDL / `design/DATA-CONTRACTS.md`):
* - `listingId`: `listing.listing_id` (`INT32`)
* - `instrumentId`: `listing.instrument_id` / `instrument.instrument_id` (`INT32`)
* - `ticker`: `listing_symbol_history.ticker` valid as of the Vault cutoff
* - `classSuffix`: nullable `listing.class_suffix`
* - `name`: `instrument.canonical_name`
* - `mic`: `listing.mic`
* - `currency`: `listing.currency`
* - `isin`: nullable `instrument.primary_isin`
* - `firstBarDate`: nullable `YYYY-MM-DD` observed bar span start (`listing.listed_from`)
* - `lastBarDate`: nullable `YYYY-MM-DD` observed bar span end (`listing.listed_to`)
* - `delistedAt`: nullable `YYYY-MM-DD` confirmed delisting date (distinct from `lastBarDate`)
*/
export interface SymbolSearchRow {
readonly listingId: number;
readonly instrumentId: number;
readonly ticker: string;
readonly classSuffix: string | null;
readonly name: string;
readonly mic: string;
readonly currency: string;
readonly isin: string | null;
readonly firstBarDate: string | null;
readonly lastBarDate: string | null;
readonly delistedAt: string | null;
}
/**
* Query passed to {@link SymbolSearchPort.searchSymbols}.
*
* Port contract:
* - Return all matching candidates for tool-side ranking and Vault fencing;
* treat `limit` as a hint only (never truncate ahead of exact-ticker matches).
* - Resolve symbol identities and matches as of `vaultCutoffTs` so future
* renames or delistings do not leak into research queries.
* - Include listings whose `firstBarDate` is unknown (`null`).
* - The tool always passes `includeDelisted: true` to the port so current
* delisting status cannot drop a candidate before Vault cutoff masking.
*/
export interface SymbolSearchQuery {
readonly query: string;
readonly limit: number;
readonly country?: SymbolSearchCountry;
readonly includeDelisted: boolean;
readonly vaultCutoffTs: number;
}
/** Read-only security-master symbol lookup port injected into `createSearchSymbolsTool`. */
export interface SymbolSearchPort {
searchSymbols(q: SymbolSearchQuery): Promise<readonly SymbolSearchRow[]>;
}
/**
* Strict Zod input schema for the `search_symbols` MCP tool.
*
* Intentionally omits `scope`, `vault_evaluation_only`, and `vaultCutoffTs`;
* `.strict()` rejects any unknown keys.
*/
export const searchSymbolsInputSchema = z
.object({
query: z
.string()
.trim()
.min(1)
.max(SEARCH_SYMBOLS_MAX_QUERY_LENGTH)
.describe(
`Ticker symbol or company name search query (trimmed, 1–${SEARCH_SYMBOLS_MAX_QUERY_LENGTH} characters).`
),
limit: z
.number()
.int()
.min(1)
.max(SEARCH_SYMBOLS_MAX_LIMIT)
.default(SEARCH_SYMBOLS_DEFAULT_LIMIT)
.describe(
`Maximum number of matching listings to return (default ${SEARCH_SYMBOLS_DEFAULT_LIMIT}, max ${SEARCH_SYMBOLS_MAX_LIMIT}).`
),
country: z
.enum(SEARCH_SYMBOLS_COUNTRIES)
.optional()
.describe('Optional exchange country filter (US or CA).'),
includeDelisted: z
.boolean()
.default(true)
.describe('Include delisted listings as of the Vault cutoff (default true).'),
})
.strict();
export type SearchSymbolsInput = z.infer<typeof searchSymbolsInputSchema>;
/** Server-side injected configuration for {@link createSearchSymbolsTool}. */
export interface SearchSymbolsToolOptions {
readonly port: SymbolSearchPort;
readonly vaultContext: Pick<VaultFenceContext, 'vaultCutoffTs'>;
}
/** Structured JSON payload serialized into the `search_symbols` MCP text result. */
export interface SearchSymbolsResultPayload {
readonly scope: 'vault_fenced';
readonly vaultCutoffTs: number;
readonly rowCount: number;
readonly truncated: boolean;
readonly rows: readonly SymbolSearchRow[];
}
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 validateNullableDate(value: unknown, field: string): string | null {
if (value === null) {
return null;
}
if (!isValidCalendarDate(value)) {
throw new Error(`Invalid port date for "${field}".`);
}
return value;
}
function validateNullableString(value: unknown, field: string): string | null {
if (value === null) {
return null;
}
if (typeof value !== 'string') {
throw new Error(`Invalid port string for "${field}".`);
}
return value;
}
function validateRequiredString(value: unknown, field: string): string {
if (typeof value !== 'string') {
throw new Error(`Invalid port string for "${field}".`);
}
return value;
}
function validateSafeInteger(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
throw new Error(`Invalid port integer for "${field}".`);
}
return value;
}
function fenceAndProjectRow(
raw: SymbolSearchRow,
vaultCutoffDate: string,
includeDelisted: boolean
): SymbolSearchRow | null {
if (typeof raw !== 'object' || raw === null) {
throw new Error('Invalid symbol search row returned by port.');
}
const listingId = validateSafeInteger(raw.listingId, 'listingId');
const instrumentId = validateSafeInteger(raw.instrumentId, 'instrumentId');
const ticker = validateRequiredString(raw.ticker, 'ticker');
const classSuffix = validateNullableString(raw.classSuffix, 'classSuffix');
const name = validateRequiredString(raw.name, 'name');
const mic = validateRequiredString(raw.mic, 'mic');
const currency = validateRequiredString(raw.currency, 'currency');
const isin = validateNullableString(raw.isin, 'isin');
const firstBarDate = validateNullableDate(raw.firstBarDate, 'firstBarDate');
const rawLastBarDate = validateNullableDate(raw.lastBarDate, 'lastBarDate');
const rawDelistedAt = validateNullableDate(raw.delistedAt, 'delistedAt');
if (firstBarDate !== null && firstBarDate > vaultCutoffDate) {
return null;
}
const lastBarDate =
rawLastBarDate !== null && rawLastBarDate > vaultCutoffDate ? vaultCutoffDate : rawLastBarDate;
const delistedAt =
rawDelistedAt !== null && rawDelistedAt > vaultCutoffDate ? null : rawDelistedAt;
if (!includeDelisted && delistedAt !== null) {
return null;
}
return {
listingId,
instrumentId,
ticker,
classSuffix,
name,
mic,
currency,
isin,
firstBarDate,
lastBarDate,
delistedAt,
};
}
function matchRank(row: SymbolSearchRow, normalizedQuery: string): number | null {
const normalizedTicker = row.ticker.toLowerCase();
if (normalizedTicker === normalizedQuery) {
return 0;
}
if (normalizedTicker.startsWith(normalizedQuery)) {
return 1;
}
if (row.name.toLowerCase().includes(normalizedQuery)) {
return 2;
}
return null;
}
function validateFactoryOptions(options: SearchSymbolsToolOptions): number {
if (typeof options !== 'object' || options === null) {
throw new MarketDataStoreValidationError(
'Invalid `options`: expected a SearchSymbolsToolOptions object.',
'options'
);
}
if (
typeof options.port !== 'object' ||
options.port === null ||
typeof options.port.searchSymbols !== 'function'
) {
throw new MarketDataStoreValidationError(
'Invalid `port`: expected a SymbolSearchPort implementing `searchSymbols`.',
'port'
);
}
return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs);
}
/**
* Creates the Vault-fenced `search_symbols` MCP tool backed by an injected
* read-only {@link SymbolSearchPort}.
*
* Enforces `scope: 'vault_fenced'`, requests candidates with
* `includeDelisted: true` so current delisting status cannot hide listings that
* were active as of the Vault cutoff, drops post-cutoff listings, clamps
* `lastBarDate` and masks future `delistedAt` against the cutoff UTC calendar
* date, ranks deterministically (exact ticker > ticker prefix > company name,
* breaking ties by ascending `listingId`), and caps results at `limit`.
*/
export function createSearchSymbolsTool(options: SearchSymbolsToolOptions): McpToolEntry {
const vaultCutoffTs = validateFactoryOptions(options);
const vaultCutoffDate = utcDateOf(vaultCutoffTs);
const { port } = options;
return defineMcpTool({
name: 'search_symbols',
description:
'Search Vault-fenced security-master listings by ticker symbol or company name and return numeric listing IDs.',
inputSchema: searchSymbolsInputSchema,
async handler(input: SearchSymbolsInput): Promise<McpToolCallResult> {
const candidates = await port.searchSymbols({
query: input.query,
limit: input.limit,
...(input.country !== undefined ? { country: input.country } : {}),
includeDelisted: true,
vaultCutoffTs,
});
if (!Array.isArray(candidates)) {
throw new Error('Invalid symbol search response returned by port.');
}
const normalizedQuery = input.query.toLowerCase();
const eligible: { readonly row: SymbolSearchRow; readonly rank: number }[] = [];
for (let i = 0; i < candidates.length; i += 1) {
const fenced = fenceAndProjectRow(
candidates[i] as SymbolSearchRow,
vaultCutoffDate,
input.includeDelisted
);
if (fenced !== null) {
const rank = matchRank(fenced, normalizedQuery);
if (rank !== null) {
eligible.push({ row: fenced, rank });
}
}
}
eligible.sort((a, b) => {
if (a.rank !== b.rank) {
return a.rank - b.rank;
}
return a.row.listingId - b.row.listingId;
});
const truncated = eligible.length > input.limit;
const limitCount = truncated ? input.limit : eligible.length;
const rows: SymbolSearchRow[] = [];
for (let i = 0; i < limitCount; i += 1) {
rows.push((eligible[i] as { readonly row: SymbolSearchRow }).row);
}
const payload: SearchSymbolsResultPayload = {
scope: 'vault_fenced',
vaultCutoffTs,
rowCount: rows.length,
truncated,
rows,
};
return {
content: [{ type: 'text', text: JSON.stringify(payload) }],
};
},
});
}

105
libs/research/src/sha256.ts Normal file
View file

@ -0,0 +1,105 @@
/**
* Browser-safe, dependency-free FIPS 180-4 SHA-256 hex digest helper.
*
* Internal module shared by `trial-ledger.ts` and `feature-library.ts`.
*/
// FIPS 180-4 SHA-256 round constants.
const SHA256_K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
]);
const UTF8_ENCODER = new TextEncoder();
export function sha256HexUtf8(text: string): string {
const bytes = UTF8_ENCODER.encode(text);
const byteLen = bytes.length;
const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0;
const buffer = new Uint8Array(paddedLen);
buffer.set(bytes);
buffer[byteLen] = 0x80;
const view = new DataView(buffer.buffer);
const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000);
const bitLenLow = (byteLen * 8) >>> 0;
view.setUint32(paddedLen - 8, bitLenHigh, false);
view.setUint32(paddedLen - 4, bitLenLow, false);
let h0 = 0x6a09e667;
let h1 = 0xbb67ae85;
let h2 = 0x3c6ef372;
let h3 = 0xa54ff53a;
let h4 = 0x510e527f;
let h5 = 0x9b05688c;
let h6 = 0x1f83d9ab;
let h7 = 0x5be0cd19;
const w = new Uint32Array(64);
for (let offset = 0; offset < paddedLen; offset += 64) {
for (let i = 0; i < 16; i += 1) {
w[i] = view.getUint32(offset + i * 4, false);
}
for (let i = 16; i < 64; i += 1) {
const w15 = w[i - 15] as number;
const w2 = w[i - 2] as number;
const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3);
const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10);
w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0;
}
let a = h0;
let b = h1;
let c = h2;
let d = h3;
let e = h4;
let f = h5;
let g = h6;
let h = h7;
for (let i = 0; i < 64; i += 1) {
const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
const ch = (e & f) ^ (~e & g);
const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0;
const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
const maj = (a & b) ^ (a & c) ^ (b & c);
const temp2 = (s0 + maj) | 0;
h = g;
g = f;
f = e;
e = (d + temp1) | 0;
d = c;
c = b;
b = a;
a = (temp1 + temp2) | 0;
}
h0 = (h0 + a) >>> 0;
h1 = (h1 + b) >>> 0;
h2 = (h2 + c) >>> 0;
h3 = (h3 + d) >>> 0;
h4 = (h4 + e) >>> 0;
h5 = (h5 + f) >>> 0;
h6 = (h6 + g) >>> 0;
h7 = (h7 + h) >>> 0;
}
return (
h0.toString(16).padStart(8, '0') +
h1.toString(16).padStart(8, '0') +
h2.toString(16).padStart(8, '0') +
h3.toString(16).padStart(8, '0') +
h4.toString(16).padStart(8, '0') +
h5.toString(16).padStart(8, '0') +
h6.toString(16).padStart(8, '0') +
h7.toString(16).padStart(8, '0')
);
}

View file

@ -18,6 +18,7 @@ import {
VaultHoldoutFenceError,
applyVaultFence,
} from './market-data-store';
import { sha256HexUtf8 } from './sha256';
export const TRIAL_STAGES = ['signal_ic', 'event_study', 'screen', 'engine_backtest'] as const;
export type TrialStage = (typeof TRIAL_STAGES)[number];
@ -222,106 +223,6 @@ const SELECT_TRIAL_COLUMNS = `
kurtosis,
daily_series`;
// FIPS 180-4 SHA-256 round constants.
const SHA256_K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
]);
const UTF8_ENCODER = new TextEncoder();
function sha256HexUtf8(text: string): string {
const bytes = UTF8_ENCODER.encode(text);
const byteLen = bytes.length;
const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0;
const buffer = new Uint8Array(paddedLen);
buffer.set(bytes);
buffer[byteLen] = 0x80;
const view = new DataView(buffer.buffer);
const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000);
const bitLenLow = (byteLen * 8) >>> 0;
view.setUint32(paddedLen - 8, bitLenHigh, false);
view.setUint32(paddedLen - 4, bitLenLow, false);
let h0 = 0x6a09e667;
let h1 = 0xbb67ae85;
let h2 = 0x3c6ef372;
let h3 = 0xa54ff53a;
let h4 = 0x510e527f;
let h5 = 0x9b05688c;
let h6 = 0x1f83d9ab;
let h7 = 0x5be0cd19;
const w = new Uint32Array(64);
for (let offset = 0; offset < paddedLen; offset += 64) {
for (let i = 0; i < 16; i += 1) {
w[i] = view.getUint32(offset + i * 4, false);
}
for (let i = 16; i < 64; i += 1) {
const w15 = w[i - 15] as number;
const w2 = w[i - 2] as number;
const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3);
const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10);
w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0;
}
let a = h0;
let b = h1;
let c = h2;
let d = h3;
let e = h4;
let f = h5;
let g = h6;
let h = h7;
for (let i = 0; i < 64; i += 1) {
const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
const ch = (e & f) ^ (~e & g);
const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0;
const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
const maj = (a & b) ^ (a & c) ^ (b & c);
const temp2 = (s0 + maj) | 0;
h = g;
g = f;
f = e;
e = (d + temp1) | 0;
d = c;
c = b;
b = a;
a = (temp1 + temp2) | 0;
}
h0 = (h0 + a) >>> 0;
h1 = (h1 + b) >>> 0;
h2 = (h2 + c) >>> 0;
h3 = (h3 + d) >>> 0;
h4 = (h4 + e) >>> 0;
h5 = (h5 + f) >>> 0;
h6 = (h6 + g) >>> 0;
h7 = (h7 + h) >>> 0;
}
return (
h0.toString(16).padStart(8, '0') +
h1.toString(16).padStart(8, '0') +
h2.toString(16).padStart(8, '0') +
h3.toString(16).padStart(8, '0') +
h4.toString(16).padStart(8, '0') +
h5.toString(16).padStart(8, '0') +
h6.toString(16).padStart(8, '0') +
h7.toString(16).padStart(8, '0')
);
}
function compareAscii(a: string, b: string): number {
return a < b ? -1 : a > b ? 1 : 0;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,469 @@
import { describe, expect, test } from 'bun:test';
import {
type AppendFindingResult,
FILE_FINDING_ERROR_FILING_FAILED,
FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT,
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
FILE_FINDING_MAX_EVIDENCE_REFS,
FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH,
FILE_FINDING_MAX_REF_LENGTH,
FILE_FINDING_MAX_SUMMARY_LENGTH,
FILE_FINDING_MAX_TITLE_LENGTH,
FILE_FINDING_MAX_TRIAL_REFS,
type FileFindingResultPayload,
type FiledFindingRecord,
type FindingWritePort,
type TrialRefLookupPort,
areFiledFindingPayloadsEqual,
createFileFindingTool,
} from '../src/mcp/index';
// Compile-time guard: the write port exposes exactly one append method (no update/delete).
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2
? true
: false;
const writePortKeysAreAppendOnly: Equal<keyof FindingWritePort, 'appendFinding'> = true;
const FIXED_EPOCH_MS = Date.UTC(2025, 5, 2, 15, 30, 0);
interface RecordingPort {
readonly calls: { record: FiledFindingRecord; idempotencyKey: string | undefined }[];
readonly port: FindingWritePort;
}
function recordingPort(
respond: (record: FiledFindingRecord, key: string | undefined) => unknown
): RecordingPort {
const calls: RecordingPort['calls'] = [];
return {
calls,
port: {
async appendFinding(record, idempotencyKey) {
calls.push({ record, idempotencyKey });
return respond(record, idempotencyKey) as AppendFindingResult;
},
},
};
}
function createdEcho(record: FiledFindingRecord): AppendFindingResult {
return { status: 'created', id: record.id, createdAt: record.createdAt };
}
function lookupFrom(
answer: (ref: string) => unknown
): { readonly queried: string[]; readonly port: TrialRefLookupPort } {
const queried: string[] = [];
return {
queried,
port: {
hasResearchVisibleTrial(ref: string) {
queried.push(ref);
return answer(ref) as boolean;
},
},
};
}
function counter<T>(fn: () => T): { calls: number; fn: () => T } {
const state = {
calls: 0,
fn: () => {
state.calls += 1;
return fn();
},
};
return state;
}
const validArgs = {
kind: 'finding',
title: 'QA filing',
summary: 'Research-visible summary.',
trialRefs: ['trial-1'],
};
function parseReceipt(text: string | undefined): FileFindingResultPayload {
return JSON.parse(text ?? '') as FileFindingResultPayload;
}
describe('MCP file_finding QA edge cases', () => {
test('write port type exposes only appendFinding', () => {
expect(writePortKeysAreAppendOnly).toBe(true);
});
test('deduplicates trial refs before lookup, verifies in sorted order, and short-circuits on the first unavailable ref', async () => {
const rec = recordingPort(createdEcho);
const lookup = lookupFrom(ref => ref !== 'trial-b');
const tool = createFileFindingTool({
port: rec.port,
trialLookup: lookup.port,
newId: () => 'id-1',
now: () => FIXED_EPOCH_MS,
});
const res = await tool.execute({
...validArgs,
trialRefs: ['trial-c', 'trial-a', 'trial-b', 'trial-a', 'trial-c'],
});
expect(res.isError).toBe(true);
expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
expect(lookup.queried).toEqual(['trial-a', 'trial-b']);
expect(rec.calls).toHaveLength(0);
});
test('accepts a synchronous boolean lookup and queries each unique ref exactly once on success', async () => {
const rec = recordingPort(createdEcho);
const lookup = lookupFrom(() => true);
const tool = createFileFindingTool({
port: rec.port,
trialLookup: lookup.port,
newId: () => 'id-sync',
now: () => FIXED_EPOCH_MS,
});
const res = await tool.execute({ ...validArgs, trialRefs: ['t2', 't1', 't2', 't1'] });
expect(res.isError).toBeUndefined();
expect(lookup.queried).toEqual(['t1', 't2']);
expect(rec.calls).toHaveLength(1);
expect(rec.calls[0]?.record.trialRefs).toEqual(['t1', 't2']);
});
test('treats non-boolean lookup answers as a filing failure with zero writes and no metadata generation', async () => {
for (const answer of [1, 'true', null, undefined, {}]) {
const rec = recordingPort(createdEcho);
const ids = counter(() => 'never');
const clock = counter(() => FIXED_EPOCH_MS);
const tool = createFileFindingTool({
port: rec.port,
trialLookup: lookupFrom(() => answer).port,
newId: ids.fn,
now: clock.fn,
});
const res = await tool.execute(validArgs);
expect(res.isError).toBe(true);
expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED);
expect(rec.calls).toHaveLength(0);
expect(ids.calls).toBe(0);
expect(clock.calls).toBe(0);
}
});
test('rejects unusable generated ids and clock values with a fixed error and zero writes', async () => {
const badSources: readonly {
readonly label: string;
readonly newId: () => string;
readonly now: () => Date | number;
}[] = [
{ label: 'empty id', newId: () => '', now: () => FIXED_EPOCH_MS },
{ label: 'blank id', newId: () => ' ', now: () => FIXED_EPOCH_MS },
{ label: 'non-string id', newId: () => 42 as unknown as string, now: () => FIXED_EPOCH_MS },
{
label: 'throwing id source',
newId: () => {
throw new Error('postgres://u:p@db/x id sequence exhausted');
},
now: () => FIXED_EPOCH_MS,
},
{ label: 'NaN clock', newId: () => 'id-1', now: () => Number.NaN },
{ label: 'infinite clock', newId: () => 'id-1', now: () => Number.POSITIVE_INFINITY },
{ label: 'invalid Date', newId: () => 'id-1', now: () => new Date('not-a-date') },
{ label: 'out-of-range epoch', newId: () => 'id-1', now: () => 9e15 },
{ label: 'string clock', newId: () => 'id-1', now: () => '2025-01-01' as unknown as number },
{
label: 'throwing clock',
newId: () => 'id-1',
now: () => {
throw new Error('clock unavailable at /srv/secret.ts:1:1');
},
},
];
for (const source of badSources) {
const rec = recordingPort(createdEcho);
const tool = createFileFindingTool({
port: rec.port,
trialLookup: lookupFrom(() => true).port,
newId: source.newId,
now: source.now,
});
const res = await tool.execute(validArgs);
expect({ label: source.label, isError: res.isError }).toEqual({
label: source.label,
isError: true,
});
expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED);
expect(rec.calls).toHaveLength(0);
}
});
test('stores Date and epoch clock values as identical UTC ISO timestamps', async () => {
const fromDate = recordingPort(createdEcho);
const fromEpoch = recordingPort(createdEcho);
const lookup = lookupFrom(() => true).port;
await createFileFindingTool({
port: fromDate.port,
trialLookup: lookup,
newId: () => 'id-d',
now: () => new Date(FIXED_EPOCH_MS),
}).execute(validArgs);
await createFileFindingTool({
port: fromEpoch.port,
trialLookup: lookup,
newId: () => 'id-e',
now: () => FIXED_EPOCH_MS,
}).execute(validArgs);
expect(fromDate.calls[0]?.record.createdAt).toBe('2025-06-02T15:30:00.000Z');
expect(fromEpoch.calls[0]?.record.createdAt).toBe('2025-06-02T15:30:00.000Z');
});
test('passes the trimmed idempotency key to the port and undefined when omitted', async () => {
const rec = recordingPort(createdEcho);
const tool = createFileFindingTool({
port: rec.port,
trialLookup: lookupFrom(() => true).port,
newId: () => 'id-k',
now: () => FIXED_EPOCH_MS,
});
await tool.execute({ ...validArgs, idempotencyKey: '\t retry-key-7 \n' });
await tool.execute(validArgs);
expect(rec.calls.map(c => c.idempotencyKey)).toEqual(['retry-key-7', undefined]);
});
test('receipt reflects the port-stored id and timestamp on replay, not freshly generated metadata', async () => {
const rec = recordingPort(() => ({
status: 'replayed',
id: 'stored-original',
createdAt: '2024-12-31T23:59:59.000Z',
}));
const tool = createFileFindingTool({
port: rec.port,
trialLookup: lookupFrom(() => true).port,
newId: () => 'fresh-id',
now: () => FIXED_EPOCH_MS,
});
const res = await tool.execute({ ...validArgs, idempotencyKey: 'k' });
expect(res.isError).toBeUndefined();
expect(parseReceipt(res.content[0]?.text)).toEqual({
id: 'stored-original',
createdAt: '2024-12-31T23:59:59.000Z',
created: false,
});
});
test('maps malformed port outcomes to the fixed filing error and conflict to the fixed conflict error', async () => {
const malformed: readonly unknown[] = [
null,
undefined,
'created',
{},
{ status: 'updated', id: 'x', createdAt: 'y' },
{ status: 'created', id: '', createdAt: '2025-01-01T00:00:00.000Z' },
{ status: 'created', id: 'x' },
{ status: 'replayed', id: 7, createdAt: '2025-01-01T00:00:00.000Z' },
];
for (const outcome of malformed) {
const tool = createFileFindingTool({
port: recordingPort(() => outcome).port,
trialLookup: lookupFrom(() => true).port,
newId: () => 'id-m',
now: () => FIXED_EPOCH_MS,
});
const res = await tool.execute(validArgs);
expect(res.isError).toBe(true);
expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED);
}
const conflictTool = createFileFindingTool({
port: recordingPort(() => ({ status: 'conflict' })).port,
trialLookup: lookupFrom(() => true).port,
newId: () => 'id-c',
now: () => FIXED_EPOCH_MS,
});
const conflict = await conflictTool.execute({ ...validArgs, idempotencyKey: 'k' });
expect(conflict.isError).toBe(true);
expect(conflict.content[0]?.text).toBe(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT);
});
test('accepts every field exactly at its hard limit', async () => {
const rec = recordingPort(createdEcho);
const tool = createFileFindingTool({
port: rec.port,
trialLookup: lookupFrom(() => true).port,
newId: () => 'id-limit',
now: () => FIXED_EPOCH_MS,
});
const trialRefs = Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS }, (_, i) =>
`t${String(i).padStart(2, '0')}`.padEnd(FILE_FINDING_MAX_REF_LENGTH, 'x')
);
const evidenceRefs = Array.from({ length: FILE_FINDING_MAX_EVIDENCE_REFS }, (_, i) =>
`e${String(i).padStart(2, '0')}`.padEnd(FILE_FINDING_MAX_REF_LENGTH, 'y')
);
const res = await tool.execute({
kind: 'dead_end',
title: 'T'.repeat(FILE_FINDING_MAX_TITLE_LENGTH),
summary: 'S'.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH),
trialRefs,
evidenceRefs,
idempotencyKey: 'K'.repeat(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH),
});
expect(res.isError).toBeUndefined();
expect(rec.calls).toHaveLength(1);
expect(rec.calls[0]?.record.trialRefs).toHaveLength(FILE_FINDING_MAX_TRIAL_REFS);
expect(rec.calls[0]?.record.evidenceRefs).toHaveLength(FILE_FINDING_MAX_EVIDENCE_REFS);
});
test('measures limits after trimming, so padded at-limit text is accepted', async () => {
const rec = recordingPort(createdEcho);
const tool = createFileFindingTool({
port: rec.port,
trialLookup: lookupFrom(() => true).port,
newId: () => 'id-trim',
now: () => FIXED_EPOCH_MS,
});
const res = await tool.execute({
...validArgs,
title: ` ${'T'.repeat(FILE_FINDING_MAX_TITLE_LENGTH)} `,
});
expect(res.isError).toBeUndefined();
expect(rec.calls[0]?.record.title).toHaveLength(FILE_FINDING_MAX_TITLE_LENGTH);
});
test('validation errors never echo submitted text, refs, or keys', async () => {
const sentinel = 'HOLDOUT_OBSERVATION_SENTINEL_0x5f3';
const rec = recordingPort(createdEcho);
const tool = createFileFindingTool({
port: rec.port,
trialLookup: lookupFrom(() => true).port,
newId: () => 'id-v',
now: () => FIXED_EPOCH_MS,
});
const cases: readonly Record<string, unknown>[] = [
{ ...validArgs, summary: `${sentinel} `.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH) },
{ ...validArgs, title: sentinel.repeat(20) },
{ ...validArgs, trialRefs: [sentinel.repeat(10)] },
{ ...validArgs, evidenceRefs: [sentinel.repeat(10)] },
{ ...validArgs, idempotencyKey: sentinel.repeat(5) },
{ ...validArgs, kind: sentinel },
{ ...validArgs, [sentinel]: 1.2345 },
{ ...validArgs, observations: [{ date: '2025-09-01', value: sentinel }] },
];
for (const args of cases) {
const res = await tool.execute(args);
expect(res.isError).toBe(true);
expect(res.content[0]?.text).not.toContain(sentinel);
}
expect(rec.calls).toHaveLength(0);
});
test('concurrent same-key filings across two tool instances store one row (promise barrier, no timers)', async () => {
const stored: FiledFindingRecord[] = [];
const byKey = new Map<string, FiledFindingRecord>();
let releaseFirst: () => void = () => undefined;
const firstHeld = new Promise<void>(resolve => {
releaseFirst = resolve;
});
let secondArrived: () => void = () => undefined;
const secondReached = new Promise<void>(resolve => {
secondArrived = resolve;
});
let callIndex = 0;
const port: FindingWritePort = {
async appendFinding(record, key) {
callIndex += 1;
const mine = callIndex;
// Atomic compare-and-append (no await between read and write).
let outcome: AppendFindingResult;
const existing = key === undefined ? undefined : byKey.get(key);
if (existing === undefined) {
stored.push(record);
if (key !== undefined) {
byKey.set(key, record);
}
outcome = { status: 'created', id: record.id, createdAt: record.createdAt };
} else if (areFiledFindingPayloadsEqual(existing, record)) {
outcome = { status: 'replayed', id: existing.id, createdAt: existing.createdAt };
} else {
outcome = { status: 'conflict' };
}
if (mine === 1) {
await firstHeld;
} else {
secondArrived();
}
return outcome;
},
};
const lookup = lookupFrom(() => true).port;
const toolA = createFileFindingTool({
port,
trialLookup: lookup,
newId: () => 'inst-a',
now: () => FIXED_EPOCH_MS,
});
const toolB = createFileFindingTool({
port,
trialLookup: lookup,
newId: () => 'inst-b',
now: () => FIXED_EPOCH_MS + 1_000,
});
const args = { ...validArgs, idempotencyKey: 'concurrent' };
const pendingA = toolA.execute(args);
const pendingB = toolB.execute(args);
await secondReached;
releaseFirst();
const [resA, resB] = await Promise.all([pendingA, pendingB]);
expect(stored).toHaveLength(1);
expect(parseReceipt(resA.content[0]?.text)).toEqual({
id: 'inst-a',
createdAt: new Date(FIXED_EPOCH_MS).toISOString(),
created: true,
});
expect(parseReceipt(resB.content[0]?.text)).toEqual({
id: 'inst-a',
createdAt: new Date(FIXED_EPOCH_MS).toISOString(),
created: false,
});
});
test('payload equality helper ignores server metadata and is order-sensitive on normalized refs', () => {
const base = {
kind: 'finding' as const,
title: 't',
summary: 's',
trialRefs: ['a', 'b'],
evidenceRefs: [],
};
expect(
areFiledFindingPayloadsEqual(
{ ...base, id: 'x', createdAt: '1', status: 'pending_review' } as FiledFindingRecord,
{ ...base, id: 'y', createdAt: '2', status: 'pending_review' } as FiledFindingRecord
)
).toBe(true);
expect(areFiledFindingPayloadsEqual(base, { ...base, trialRefs: ['a'] })).toBe(false);
expect(areFiledFindingPayloadsEqual(base, { ...base, evidenceRefs: ['e'] })).toBe(false);
expect(areFiledFindingPayloadsEqual(base, { ...base, title: 'T' })).toBe(false);
});
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,581 @@
import { describe, expect, test } from 'bun:test';
import {
createMcpServer,
createReadKnowledgeTool,
type FindingQuery,
type FindingRecord,
type KnowledgePort,
type LibraryCardQuery,
type LibraryCardRecord,
type ProviderCaveatQuery,
type ProviderCaveatRecord,
READ_KNOWLEDGE_MAX_LIMIT,
READ_KNOWLEDGE_MAX_QUERY_LENGTH,
READ_KNOWLEDGE_MAX_TEXT_LENGTH,
type ReadKnowledgeResultPayload,
} from '../src/mcp/index';
// QA fixtures: deterministic in-memory KnowledgePort (no network, no Postgres,
// no filesystem). All timestamps are pinned ISO strings; shuffles use a seeded PRNG.
const SECRET = 'postgres://admin:super-secret@10.0.0.51:5432/trading_bot';
function card(id: string, o: Partial<LibraryCardRecord> = {}): LibraryCardRecord {
return {
id,
title: o.title ?? `Card ${id}`,
tags: o.tags ?? ['methodology'],
summary: o.summary ?? `Summary ${id}`,
body: o.body ?? `Body ${id}`,
};
}
function finding(id: string, o: Partial<FindingRecord> = {}): FindingRecord {
return {
id,
title: o.title ?? `Finding ${id}`,
status: o.status ?? 'confirmed',
createdAt: o.createdAt ?? '2025-01-15T12:00:00.000Z',
summary: o.summary ?? `Finding summary ${id}`,
trialRefs: o.trialRefs ?? [`trial-${id}`],
evidenceRefs: o.evidenceRefs ?? [`ev-${id}`],
};
}
function caveat(id: string, o: Partial<ProviderCaveatRecord> = {}): ProviderCaveatRecord {
return {
id,
provider: o.provider ?? 'eodhd',
dataset: o.dataset ?? `dataset_${id}`,
caveat: o.caveat ?? `Caveat ${id}`,
createdAt: o.createdAt ?? '2025-01-20T08:30:00.000Z',
};
}
interface PortImpl {
readonly library?: (q: LibraryCardQuery) => unknown;
readonly findings?: (q: FindingQuery) => unknown;
readonly caveats?: (q: ProviderCaveatQuery) => unknown;
}
function makePort(impl: PortImpl): { port: KnowledgePort; calls: string[] } {
const calls: string[] = [];
const port: KnowledgePort = {
listLibraryCards(q) {
calls.push('listLibraryCards');
return (impl.library ?? (() => Promise.resolve([])))(q) as Promise<
readonly LibraryCardRecord[]
>;
},
listFindings(q) {
calls.push('listFindings');
return (impl.findings ?? (() => Promise.resolve([])))(q) as Promise<
readonly FindingRecord[]
>;
},
listProviderCaveats(q) {
calls.push('listProviderCaveats');
return (impl.caveats ?? (() => Promise.resolve([])))(q) as Promise<
readonly ProviderCaveatRecord[]
>;
},
};
return { port, calls };
}
function staticPort(
library: readonly LibraryCardRecord[],
findings: readonly FindingRecord[],
caveats: readonly ProviderCaveatRecord[]
): { port: KnowledgePort; calls: string[] } {
return makePort({
library: async () => library,
findings: async () => findings,
caveats: async () => caveats,
});
}
async function call(
port: KnowledgePort,
args: Record<string, unknown> | undefined
): Promise<{ isError: boolean; text: string; payload: ReadKnowledgeResultPayload | null }> {
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [createReadKnowledgeTool({ port })],
});
const params: Record<string, unknown> = { name: 'read_knowledge' };
if (args !== undefined) {
params.arguments = args;
}
const raw = await server.handleMessage(
JSON.stringify({ jsonrpc: '2.0', id: 'qa', method: 'tools/call', params })
);
expect(raw).not.toBeNull();
const parsed = JSON.parse(raw as string) as {
result: { isError?: boolean; content: { type: string; text: string }[] };
};
const isError = parsed.result.isError === true;
const text = parsed.result.content[0]?.text ?? '';
return { isError, text, payload: isError ? null : (JSON.parse(text) as ReadKnowledgeResultPayload) };
}
function expectSanitized(res: { isError: boolean; text: string }): void {
expect(res.isError).toBe(true);
expect(res.text).toMatch(/^[A-Za-z][A-Za-z0-9_]*: Tool execution failed\.$/);
for (const leak of ['super-secret', '10.0.0.51', 'trading_bot', 'postgres://', 'db.ts', ' at ']) {
expect(res.text).not.toContain(leak);
}
}
function deepFreeze<T>(value: T): T {
if (typeof value === 'object' && value !== null) {
for (const v of Object.values(value)) {
deepFreeze(v);
}
Object.freeze(value);
}
return value;
}
// mulberry32 — seeded PRNG for reproducible shuffles.
function seededShuffle<T>(items: readonly T[], seed: number): T[] {
let s = seed >>> 0;
const rand = (): number => {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
const out = [...items];
for (let i = out.length - 1; i > 0; i -= 1) {
const j = Math.floor(rand() * (i + 1));
[out[i], out[j]] = [out[j] as T, out[i] as T];
}
return out;
}
describe('read_knowledge QA: port failures and malformed port output', () => {
test('non-Error rejections and synchronous throws carrying connection strings are sanitized', async () => {
const cases: PortImpl[] = [
{ library: () => Promise.reject(SECRET) },
{ findings: () => Promise.reject({ message: SECRET, stack: 'at /srv/db.ts:1' }) },
{
caveats: () => {
throw new Error(SECRET);
},
},
{
library: () => {
const err = new Error(SECRET);
err.name = SECRET;
throw err;
},
},
];
for (const impl of cases) {
const { port } = makePort(impl);
const res = await call(port, { query: 'alpha' });
expectSanitized(res);
}
});
test('malformed port responses map to a sanitized isError without echoing record contents', async () => {
const badResponses: PortImpl[] = [
{ library: async () => SECRET },
{ library: async () => undefined },
{ library: async () => [null] },
{ library: async () => [{ ...card('c1'), id: 42 }] },
{ library: async () => [{ ...card('c1'), tags: [SECRET, 7] }] },
{ library: async () => [{ ...card('c1'), tags: SECRET }] },
{ findings: async () => [{ ...finding('f1'), trialRefs: undefined }] },
{ findings: async () => [{ ...finding('f1'), createdAt: 1_700_000_000_000 }] },
{ caveats: async () => [{ ...caveat('v1'), caveat: { text: SECRET } }] },
{ caveats: async () => ({ rows: [caveat('v1')] }) },
];
for (const impl of badResponses) {
const { port } = makePort(impl);
const res = await call(port, {});
expectSanitized(res);
}
});
// Regression: port calls were started eagerly inside the Promise.all array literal, so a
// synchronous throw from a later source abandoned an earlier source's rejected promise.
// Bun treats that unhandled rejection as fatal: the MCP stdio process exits 1 after replying
// and prints the raw error (including any connection string) to stderr. Bun's test runner
// also reports it as an error between tests, so the scenario runs in a child process.
test('earlier async rejection combined with a later synchronous throw does not crash the process', () => {
const indexPath = new URL('../src/mcp/index.ts', import.meta.url).pathname;
const script = `
import { createMcpServer, createReadKnowledgeTool } from ${JSON.stringify(indexPath)};
const secret = ${JSON.stringify(SECRET)};
const combos = [
{ listLibraryCards: () => Promise.reject(new Error(secret)), listFindings: () => { throw new Error('sync'); }, listProviderCaveats: async () => [] },
{ listLibraryCards: () => Promise.reject(new Error(secret)), listFindings: async () => [], listProviderCaveats: () => { throw new Error('sync'); } },
{ listLibraryCards: async () => [], listFindings: () => Promise.reject(new Error(secret)), listProviderCaveats: () => { throw new Error('sync'); } },
];
for (const port of combos) {
const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [createReadKnowledgeTool({ port })] });
const raw = await server.handleMessage(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'read_knowledge', arguments: {} } }));
console.log(JSON.parse(raw).result.content[0].text);
}
await new Promise(resolve => setTimeout(resolve, 20));
console.log('DONE');
`;
const proc = Bun.spawnSync([process.execPath, '-e', script], {
stdout: 'pipe',
stderr: 'pipe',
timeout: 30_000,
});
const stdout = proc.stdout.toString();
const stderr = proc.stderr.toString();
expect(stdout.trim().split('\n')).toEqual([
'Error: Tool execution failed.',
'Error: Tool execution failed.',
'Error: Tool execution failed.',
'DONE',
]);
expect(stderr).not.toContain('super-secret');
expect(proc.exitCode).toBe(0);
});
});
describe('read_knowledge QA: read-only port usage', () => {
test('never calls write-like methods present on the injected object and calls each read method at most once', async () => {
const writes: string[] = [];
const base = staticPort([card('c1')], [finding('f1')], [caveat('v1')]);
const port = Object.assign(base.port, {
fileFinding: () => writes.push('fileFinding'),
upsertCard: () => writes.push('upsertCard'),
deleteCaveat: () => writes.push('deleteCaveat'),
});
for (const args of [{}, { source: 'library' }, { id: 'f1' }, { query: 'card', limit: 1 }]) {
base.calls.length = 0;
const res = await call(port, args);
expect(res.isError).toBe(false);
expect(new Set(base.calls).size).toBe(base.calls.length);
}
expect(writes).toEqual([]);
});
test('does not mutate deeply frozen port records and returns copies of array fields', async () => {
const lib = deepFreeze([card('c1', { tags: ['Alpha', 'beta'], body: 'b'.repeat(5000) })]);
const fin = deepFreeze([finding('f1', { title: 'Alpha finding' })]);
const cav = deepFreeze([caveat('v1', { dataset: 'alpha_ds', caveat: 'c'.repeat(5000) })]);
const snapshot = JSON.stringify([lib, fin, cav]);
const { port } = staticPort(lib, fin, cav);
const res = await call(port, { query: 'alpha', tags: ['ALPHA'] });
expect(res.isError).toBe(false);
expect(res.payload?.rowCount).toBe(3);
expect(JSON.stringify([lib, fin, cav])).toBe(snapshot);
});
test('omitted tools/call arguments use defaults and call all three sources with an empty selector', async () => {
const seen: unknown[] = [];
const { port, calls } = makePort({
library: async q => {
seen.push(q);
return [card('c1')];
},
findings: async q => {
seen.push(q);
return [finding('f1')];
},
caveats: async q => {
seen.push(q);
return [caveat('v1')];
},
});
const res = await call(port, undefined);
expect(res.isError).toBe(false);
expect(calls.sort()).toEqual(['listFindings', 'listLibraryCards', 'listProviderCaveats']);
expect(seen).toEqual([{}, {}, {}]);
expect(res.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 });
});
});
describe('read_knowledge QA: input boundaries', () => {
test('accepts query at exactly the cap, including when surrounding whitespace is trimmed', async () => {
const atCap = 'q'.repeat(READ_KNOWLEDGE_MAX_QUERY_LENGTH);
const seen: (string | undefined)[] = [];
const { port } = makePort({
library: async q => {
seen.push(q.query);
return [card('c1', { title: `x${atCap}x` })];
},
});
for (const query of [atCap, ` ${atCap}\t\n `]) {
const res = await call(port, { source: 'library', query });
expect(res.isError).toBe(false);
expect(res.payload?.rows.map(r => r.id)).toEqual(['c1']);
}
expect(seen).toEqual([atCap, atCap]);
});
test('accepts limit 1 and limit max as boundary values', async () => {
const lib = Array.from({ length: READ_KNOWLEDGE_MAX_LIMIT + 5 }, (_, i) =>
card(`c${String(i).padStart(3, '0')}`)
);
const { port } = staticPort(lib, [], []);
const one = await call(port, { limit: 1 });
const max = await call(port, { limit: READ_KNOWLEDGE_MAX_LIMIT });
expect(one.payload?.rows.map(r => r.id)).toEqual(['c000']);
expect(max.payload?.rowCount).toBe(READ_KNOWLEDGE_MAX_LIMIT);
expect(max.payload?.rows.at(-1)?.id).toBe('c099');
});
test('rejects null-valued optional selectors and non-array tags before calling the port', async () => {
for (const args of [
{ query: null },
{ id: null },
{ tags: 'alpha' },
{ tags: [1] },
{ provider: ['eodhd'] },
{ source: null },
{ limit: null },
{ limit: Number.POSITIVE_INFINITY },
]) {
const { port, calls } = staticPort([card('c1')], [], []);
const res = await call(port, args);
expect(res.isError).toBe(true);
expect(res.text).toContain('Invalid arguments for tool "read_knowledge"');
expect(calls).toEqual([]);
}
});
});
describe('read_knowledge QA: matching semantics', () => {
test('free-text query does not match on id, status, createdAt, or trial/evidence refs alone', async () => {
const { port } = staticPort(
[card('zeta-card', { title: 'A', tags: ['b'], summary: 'c', body: 'zeta in body only' })],
[
finding('zeta-finding', {
title: 'A',
summary: 'c',
status: 'zeta',
createdAt: 'zeta',
trialRefs: ['zeta'],
evidenceRefs: ['zeta'],
}),
],
[caveat('zeta-caveat', { provider: 'p', dataset: 'd', caveat: 'c', createdAt: 'zeta' })]
);
const res = await call(port, { query: 'zeta' });
expect(res.payload).toEqual({
rowCount: 0,
sources: { library: 0, findings: 0, provider_caveats: 0 },
rows: [],
});
});
test('provider filter is exact (not substring) and tags filter requires whole-tag equality', async () => {
const { port } = staticPort(
[card('c-full', { tags: ['momentum'] }), card('c-partial', { tags: ['momentum-crash'] })],
[],
[caveat('v-eodhd', { provider: 'eodhd' }), caveat('v-eod', { provider: 'eod' })]
);
const byProvider = await call(port, { source: 'provider_caveats', provider: 'EOD' });
const byTag = await call(port, { source: 'library', tags: ['Momentum'] });
expect(byProvider.payload?.rows.map(r => r.id)).toEqual(['v-eod']);
expect(byTag.payload?.rows.map(r => r.id)).toEqual(['c-full']);
});
test('provider matched in free text ranks below a dataset match for caveats', async () => {
const { port } = staticPort(
[],
[],
[
caveat('a-provider', { provider: 'quantmedia', dataset: 'bars', caveat: 'x' }),
caveat('z-dataset', { provider: 'eodhd', dataset: 'quantmedia_filings', caveat: 'x' }),
]
);
const res = await call(port, { query: 'QuantMedia' });
expect(res.payload?.rows.map(r => r.id)).toEqual(['z-dataset', 'a-provider']);
});
test('id lookup still honours source-specific filters: tag mismatch drops the card but keeps other sources under all', async () => {
const { port } = staticPort(
[card('shared', { tags: ['risk'] })],
[finding('shared')],
[caveat('shared', { provider: 'polygon' })]
);
const res = await call(port, { id: 'shared', tags: ['momentum'], provider: 'eodhd' });
expect(res.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual(['findings:shared']);
expect(res.payload?.sources).toEqual({ library: 0, findings: 1, provider_caveats: 0 });
});
test('regex and wildcard metacharacters in query are matched literally', async () => {
const { port } = staticPort(
[card('c-literal', { title: 'Sharpe (annualised) * sqrt(252)' }), card('c-plain', { title: 'Sharpe annualised' })],
[finding('f-dot', { summary: 'a.b' }), finding('f-any', { summary: 'axb' })],
[caveat('v-pct', { caveat: '100% adjusted' }), caveat('v-none', { caveat: '100 adjusted' })]
);
const paren = await call(port, { query: '(annualised) *' });
const dot = await call(port, { query: 'a.b' });
const pct = await call(port, { query: '100%' });
expect(paren.payload?.rows.map(r => r.id)).toEqual(['c-literal']);
expect(dot.payload?.rows.map(r => r.id)).toEqual(['f-dot']);
expect(pct.payload?.rows.map(r => r.id)).toEqual(['v-pct']);
});
test('case-insensitive matching handles non-ASCII text', async () => {
const { port } = staticPort(
[card('c1', { title: 'Étude des rendements' })],
[finding('f1', { summary: 'ÜBERRENDITE nach Ankündigung' })],
[]
);
const res = await call(port, { query: 'étude' });
const res2 = await call(port, { query: 'überrendite' });
expect(res.payload?.rows.map(r => r.id)).toEqual(['c1']);
expect(res2.payload?.rows.map(r => r.id)).toEqual(['f1']);
});
test('projects exactly the documented fields for findings and caveats, dropping extra port fields', async () => {
const extraFinding = { ...finding('f1'), holdoutPnl: 123, dsn: SECRET } as FindingRecord;
const extraCaveat = { ...caveat('v1'), internalNote: SECRET } as ProviderCaveatRecord;
const { port } = staticPort([], [extraFinding], [extraCaveat]);
const res = await call(port, {});
expect(res.text).not.toContain('super-secret');
expect(res.text).not.toContain('holdoutPnl');
expect(res.payload?.rows).toEqual([
{
source: 'findings',
id: 'f1',
title: 'Finding f1',
status: 'confirmed',
createdAt: '2025-01-15T12:00:00.000Z',
summary: 'Finding summary f1',
trialRefs: ['trial-f1'],
evidenceRefs: ['ev-f1'],
truncated: false,
},
{
source: 'provider_caveats',
id: 'v1',
provider: 'eodhd',
dataset: 'dataset_v1',
caveat: 'Caveat v1',
createdAt: '2025-01-20T08:30:00.000Z',
truncated: false,
},
]);
});
});
describe('read_knowledge QA: deterministic ranking and limit', () => {
test('seeded permutations of a mixed fixture replay to identical rows and counts at every limit', async () => {
const lib = [
card('m-title', { title: 'Drift study', summary: 's' }),
card('a-tag', { title: 'x', tags: ['drift'] }),
card('Q-sum', { title: 'x', summary: 'post drift' }),
card('shared', { title: 'Drift shared', summary: 's' }),
];
const fin = [
finding('shared', { title: 'Drift finding' }),
finding('b-sum', { title: 'x', summary: 'DRIFT' }),
finding('k-none', { title: 'x', summary: 'nothing' }),
];
const cav = [
caveat('shared', { dataset: 'drift_ds' }),
caveat('c-cav', { dataset: 'bars', caveat: 'drift noted' }),
];
for (const limit of [1, 2, 3, 5, 8, 20]) {
let baseline: ReadKnowledgeResultPayload | null = null;
for (let seed = 1; seed <= 12; seed += 1) {
const { port } = staticPort(
seededShuffle(lib, seed),
seededShuffle(fin, seed * 7),
seededShuffle(cav, seed * 13)
);
const res = await call(port, { query: 'drift', limit });
expect(res.isError).toBe(false);
if (baseline === null) {
baseline = res.payload;
} else {
expect(res.payload).toEqual(baseline);
}
}
const expectedOrder = [
'library:m-title',
'library:shared',
'findings:shared',
'provider_caveats:shared',
'library:Q-sum',
'library:a-tag',
'findings:b-sum',
'provider_caveats:c-cav',
].slice(0, limit);
expect(baseline?.rows.map(r => `${r.source}:${r.id}`)).toEqual(expectedOrder);
const counts = { library: 0, findings: 0, provider_caveats: 0 };
for (const r of baseline?.rows ?? []) {
counts[r.source] += 1;
}
expect(baseline?.sources).toEqual(counts);
expect(baseline?.rowCount).toBe(expectedOrder.length);
}
});
test('truncation flag reflects only text fields over the cap; title, tags and refs are never truncated', async () => {
const longTitle = 'T'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 10);
const { port } = staticPort(
[card('c1', { title: longTitle, tags: ['t'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 1)] })],
[finding('f1', { title: longTitle })],
[]
);
const res = await call(port, {});
for (const row of res.payload?.rows ?? []) {
expect(row.truncated).toBe(false);
if (row.source !== 'provider_caveats') {
expect(row.title).toHaveLength(longTitle.length);
}
}
});
});
describe('read_knowledge QA: limit cutting through a cross-source tie', () => {
test('limit inside a same-id tie keeps library > findings > provider_caveats and counts only returned rows', async () => {
const { port } = staticPort(
[card('dup', { title: 'Basis risk' })],
[finding('dup', { title: 'Basis risk' })],
[caveat('dup', { dataset: 'basis_ds' })]
);
const two = await call(port, { query: 'basis', limit: 2 });
expect(two.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([
'library:dup',
'findings:dup',
]);
expect(two.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 0 });
expect(two.payload?.rowCount).toBe(2);
});
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,354 @@
import { describe, expect, test } from 'bun:test';
import {
createMcpServer,
createSearchSymbolsTool,
SEARCH_SYMBOLS_MAX_QUERY_LENGTH,
type SearchSymbolsResultPayload,
type SymbolSearchPort,
type SymbolSearchQuery,
type SymbolSearchRow,
} from '../src/mcp/index';
// QA fixture: deterministic in-memory security-master port (no network, no
// Postgres, no MongoDB). Cutoffs are pinned epoch-ms values; no wall clock.
const MIDDAY_CUTOFF_TS = Date.UTC(2025, 2, 31, 15, 30, 0, 0); // 2025-03-31T15:30Z
const LAST_MS_CUTOFF_TS = Date.UTC(2025, 2, 31, 23, 59, 59, 999); // 2025-03-31T23:59:59.999Z
const CUTOFF_DATE = '2025-03-31';
function row(
overrides: Partial<SymbolSearchRow> & { readonly listingId: number }
): SymbolSearchRow {
return {
instrumentId: overrides.listingId * 10,
ticker: `T${overrides.listingId}`,
classSuffix: null,
name: `Company ${overrides.listingId}`,
mic: 'XNAS',
currency: 'USD',
isin: null,
firstBarDate: '2020-01-02',
lastBarDate: '2025-03-28',
delistedAt: null,
...overrides,
};
}
function fakePort(impl: (q: SymbolSearchQuery) => Promise<unknown> | unknown): {
readonly calls: SymbolSearchQuery[];
readonly port: SymbolSearchPort;
} {
const calls: SymbolSearchQuery[] = [];
return {
calls,
port: {
async searchSymbols(q) {
calls.push({ ...q });
return (await impl(q)) as readonly SymbolSearchRow[];
},
},
};
}
async function call(
port: SymbolSearchPort,
args: Record<string, unknown>,
vaultCutoffTs: number
): Promise<{ isError: boolean; text: string; payload: SearchSymbolsResultPayload | null }> {
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [createSearchSymbolsTool({ port, vaultContext: { vaultCutoffTs } })],
});
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 7,
method: 'tools/call',
params: { name: 'search_symbols', arguments: args },
})
);
const parsed = JSON.parse(raw as string) as {
result: { isError?: boolean; content: { text: string }[] };
};
const isError = parsed.result.isError === true;
const text = parsed.result.content[0]?.text ?? '';
return {
isError,
text,
payload: isError ? null : (JSON.parse(text) as SearchSymbolsResultPayload),
};
}
describe('MCP search_symbols QA', () => {
test('intraday cutoff fences against the cutoff UTC calendar date (equal kept, next day dropped/clamped/masked)', async () => {
const rows = [
row({
listingId: 1,
ticker: 'QQ',
firstBarDate: CUTOFF_DATE,
lastBarDate: '2025-04-01',
delistedAt: '2025-04-01',
}),
row({ listingId: 2, ticker: 'QQ', firstBarDate: '2025-04-01', lastBarDate: '2025-04-02' }),
row({ listingId: 3, ticker: 'QQ', lastBarDate: CUTOFF_DATE, delistedAt: CUTOFF_DATE }),
];
for (const cutoff of [MIDDAY_CUTOFF_TS, LAST_MS_CUTOFF_TS]) {
const { port } = fakePort(() => rows);
const res = await call(port, { query: 'QQ' }, cutoff);
expect(res.isError).toBe(false);
expect(res.payload?.vaultCutoffTs).toBe(cutoff);
expect(
res.payload?.rows.map(r => [r.listingId, r.firstBarDate, r.lastBarDate, r.delistedAt])
).toEqual([
[1, CUTOFF_DATE, CUTOFF_DATE, null],
[3, '2020-01-02', CUTOFF_DATE, CUTOFF_DATE],
]);
}
});
test('cutoff one ms before midnight UTC uses the previous calendar date', async () => {
const cutoff = Date.UTC(2025, 2, 31, 0, 0, 0, 0) - 1; // 2025-03-30T23:59:59.999Z
const { port } = fakePort(() => [
row({ listingId: 1, ticker: 'EDGE', firstBarDate: CUTOFF_DATE }),
row({ listingId: 2, ticker: 'EDGE', lastBarDate: CUTOFF_DATE, delistedAt: CUTOFF_DATE }),
]);
const res = await call(port, { query: 'EDGE' }, cutoff);
expect(res.payload?.rows).toHaveLength(1);
expect(res.payload?.rows[0]).toMatchObject({
listingId: 2,
lastBarDate: '2025-03-30',
delistedAt: null,
});
});
test('a future delisting changes neither membership nor ranking relative to a never-delisted listing', async () => {
const base = [
row({ listingId: 9, ticker: 'MSFT', name: 'Microsoft Corp' }),
row({ listingId: 4, ticker: 'MSFTX', name: 'Microsoft Tracker' }),
row({ listingId: 7, ticker: 'ZZZ', name: 'Old msft Holdings' }),
];
const withFutureDelisting = base.map(r =>
r.listingId === 4 ? { ...r, delistedAt: '2026-01-15', lastBarDate: '2026-01-14' } : r
);
for (const includeDelisted of [true, false]) {
const a = await call(
fakePort(() => base).port,
{ query: 'msft', includeDelisted },
MIDDAY_CUTOFF_TS
);
const b = await call(
fakePort(() => withFutureDelisting).port,
{ query: 'msft', includeDelisted },
MIDDAY_CUTOFF_TS
);
expect(a.payload?.rows.map(r => r.listingId)).toEqual([9, 4, 7]);
expect(b.payload?.rows.map(r => r.listingId)).toEqual([9, 4, 7]);
expect(b.payload?.rows[1]).toMatchObject({ delistedAt: null, lastBarDate: CUTOFF_DATE });
}
});
test('truncation with includeDelisted: true ignores post-cutoff rows placed ahead of eligible matches', async () => {
const rows = [
row({ listingId: 1, ticker: 'NEW', firstBarDate: '2025-06-01' }),
row({ listingId: 2, ticker: 'NEW', firstBarDate: '2025-04-01' }),
row({ listingId: 3, ticker: 'NEWA' }),
row({ listingId: 4, ticker: 'NEWB', delistedAt: '2021-05-05', lastBarDate: '2021-05-04' }),
];
const fit = await call(fakePort(() => rows).port, { query: 'new', limit: 2 }, MIDDAY_CUTOFF_TS);
expect(fit.payload).toMatchObject({ rowCount: 2, truncated: false });
expect(fit.payload?.rows.map(r => r.listingId)).toEqual([3, 4]);
const over = await call(
fakePort(() => rows).port,
{ query: 'new', limit: 1 },
MIDDAY_CUTOFF_TS
);
expect(over.payload).toMatchObject({ rowCount: 1, truncated: true });
expect(over.payload?.rows.map(r => r.listingId)).toEqual([3]);
});
test('a row matching both ticker prefix and name ranks by its best (ticker) match; name match is literal substring', async () => {
const rows = [
row({ listingId: 1, ticker: 'ZED', name: 'A.B Industries' }),
row({ listingId: 2, ticker: 'A.BX', name: 'A.B Prefix Co' }),
row({ listingId: 3, ticker: 'AXB', name: 'Regex Bait AXB' }),
row({ listingId: 4, ticker: 'A.B', name: 'Exact Dot' }),
];
const res = await call(fakePort(() => rows).port, { query: 'a.b' }, MIDDAY_CUTOFF_TS);
// "a.b" must not behave like a regex: AXB (3) is not a match.
expect(res.payload?.rows.map(r => r.listingId)).toEqual([4, 2, 1]);
});
test('repeated calls on shuffled inputs give byte-identical payloads', async () => {
const rows = Array.from({ length: 30 }, (_, i) =>
row({ listingId: 1000 - i * 7, ticker: i % 3 === 0 ? 'RY' : `RY${i}`, name: `Royal ${i}` })
);
// Deterministic Fisher-Yates with a fixed LCG seed.
let seed = 12345;
const shuffled = [...rows];
for (let i = shuffled.length - 1; i > 0; i -= 1) {
seed = (seed * 1103515245 + 12345) % 2147483648;
const j = seed % (i + 1);
[shuffled[i], shuffled[j]] = [shuffled[j] as SymbolSearchRow, shuffled[i] as SymbolSearchRow];
}
const a = await call(fakePort(() => rows).port, { query: 'RY', limit: 12 }, MIDDAY_CUTOFF_TS);
const b = await call(
fakePort(() => shuffled).port,
{ query: 'RY', limit: 12 },
MIDDAY_CUTOFF_TS
);
expect(a.text).toBe(b.text);
const ids = a.payload?.rows.map(r => r.listingId) ?? [];
const exact = ids.slice(0, 10);
expect([...exact].sort((x, y) => x - y)).toEqual(exact); // 10 exact RY matches ascending
expect(a.payload?.truncated).toBe(true);
});
test('query of exactly 64 chars (and 64 chars after trimming) is accepted; whitespace is trimmed before the length check', async () => {
const q = 'B'.repeat(SEARCH_SYMBOLS_MAX_QUERY_LENGTH);
const fake = fakePort(() => []);
const exact = await call(fake.port, { query: q }, MIDDAY_CUTOFF_TS);
const padded = await call(fake.port, { query: ` ${q} ` }, MIDDAY_CUTOFF_TS);
expect(exact.isError).toBe(false);
expect(padded.isError).toBe(false);
expect(fake.calls.map(c => c.query)).toEqual([q, q]);
});
test('limit 1 and 100 accepted and forwarded as hints; non-number limit, null and non-boolean includeDelisted rejected without port call', async () => {
const fake = fakePort(() => []);
expect((await call(fake.port, { query: 'X', limit: 1 }, MIDDAY_CUTOFF_TS)).isError).toBe(false);
expect(
(await call(fake.port, { query: 'X', limit: 100, country: 'US' }, MIDDAY_CUTOFF_TS)).isError
).toBe(false);
expect(fake.calls).toEqual([
{ query: 'X', limit: 1, includeDelisted: true, vaultCutoffTs: MIDDAY_CUTOFF_TS },
{
query: 'X',
limit: 100,
country: 'US',
includeDelisted: true,
vaultCutoffTs: MIDDAY_CUTOFF_TS,
},
]);
const bad = fakePort(() => []);
for (const args of [
{ query: 'X', limit: '20' },
{ query: 'X', limit: null },
{ query: 'X', limit: Number.NaN },
{ query: 42 },
{ query: 'X', country: null },
{ query: 'X', includeDelisted: 0 },
{ query: 'X', vaultCutoffTs: Date.UTC(2030, 0, 1) },
]) {
const res = await call(bad.port, args, MIDDAY_CUTOFF_TS);
expect(res.isError).toBe(true);
}
expect(bad.calls).toHaveLength(0);
});
test('malformed port responses yield a sanitized isError result', async () => {
const malformed: unknown[] = [
null,
{ rows: [] },
'not-an-array',
[null],
['row'],
[{ ...row({ listingId: 1, ticker: 'M' }), listingId: '1' }],
[{ ...row({ listingId: 1, ticker: 'M' }), listingId: 1.5 }],
[{ ...row({ listingId: 1, ticker: 'M' }), instrumentId: undefined }],
[{ ...row({ listingId: 1, ticker: 'M' }), ticker: null }],
[{ ...row({ listingId: 1, ticker: 'M' }), name: undefined }],
[{ ...row({ listingId: 1, ticker: 'M' }), mic: 5 }],
[{ ...row({ listingId: 1, ticker: 'M' }), isin: 123 }],
[{ ...row({ listingId: 1, ticker: 'M' }), classSuffix: undefined }],
[{ ...row({ listingId: 1, ticker: 'M' }), firstBarDate: undefined }],
];
for (const response of malformed) {
const res = await call(fakePort(() => response).port, { query: 'M' }, MIDDAY_CUTOFF_TS);
expect(res.isError).toBe(true);
expect(res.text).toBe('Error: Tool execution failed.');
}
});
test('non-Error port rejections are sanitized', async () => {
for (const thrown of ['password=hunter2', { secret: 'x' }, 42]) {
const res = await call(
fakePort(() => {
throw thrown;
}).port,
{ query: 'AAPL' },
MIDDAY_CUTOFF_TS
);
expect(res.isError).toBe(true);
expect(res.text).toBe('Error: Tool execution failed.');
expect(res.text).not.toContain('hunter2');
}
});
test('returned rows are fresh projections: mutating port objects after the call does not alter output, and port input is not mutated', async () => {
const source = row({ listingId: 5, ticker: 'FRZ', lastBarDate: '2025-05-05' });
const snapshot = JSON.stringify(source);
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createSearchSymbolsTool({
port: { searchSymbols: async () => [source] },
vaultContext: { vaultCutoffTs: MIDDAY_CUTOFF_TS },
}),
],
});
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name: 'search_symbols', arguments: { query: 'FRZ' } },
})
);
expect(JSON.stringify(source)).toBe(snapshot); // clamping did not write back to the port row
const payload = JSON.parse(
(JSON.parse(raw as string) as { result: { content: { text: string }[] } }).result.content[0]
?.text ?? ''
) as SearchSymbolsResultPayload;
expect(payload.rows[0]?.lastBarDate).toBe(CUTOFF_DATE);
});
test('concurrent calls are independent and each respects its own arguments', async () => {
const rows = [
row({ listingId: 1, ticker: 'TD', mic: 'XTSE', currency: 'CAD' }),
row({ listingId: 2, ticker: 'TD', mic: 'XNYS' }),
row({ listingId: 3, ticker: 'TDX', delistedAt: '2022-02-02', lastBarDate: '2022-02-01' }),
];
const fake = fakePort(q =>
q.country === undefined ? rows : rows.filter(r => (q.country === 'CA') === (r.mic === 'XTSE'))
);
const [all, ca, active] = await Promise.all([
call(fake.port, { query: 'TD' }, MIDDAY_CUTOFF_TS),
call(fake.port, { query: 'TD', country: 'CA' }, MIDDAY_CUTOFF_TS),
call(fake.port, { query: 'TD', includeDelisted: false, limit: 1 }, MIDDAY_CUTOFF_TS),
]);
expect(all.payload?.rows.map(r => r.listingId)).toEqual([1, 2, 3]);
expect(ca.payload?.rows.map(r => r.listingId)).toEqual([1]);
expect(active.payload).toMatchObject({ rowCount: 1, truncated: true });
expect(active.payload?.rows.map(r => r.listingId)).toEqual([1]);
});
test('pre-1970 cutoff fences correctly', async () => {
const cutoff = Date.UTC(1965, 5, 30, 12, 0, 0, 0);
const rows = [
row({
listingId: 1,
ticker: 'IBM',
firstBarDate: '1962-01-02',
lastBarDate: '2025-03-28',
delistedAt: null,
}),
row({ listingId: 2, ticker: 'IBM', firstBarDate: '1970-01-02' }),
];
const res = await call(fakePort(() => rows).port, { query: 'IBM' }, cutoff);
expect(res.payload?.rows).toHaveLength(1);
expect(res.payload?.rows[0]).toMatchObject({ listingId: 1, lastBarDate: '1965-06-30' });
});
});

View file

@ -0,0 +1,711 @@
import { describe, expect, test } from 'bun:test';
import {
type MarketDataStore,
MarketDataStoreValidationError,
} from '../src/market-data-store';
import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb';
import {
SEARCH_SYMBOLS_DEFAULT_LIMIT,
SEARCH_SYMBOLS_MAX_LIMIT,
SEARCH_SYMBOLS_MAX_QUERY_LENGTH,
type SearchSymbolsResultPayload,
type SymbolSearchPort,
type SymbolSearchQuery,
type SymbolSearchRow,
createAnalyzeSignalTool,
createEventStudyTool,
createMcpServer,
createQueryDataTool,
createSearchSymbolsTool,
} from '../src/mcp/index';
import type { TrialLedgerExecutor } from '../src/trial-ledger';
const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); // 2025-03-31T00:00:00.000Z
const VAULT_CUTOFF_DATE = '2025-03-31';
interface FixtureRow extends SymbolSearchRow {
readonly country?: 'US' | 'CA';
}
function makeRow(overrides: Partial<FixtureRow> & { readonly listingId: number }): SymbolSearchRow {
return {
listingId: overrides.listingId,
instrumentId: overrides.instrumentId ?? overrides.listingId * 10,
ticker: overrides.ticker ?? `T${overrides.listingId}`,
classSuffix: overrides.classSuffix ?? null,
name: overrides.name ?? `Company ${overrides.listingId}`,
mic: overrides.mic ?? 'XNAS',
currency: overrides.currency ?? 'USD',
isin: overrides.isin ?? null,
firstBarDate: overrides.firstBarDate === undefined ? '2020-01-02' : overrides.firstBarDate,
lastBarDate: overrides.lastBarDate === undefined ? '2025-03-28' : overrides.lastBarDate,
delistedAt: overrides.delistedAt === undefined ? null : overrides.delistedAt,
};
}
interface FakePortState {
readonly calls: SymbolSearchQuery[];
readonly port: SymbolSearchPort;
}
function createFakePort(options?: {
readonly rows?: readonly FixtureRow[];
readonly filterByCountry?: boolean;
readonly error?: unknown;
readonly rawReturn?: unknown;
}): FakePortState {
const calls: SymbolSearchQuery[] = [];
const rows = options?.rows ?? [];
const port: SymbolSearchPort = {
async searchSymbols(q: SymbolSearchQuery): Promise<readonly SymbolSearchRow[]> {
calls.push({ ...q });
if (options?.error !== undefined) {
throw options.error;
}
if (options?.rawReturn !== undefined) {
return options.rawReturn as readonly SymbolSearchRow[];
}
if (options?.filterByCountry && q.country !== undefined) {
return rows.filter(row => row.country === q.country);
}
return [...rows];
},
};
return { calls, port };
}
function createMinimalStore(): MarketDataStore {
return {
bars() {
return {
async *[Symbol.asyncIterator]() {
// empty stream
},
};
},
async universe() {
return [];
},
crossSection() {
throw new MarketDataStoreNotImplementedError('crossSection');
},
fundamentalsAsOf() {
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
},
events() {
throw new MarketDataStoreNotImplementedError('events');
},
shortsAsOf() {
throw new MarketDataStoreNotImplementedError('shortsAsOf');
},
macroAsOf() {
throw new MarketDataStoreNotImplementedError('macroAsOf');
},
fx() {
throw new MarketDataStoreNotImplementedError('fx');
},
};
}
function createMinimalLedger(): TrialLedgerExecutor {
return {
async query() {
return { rows: [] };
},
};
}
async function callSearchSymbols(
fake: FakePortState,
args: Record<string, unknown>,
vaultCutoffTs = VAULT_CUTOFF_TS
): Promise<{
readonly isError: boolean;
readonly text: string;
readonly payload: SearchSymbolsResultPayload | null;
}> {
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createSearchSymbolsTool({
port: fake.port,
vaultContext: { vaultCutoffTs },
}),
],
});
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 'ss-1',
method: 'tools/call',
params: {
name: 'search_symbols',
arguments: args,
},
})
);
expect(raw).not.toBeNull();
const parsed = JSON.parse(raw as string) as {
result: {
isError?: boolean;
content: { type: string; text: string }[];
};
};
const isError = parsed.result.isError === true;
const text = parsed.result.content[0]?.text ?? '';
return {
isError,
text,
payload: isError ? null : (JSON.parse(text) as SearchSymbolsResultPayload),
};
}
describe('MCP search_symbols tool', () => {
test('registers alongside query_data, analyze_signal, and event_study and exposes strict schema via tools/list', async () => {
const store = createMinimalStore();
const ledger = createMinimalLedger();
const fake = createFakePort({
rows: [
makeRow({
listingId: 42,
instrumentId: 420,
ticker: 'AAPL',
classSuffix: null,
name: 'Apple Inc.',
mic: 'XNAS',
currency: 'USD',
isin: 'US0378331005',
firstBarDate: '1980-12-12',
lastBarDate: '2025-03-28',
delistedAt: null,
}),
],
});
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createQueryDataTool({
store,
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
}),
createAnalyzeSignalTool({
store,
ledger,
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
principalId: 'operator',
}),
createEventStudyTool({
store,
ledger,
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
principalId: 'operator',
resolveExchangeCalendars: () => ({}),
}),
createSearchSymbolsTool({
port: fake.port,
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
}),
],
});
const listRaw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/list',
})
);
expect(listRaw).not.toBeNull();
const listParsed = JSON.parse(listRaw as string) as {
result: {
tools: {
name: string;
description: string;
inputSchema: {
type: string;
properties: Record<string, Record<string, unknown>>;
required?: string[];
additionalProperties: boolean;
};
}[];
};
};
expect(listParsed.result.tools.map(t => t.name)).toEqual([
'query_data',
'analyze_signal',
'event_study',
'search_symbols',
]);
const searchTool = listParsed.result.tools.find(t => t.name === 'search_symbols');
expect(searchTool).toBeDefined();
expect(searchTool?.inputSchema.type).toBe('object');
expect(searchTool?.inputSchema.additionalProperties).toBe(false);
expect(searchTool?.inputSchema.required).toEqual(['query']);
expect(searchTool?.inputSchema.properties.query).toMatchObject({
type: 'string',
minLength: 1,
maxLength: SEARCH_SYMBOLS_MAX_QUERY_LENGTH,
});
expect(searchTool?.inputSchema.properties.limit).toMatchObject({
type: 'integer',
minimum: 1,
maximum: SEARCH_SYMBOLS_MAX_LIMIT,
default: SEARCH_SYMBOLS_DEFAULT_LIMIT,
});
expect(searchTool?.inputSchema.properties.country).toMatchObject({
type: 'string',
enum: ['US', 'CA'],
});
expect(searchTool?.inputSchema.properties.includeDelisted).toMatchObject({
type: 'boolean',
default: true,
});
expect(searchTool?.inputSchema.properties.scope).toBeUndefined();
expect(searchTool?.inputSchema.properties.vault_evaluation_only).toBeUndefined();
expect(searchTool?.inputSchema.properties.vaultCutoffTs).toBeUndefined();
// Exercise JSON-RPC tools/call end-to-end on the multi-tool server.
const callRaw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
params: {
name: 'search_symbols',
arguments: { query: 'AAPL' },
},
})
);
expect(callRaw).not.toBeNull();
const callParsed = JSON.parse(callRaw as string) as {
result: { isError?: boolean; content: { type: string; text: string }[] };
};
expect(callParsed.result.isError).toBeUndefined();
const payload = JSON.parse(callParsed.result.content[0]?.text ?? '') as SearchSymbolsResultPayload;
expect(payload).toEqual({
scope: 'vault_fenced',
vaultCutoffTs: VAULT_CUTOFF_TS,
rowCount: 1,
truncated: false,
rows: [
{
listingId: 42,
instrumentId: 420,
ticker: 'AAPL',
classSuffix: null,
name: 'Apple Inc.',
mic: 'XNAS',
currency: 'USD',
isin: 'US0378331005',
firstBarDate: '1980-12-12',
lastBarDate: '2025-03-28',
delistedAt: null,
},
],
});
});
test('ranks exact ticker > ticker prefix > company name case-insensitively with numeric listingId tie-break', async () => {
const fixture: SymbolSearchRow[] = [
makeRow({ listingId: 100, ticker: 'XYZ', name: 'Apple Blossom Holdings' }),
makeRow({ listingId: 10, ticker: 'AAPL', name: 'Apple Inc. Secondary' }),
makeRow({ listingId: 25, ticker: 'AAPLE', name: 'Apple Energy Corp' }),
makeRow({ listingId: 2, ticker: 'aapl', name: 'Apple Inc.' }),
makeRow({ listingId: 5, ticker: 'AAPLX', name: 'Apple Extended ETF' }),
makeRow({ listingId: 15, ticker: 'ZZZ', name: 'aapl Partners LP' }),
makeRow({ listingId: 30, ticker: 'OTHER', name: 'Unrelated Name' }),
];
const fakeA = createFakePort({ rows: fixture });
const fakeB = createFakePort({ rows: [...fixture].reverse() });
const resA = await callSearchSymbols(fakeA, { query: ' AaPl ' });
const resB = await callSearchSymbols(fakeB, { query: ' AaPl ' });
expect(resA.isError).toBe(false);
expect(resB.isError).toBe(false);
expect(resA.payload).toEqual(resB.payload);
// Exact ticker (2, 10) -> prefix (5, 25) -> name substring (15); unrelated candidates (30, 100) are excluded
expect(resA.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15]);
expect(resA.payload?.rowCount).toBe(5);
expect(resA.payload?.truncated).toBe(false);
// Unrelated candidates must not trigger truncation when all actual matches fit within limit.
const exactFitRes = await callSearchSymbols(createFakePort({ rows: fixture }), {
query: 'AAPL',
limit: 5,
});
expect(exactFitRes.isError).toBe(false);
expect(exactFitRes.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15]);
expect(exactFitRes.payload?.rowCount).toBe(5);
expect(exactFitRes.payload?.truncated).toBe(false);
// When none of the port's returned candidates match, return an empty, non-truncated payload.
const noMatchRes = await callSearchSymbols(createFakePort({ rows: fixture }), {
query: 'UNMATCHED',
limit: 2,
});
expect(noMatchRes.isError).toBe(false);
expect(noMatchRes.payload).toEqual({
scope: 'vault_fenced',
vaultCutoffTs: VAULT_CUTOFF_TS,
rowCount: 0,
truncated: false,
rows: [],
});
// Verify trimmed query, default limit, includeDelisted: true, and vaultCutoffTs were passed to port.
expect(fakeA.calls).toHaveLength(1);
expect(fakeA.calls[0]).toEqual({
query: 'AaPl',
limit: SEARCH_SYMBOLS_DEFAULT_LIMIT,
includeDelisted: true,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
});
test('forwards country filter and returns empty payload when no listings match', async () => {
const fake = createFakePort({
filterByCountry: true,
rows: [
{ ...makeRow({ listingId: 1, ticker: 'SHOP', mic: 'XNYS', currency: 'USD' }), country: 'US' },
{ ...makeRow({ listingId: 2, ticker: 'SHOP', mic: 'XTSE', currency: 'CAD' }), country: 'CA' },
],
});
const caRes = await callSearchSymbols(fake, { query: 'SHOP', country: 'CA' });
expect(caRes.isError).toBe(false);
expect(caRes.payload?.rows.map(r => r.listingId)).toEqual([2]);
expect(fake.calls[0]?.country).toBe('CA');
const emptyFake = createFakePort({ rows: [] });
const emptyRes = await callSearchSymbols(emptyFake, { query: 'NO_SUCH_SYMBOL', country: 'US' });
expect(emptyRes.isError).toBe(false);
expect(emptyRes.payload).toEqual({
scope: 'vault_fenced',
vaultCutoffTs: VAULT_CUTOFF_TS,
rowCount: 0,
truncated: false,
rows: [],
});
expect(emptyFake.calls[0]?.country).toBe('US');
});
test('enforces default limit 20, hard max 100, exact-fit, and over-returning port truncation', async () => {
// 25 eligible rows with default limit (20) -> truncated: true
const rows25: SymbolSearchRow[] = [];
for (let i = 1; i <= 25; i += 1) {
rows25.push(makeRow({ listingId: i, ticker: `SYM${i}`, name: `Symbol ${i}` }));
}
const defaultOver = await callSearchSymbols(createFakePort({ rows: rows25 }), { query: 'SYM' });
expect(defaultOver.isError).toBe(false);
expect(defaultOver.payload?.rowCount).toBe(20);
expect(defaultOver.payload?.rows).toHaveLength(20);
expect(defaultOver.payload?.truncated).toBe(true);
// Exact fit of 20 eligible rows -> truncated: false
const defaultExact = await callSearchSymbols(createFakePort({ rows: rows25.slice(0, 20) }), {
query: 'SYM',
});
expect(defaultExact.isError).toBe(false);
expect(defaultExact.payload?.rowCount).toBe(20);
expect(defaultExact.payload?.truncated).toBe(false);
// Hard max 100 accepted; port over-returns 115 rows with late exact match at end
const rows115: SymbolSearchRow[] = [];
for (let i = 1; i <= 114; i += 1) {
rows115.push(makeRow({ listingId: i + 10, ticker: `ABC${i}`, name: `ABC Corp ${i}` }));
}
rows115.push(makeRow({ listingId: 999, ticker: 'ABC', name: 'Exact Match Late In Array' }));
const maxOver = await callSearchSymbols(createFakePort({ rows: rows115 }), {
query: 'ABC',
limit: 100,
});
expect(maxOver.isError).toBe(false);
expect(maxOver.payload?.rowCount).toBe(100);
expect(maxOver.payload?.rows).toHaveLength(100);
expect(maxOver.payload?.truncated).toBe(true);
// Late exact ticker match must still rank #1 before slicing
expect(maxOver.payload?.rows[0]?.listingId).toBe(999);
// Exact fit at max 100 -> truncated: false
const maxExact = await callSearchSymbols(createFakePort({ rows: rows115.slice(0, 100) }), {
query: 'ABC',
limit: 100,
});
expect(maxExact.isError).toBe(false);
expect(maxExact.payload?.rowCount).toBe(100);
expect(maxExact.payload?.truncated).toBe(false);
});
test('rows removed by Vault fencing or includeDelisted: false do not count toward truncation', async () => {
const rows: SymbolSearchRow[] = [
// Post-cutoff listings placed ahead of eligible matches
makeRow({ listingId: 1, ticker: 'ACME', firstBarDate: '2025-04-01' }),
makeRow({ listingId: 2, ticker: 'ACME2', firstBarDate: '2025-05-15' }),
// Historically delisted listings
makeRow({ listingId: 3, ticker: 'ACME3', delistedAt: '2024-06-30', lastBarDate: '2024-06-28' }),
makeRow({ listingId: 4, ticker: 'ACME4', delistedAt: '2025-03-31', lastBarDate: '2025-03-31' }),
// Active as of cutoff (one active forever, one delisted after cutoff)
makeRow({ listingId: 5, ticker: 'ACME5', delistedAt: null }),
makeRow({ listingId: 6, ticker: 'ACME6', delistedAt: '2025-04-15', lastBarDate: '2025-04-14' }),
];
const res = await callSearchSymbols(createFakePort({ rows }), {
query: 'ACME',
limit: 2,
includeDelisted: false,
});
expect(res.isError).toBe(false);
expect(res.payload?.rows.map(r => r.listingId)).toEqual([5, 6]);
expect(res.payload?.rowCount).toBe(2);
expect(res.payload?.truncated).toBe(false);
});
test('enforces Vault fencing on firstBarDate, lastBarDate, delistedAt, UTC cutoff equality, and null dates', async () => {
const extraFieldRow = {
...makeRow({
listingId: 10,
ticker: 'VLT',
classSuffix: 'A',
isin: 'US0000000010',
firstBarDate: '2024-02-29', // valid leap-year date
lastBarDate: '2025-06-01', // after cutoff -> clamp to 2025-03-31
delistedAt: '2025-05-01', // after cutoff -> mask to null
}),
internalSecretField: 'must-not-leak',
} as unknown as SymbolSearchRow;
const rows: SymbolSearchRow[] = [
extraFieldRow,
// firstBarDate strictly after cutoff -> dropped
makeRow({
listingId: 11,
ticker: 'VLT',
firstBarDate: '2025-04-01',
lastBarDate: '2025-06-01',
delistedAt: null,
}),
// firstBarDate / lastBarDate / delistedAt equal to cutoff -> kept as-is
makeRow({
listingId: 12,
ticker: 'VLT',
firstBarDate: VAULT_CUTOFF_DATE,
lastBarDate: VAULT_CUTOFF_DATE,
delistedAt: VAULT_CUTOFF_DATE,
}),
// Null dates preserved
makeRow({
listingId: 13,
ticker: 'VLT',
firstBarDate: null,
lastBarDate: null,
delistedAt: null,
}),
// Historical delisting before cutoff -> preserved by default
makeRow({
listingId: 14,
ticker: 'VLT',
firstBarDate: '2019-01-03',
lastBarDate: '2023-10-12',
delistedAt: '2023-10-15',
}),
];
const fakeDefault = createFakePort({ rows });
const resDefault = await callSearchSymbols(fakeDefault, { query: 'VLT' });
expect(resDefault.isError).toBe(false);
expect(resDefault.payload?.rows).toEqual([
{
listingId: 10,
instrumentId: 100,
ticker: 'VLT',
classSuffix: 'A',
name: 'Company 10',
mic: 'XNAS',
currency: 'USD',
isin: 'US0000000010',
firstBarDate: '2024-02-29',
lastBarDate: VAULT_CUTOFF_DATE,
delistedAt: null,
},
{
listingId: 12,
instrumentId: 120,
ticker: 'VLT',
classSuffix: null,
name: 'Company 12',
mic: 'XNAS',
currency: 'USD',
isin: null,
firstBarDate: VAULT_CUTOFF_DATE,
lastBarDate: VAULT_CUTOFF_DATE,
delistedAt: VAULT_CUTOFF_DATE,
},
{
listingId: 13,
instrumentId: 130,
ticker: 'VLT',
classSuffix: null,
name: 'Company 13',
mic: 'XNAS',
currency: 'USD',
isin: null,
firstBarDate: null,
lastBarDate: null,
delistedAt: null,
},
{
listingId: 14,
instrumentId: 140,
ticker: 'VLT',
classSuffix: null,
name: 'Company 14',
mic: 'XNAS',
currency: 'USD',
isin: null,
firstBarDate: '2019-01-03',
lastBarDate: '2023-10-12',
delistedAt: '2023-10-15',
},
]);
// Extra port property must not be projected
expect('internalSecretField' in (resDefault.payload?.rows[0] ?? {})).toBe(false);
// With includeDelisted: false, historical delistings (12, 14) are excluded,
// while future delisting (10) remains eligible with delistedAt: null.
const fakeNoDelisted = createFakePort({ rows });
const resNoDelisted = await callSearchSymbols(fakeNoDelisted, {
query: 'VLT',
includeDelisted: false,
});
expect(resNoDelisted.isError).toBe(false);
expect(resNoDelisted.payload?.rows.map(r => r.listingId)).toEqual([10, 13]);
expect(resNoDelisted.payload?.rows[0]?.delistedAt).toBeNull();
// Port must still be called with includeDelisted: true
expect(fakeNoDelisted.calls[0]?.includeDelisted).toBe(true);
});
test('rejects invalid port date strings with sanitized isError result', async () => {
const invalidDateCases: Partial<SymbolSearchRow>[] = [
{ firstBarDate: '2025-02-29' }, // non-leap year Feb 29
{ lastBarDate: '2025-04-31' }, // April has 30 days
{ delistedAt: '2025-13-01' }, // invalid month
{ firstBarDate: '2025-03-31T00:00:00Z' }, // timestamp instead of YYYY-MM-DD
{ lastBarDate: 'not-a-date' },
{ delistedAt: '' },
];
for (const badFields of invalidDateCases) {
const fake = createFakePort({
rows: [makeRow({ listingId: 1, ticker: 'BAD', ...badFields })],
});
const res = await callSearchSymbols(fake, { query: 'BAD' });
expect(res.isError).toBe(true);
expect(res.text).toBe('Error: Tool execution failed.');
}
});
test('factory throws MarketDataStoreValidationError on missing or invalid port or vaultCutoffTs', () => {
const validPort = createFakePort().port;
expect(() =>
createSearchSymbolsTool(null as unknown as Parameters<typeof createSearchSymbolsTool>[0])
).toThrow(MarketDataStoreValidationError);
expect(() =>
createSearchSymbolsTool({
port: null as unknown as SymbolSearchPort,
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
})
).toThrow(MarketDataStoreValidationError);
expect(() =>
createSearchSymbolsTool({
port: {} as unknown as SymbolSearchPort,
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
})
).toThrow(MarketDataStoreValidationError);
const invalidCutoffs: unknown[] = [
undefined,
null,
'2025-03-31',
Number.NaN,
Number.POSITIVE_INFINITY,
Number.NEGATIVE_INFINITY,
123.45,
8_640_000_000_000_000,
];
for (const badCutoff of invalidCutoffs) {
expect(() =>
createSearchSymbolsTool({
port: validPort,
vaultContext: { vaultCutoffTs: badCutoff as number },
})
).toThrow(MarketDataStoreValidationError);
}
expect(() =>
createSearchSymbolsTool({
port: validPort,
vaultContext: undefined as unknown as { vaultCutoffTs: number },
})
).toThrow(MarketDataStoreValidationError);
});
test('returns structured isError without calling port on invalid arguments', async () => {
const invalidInputs: Record<string, unknown>[] = [
{},
{ query: '' },
{ query: ' \t\n ' },
{ query: 'A'.repeat(SEARCH_SYMBOLS_MAX_QUERY_LENGTH + 1) },
{ query: 'AAPL', limit: 0 },
{ query: 'AAPL', limit: -5 },
{ query: 'AAPL', limit: SEARCH_SYMBOLS_MAX_LIMIT + 1 },
{ query: 'AAPL', limit: 1.5 },
{ query: 'AAPL', country: 'UK' },
{ query: 'AAPL', country: 'us' },
{ query: 'AAPL', includeDelisted: 'true' },
{ query: 'AAPL', scope: 'vault_evaluation_only' },
{ query: 'AAPL', unknownField: 123 },
];
for (const args of invalidInputs) {
const fake = createFakePort({ rows: [makeRow({ listingId: 1, ticker: 'AAPL' })] });
const res = await callSearchSymbols(fake, args);
expect(res.isError).toBe(true);
expect(res.text).toContain('Invalid arguments for tool "search_symbols"');
expect(fake.calls).toHaveLength(0);
}
});
test('returns sanitized isError without leaking error message when port rejects', async () => {
const fake = createFakePort({
error: new Error('postgres://admin:super-secret@10.0.0.51:5432/trading_bot failed'),
});
const res = await callSearchSymbols(fake, { query: 'AAPL' });
expect(res.isError).toBe(true);
expect(res.text).toBe('Error: Tool execution failed.');
expect(res.text).not.toContain('super-secret');
expect(res.text).not.toContain('10.0.0.51');
expect(res.text).not.toContain('trading_bot');
expect(fake.calls).toHaveLength(1);
});
});

View file

@ -131,6 +131,19 @@ Rules:
Deferred out of `src/shorts.rs`: MongoDB `ceoShorts` BSON streaming, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, `rayon` sharding, and deriving `pct_float` from shares outstanding (values are passed through as supplied by the caller).
## `posts` Builder (`M2.2b`)
`build_posts` (`src/posts.rs`) turns already-decoded `ceoPosts` rows (`CeoPost<K>`) into two disjoint, deterministically sorted point-in-time `PostRow<K>` streams (`newswire` and `retail`) aligned with `design/DATA-CONTRACTS.md` §1 (`ceoSymbols`, `ceoPosts`, `ceoShorts` row).
Rules:
1. **Newswire vs. retail split:** `is_bot` is `true` iff `bot` is `"1"` after trimming whitespace; only `is_bot == true` rows route to `newswire`, and all other values (`None`, `"0"`, `""`, etc.) route to `retail`.
2. **Point-in-time `known_at` guard:** `posted_at = timestamp_ms * 1_000` (UTC microseconds) and `known_at = max(timestamp_ms, edited_ms) * 1_000` (`COALESCE(edited, timestamp)` clamped so `known_at >= posted_at` always holds). Any text-based feature MUST join on `known_at`, never `posted_at`. Rows with `edited_ms < timestamp_ms` clamp `known_at` to `posted_at` and increment `stats.edited_before_posted`. Both `stats.edited` and `stats.edited_before_posted` are counted on valid input rows before deduplication. Because `ceoPosts` overwrites `spiel` in place without version history, the builder retains one supplied version per `spiel_id` and cannot recover earlier pre-edit text.
3. **Validation & overflow:** Empty `spiel_id` or `timestamp_ms <= 0` rows are rejected before conversion and counted in `stats.rejected_invalid`. Overflow converting `timestamp_ms` or the selected `known_at` millisecond value to UTC microseconds returns `PostsError::TimestampOverflow`.
4. **Global `spiel_id` deduplication & deterministic tie-break:** Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail`. Within each `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties by the maximum lexicographic tuple `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero dependence on input order. The remaining `group_len - 1` rows are counted in `stats.duplicates_dropped`.
5. **Sort order & invariants:** Both `newswire` and `retail` are sorted strictly ascending by `(key, known_at, spiel_id)`. Any input permutation yields identical `newswire`, `retail`, and `stats`, and `input == newswire + retail + duplicates_dropped + rejected_invalid`.
Deferred out of `src/posts.rs`: `ceoPosts` raw-BSON decoding (pending live `edited` BSON type verification), `provider_mapping` resolution, Parquet writing, CLI subcommand, and benchmarks.
## `events` Builder (`M1.2g`)
`build_events` (`src/events.rs`) turns raw `qmFilings` (`QmFiling<K>`) and `qmEarnings` (`QmEarning<K>`) streams into deterministically sorted point-in-time `EventRow<K>` records matching `events/year=YYYY/part.parquet` in `design/DATA-CONTRACTS.md` (`listing_id, ts, known_at, known_at_source, kind, subtype, payload_json`), plus `partition_year_utc` / `EventRow::partition_year` for UTC `year=YYYY` partitioning.
@ -1553,6 +1566,14 @@ Measured locally (`2026-11-30`, two back-to-back offline runs on the final code
- **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress.
- **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks).
## Zero-Copy `eodIntraday1M` BSON Decoder (`M2.3d`)
`src/bson_eod_intraday.rs` decodes raw `eodIntraday1M` MongoDB BSON documents in a single zero-copy forward pass (`RawEodIntradayBar<'a>`, `decode_eod_intraday_doc`, `decode_eod_intraday_bytes`, `decode_eod_intraday_buffer`, `BsonEodIntradayError`, `BsonEodIntradayDecodeStats`) with bounded-memory streaming helpers in `src/bson_stream.rs` (`decode_eod_intraday_chunks`, `decode_eod_intraday_stream`):
- **Timestamp units:** `timestamp` is bar-start **UTC Unix seconds** (accepted in BSON `Int32`, `Int64`, or finite integral `Double` within `0..=i64::MAX / 1_000_000`) converted to UTC microseconds (`ts: i64`) via checked multiplication by `1_000_000`. It is bar start only (not a publication / `known_at` timestamp).
- **Split-adjusted passthrough:** `open`, `high`, `low`, `close` (finite and `> 0.0`) and `volume` (finite and `>= 0.0`, `-0.0` normalized to `+0.0`) are passed through untouched as the provider's retroactively split-adjusted values; downstream `bars_1m::build_bars_1m` performs split un-adjustment via `SplitTable`.
- **Conversion & zero-copy:** `eodSearchCode` is borrowed verbatim from the input `&RawDocument` slice; `into_eod_intraday_bar` / `try_into_eod_intraday_bar` map `(&'a str, i64)` directly into `bars_1m::EodIntradayBar<K>`.
## Point-in-Time Fundamentals Core (`M2.2a`)
Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals.rs`, tested in `src/fundamentals_tests.rs`) generic over listing key `K`. BSON decoding, Zstd Parquet writing, CLI `curate-*` wiring, and `MarketDataStore.fundamentalsAsOf` are deferred to follow-up tasks.

View file

@ -18,8 +18,8 @@ use parquet::file::reader::{FileReader, SerializedFileReader};
use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent};
use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume};
use crate::bars_1m::{
build_bars_1m, check_session_closes, Bars1mError, Bars1mStats, DailySessionClose,
EodIntradayBar, IntradaySession, SessionCloseStats,
build_bars_1m, check_session_closes, Bar1mRow, Bars1mError, Bars1mStats, DailySessionClose,
EodIntradayBar, IntradaySession, SessionCloseStats, BARS_1M_SOURCE_EOD,
};
use crate::bson_eod_prices::{decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats};
use crate::bson_qm_actions::{
@ -44,6 +44,7 @@ use crate::fundamentals::{
FundamentalsError, FundamentalsFields, FundamentalsStats, StatutoryLagVenue,
};
use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar, FxSource, FX_PAIR_USDCAD};
use crate::ilp::{IlpShardedWriter, IlpWriterError, IlpWriterOptions};
use crate::parquet_adj::{
write_adj_factors_dataset, AdjFactorsParquetRow, AdjFactorsWriteOptions, ParquetAdjError,
};
@ -77,6 +78,8 @@ pub const DEFAULT_ADJ_BENCH_EVENTS: usize = 1_000_000;
pub const DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 1_000_000;
pub const DEFAULT_BARS_BENCH_ROWS: usize = 10_000_000;
pub const DEFAULT_BARS_1M_BENCH_ROWS: usize = 10_000_000;
pub const DEFAULT_ILP_BARS_1M_BENCH_ROWS: usize = DEFAULT_BARS_1M_BENCH_ROWS;
pub const ILP_BARS_1M_BENCH_SHARDS: usize = 4;
pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000;
pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000;
pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000;
@ -118,6 +121,7 @@ const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70;
const CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C049_AC71;
const BARS_BENCH_SEED: u64 = 0x570C_4B07_BA45_1D00;
const BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_BA45_0100;
const ILP_BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_119B_A451;
const BARS_1M_BENCH_KEY_COUNT: usize = 2_000;
const BARS_1M_BENCH_EVENT_COUNT: usize = 2_000;
const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE;
@ -1177,6 +1181,108 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result<Bars1mBenchReport, Bars1mErr
})
}
/// Summary metrics produced by [`run_ilp_bars_1m_benchmark`].
#[derive(Debug, Clone, PartialEq)]
pub struct IlpBars1mBenchReport {
pub rows: usize,
pub rows_encoded: usize,
pub key_count: usize,
pub shards: usize,
pub bytes: usize,
pub flushes: usize,
pub elapsed_ms: f64,
pub rows_per_sec: f64,
pub ns_per_row: f64,
pub bytes_per_row: f64,
pub mb_per_sec: f64,
pub per_shard_rows: Vec<usize>,
}
/// Runs the fixed-seed QuestDB ILP v2 `bars_1m` encoding + sharded batching benchmark for `rows`
/// curated 1-minute equity bars across four `std::io::sink()` shards.
///
/// Generates `rows` deterministic curated [`Bar1mRow<i32>`] records and `known_at` timestamps
/// across `2_000` `i32` listing IDs spanning `2024-01-02..=2025-12-31` (`PRE`/`RTH`/`POST`), then
/// times encoding and batching through [`IlpShardedWriter`] including [`IlpShardedWriter::finish`].
pub fn run_ilp_bars_1m_benchmark(rows: usize) -> Result<IlpBars1mBenchReport, IlpWriterError> {
let min_date = ymd_to_epoch_days(2024, 1, 2).unwrap_or(19_724);
let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453);
let date_span = (max_date - min_date + 1) as u64;
let mut rng = SplitMix64::new(ILP_BARS_1M_BENCH_SEED);
let mut input_rows: Vec<(Bar1mRow<i32>, i64)> = Vec::with_capacity(rows);
for _ in 0..rows {
let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1;
let session_date = min_date + (rng.next_u64() % date_span) as i32;
let et_minute = (480 + (rng.next_u64() % 720)) as u16;
let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0);
let ts = close_1600_utc + (i64::from(et_minute) - 960) * 60_000_000;
let known_at = ts + 60_000_000;
let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01;
let spread = ((rng.next_u64() % 300) + 5) as f64 * 0.01;
let high = low + spread;
let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01);
let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01);
let volume = ((rng.next_u64() % 500_000) + 10) as f64;
input_rows.push((
Bar1mRow {
key,
ts,
session_date,
open,
high,
low,
close,
volume,
session: IntradaySession::from_et_minute(et_minute),
source: BARS_1M_SOURCE_EOD,
},
known_at,
));
}
let sinks: Vec<io::Sink> = (0..ILP_BARS_1M_BENCH_SHARDS).map(|_| io::sink()).collect();
let mut writer = IlpShardedWriter::new(sinks, IlpWriterOptions::default())?;
let start = Instant::now();
for (row, known_at) in &input_rows {
writer.write_bar_1m(row, *known_at)?;
}
let stats = black_box(writer.finish()?);
let elapsed_secs = start.elapsed().as_secs_f64();
let elapsed_ms = elapsed_secs * 1_000.0;
let (rows_per_sec, ns_per_row) = compute_rates(stats.rows, elapsed_secs);
let bytes_per_row = if stats.rows == 0 {
0.0
} else {
stats.bytes as f64 / stats.rows as f64
};
let mb_per_sec = if elapsed_secs <= 0.0 || !elapsed_secs.is_finite() {
0.0
} else {
(stats.bytes as f64 / 1_000_000.0) / elapsed_secs
};
Ok(IlpBars1mBenchReport {
rows,
rows_encoded: stats.rows,
key_count: BARS_1M_BENCH_KEY_COUNT,
shards: ILP_BARS_1M_BENCH_SHARDS,
bytes: stats.bytes,
flushes: stats.flushes,
elapsed_ms,
rows_per_sec,
ns_per_row,
bytes_per_row,
mb_per_sec,
per_shard_rows: stats.per_shard_rows,
})
}
/// Summary metrics produced by [`run_fx_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FxBenchReport {
@ -13397,6 +13503,37 @@ mod tests {
assert_eq!(report.ns_per_row, 0.0);
}
#[test]
fn ilp_bars_1m_benchmark_small_run_is_deterministic_and_conserves_counts() {
let a = run_ilp_bars_1m_benchmark(5_000).unwrap();
let b = run_ilp_bars_1m_benchmark(5_000).unwrap();
assert_eq!(a.rows, 5_000);
assert_eq!(a.rows_encoded, a.rows);
assert_eq!(a.shards, ILP_BARS_1M_BENCH_SHARDS);
assert_eq!(a.bytes, b.bytes);
assert_eq!(a.flushes, b.flushes);
assert_eq!(a.per_shard_rows, b.per_shard_rows);
assert_eq!(a.per_shard_rows.len(), ILP_BARS_1M_BENCH_SHARDS);
assert_eq!(a.per_shard_rows.iter().sum::<usize>(), a.rows_encoded);
assert!(a.bytes > 0);
assert!(a.bytes_per_row > 100.0);
assert!(a.flushes >= ILP_BARS_1M_BENCH_SHARDS);
}
#[test]
fn ilp_bars_1m_benchmark_zero_rows_handles_cleanly() {
let report = run_ilp_bars_1m_benchmark(0).unwrap();
assert_eq!(report.rows, 0);
assert_eq!(report.rows_encoded, 0);
assert_eq!(report.bytes, 0);
assert_eq!(report.flushes, 0);
assert_eq!(report.bytes_per_row, 0.0);
assert_eq!(report.rows_per_sec, 0.0);
assert_eq!(report.ns_per_row, 0.0);
assert_eq!(report.per_shard_rows, vec![0; ILP_BARS_1M_BENCH_SHARDS]);
}
#[test]
fn fundamentals_benchmark_small_run_is_deterministic_and_conserves_counts() {
let a = run_fundamentals_benchmark(1_000).unwrap();

View file

@ -0,0 +1,663 @@
//! Zero-copy raw BSON decoder for MongoDB `eodIntraday1M` documents (`M2.3d`).
//!
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into
//! borrowed [`RawEodIntradayBar`] views without allocating a `String` or `bson::Document` per row.
//! Callers convert borrowed views into [`crate::bars_1m::EodIntradayBar<K>`] via a caller-supplied
//! key mapper (for example [`crate::provider_mapping::ProviderMappingTable::resolve`] or an
//! interned integer symbol ID), keeping the 3.40B-document path free of per-row `String`
//! allocations.
//!
//! # Empirical Field Contract & Cited Sources
//!
//! Field names and semantics are grounded in the repository's ingestion writer, historical reader,
//! and empirical data contract:
//! - `apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts:565-585` (`fetchIntraday`
//! writes `symbol`, `exchange`, `eodSearchCode`, `datetime`, `timestamp`, `gmtoffset`, `open`,
//! `high`, `low`, `close`, `volume`, `source` into `eodIntraday1M`, keyed by
//! `['timestamp', 'eodSearchCode']`)
//! - `libs/trading-runtime/src/historical-storage.ts:265-298` (`timestamp` is bar-start **UTC
//! Unix seconds**, not a local `datetime` label and not a publication / `known_at` time)
//! - `design/DATA-CONTRACTS.md` §1: `eodIntraday1M` (~3.40B docs) stores retroactively
//! split-adjusted OHLC and volume. This decoder passes those split-adjusted values through
//! untouched; split un-adjustment happens downstream in [`crate::bars_1m::build_bars_1m`].
//!
//! # Accepted BSON Representations & Daily-Decoder Conventions
//!
//! Where a rule is ambiguous, this module follows [`crate::bson_eod_prices`]:
//! - `eodSearchCode`: BSON UTF-8 `String`, borrowed verbatim (never trimmed). Empty or
//! whitespace-only strings are rejected as [`BsonEodIntradayError::EmptyField`]; non-string
//! values (including BSON `Null`) are rejected as [`BsonEodIntradayError::WrongType`].
//! - `timestamp`: bar-start UTC Unix seconds in BSON `Int32`, `Int64`, or finite integral `Double`
//! within `0..=i64::MAX / 1_000_000`, converted to UTC microseconds via checked multiplication
//! by `1_000_000`. Non-numeric types (including `Null` and `DateTime`) are rejected as
//! [`BsonEodIntradayError::WrongType`]; negative, fractional, non-finite, or microsecond-overflow
//! values are rejected as [`BsonEodIntradayError::InvalidTimestamp`].
//! - `open`, `high`, `low`, `close`: BSON `Double`, `Int32`, or `Int64`; must be finite and
//! strictly positive (`> 0.0`). Non-numeric types (including `Null`) are rejected as
//! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, `0.0`, `-0.0`, and `< 0.0` are rejected
//! as [`BsonEodIntradayError::InvalidNumber`].
//! - `volume`: BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` is
//! normalized to `+0.0`). Non-numeric types (including `Null`) are rejected as
//! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, and `< 0.0` are rejected as
//! [`BsonEodIntradayError::InvalidNumber`].
//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `datetime`, `gmtoffset`, `source`, nested
//! objects/arrays, etc.) are validated as borrowed `RawBsonRef` views (zero allocation) and
//! otherwise ignored, so malformed payloads (such as invalid UTF-8 in `datetime`) still surface
//! as [`BsonEodIntradayError::CorruptBson`].
//! - Error precedence: retains the first semantic error while continuing to scan remaining
//! top-level elements so any malformed BSON bytes surface immediately as `CorruptBson`.
use std::error::Error;
use std::fmt;
use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement};
use bson::spec::ElementType;
use crate::bars_1m::EodIntradayBar;
use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError};
const MICROS_PER_SECOND: i64 = 1_000_000;
/// Largest whole Unix-second timestamp that fits in signed `i64` microseconds (`9_223_372_036_854`).
pub(crate) const MAX_TIMESTAMP_SECONDS: i64 = i64::MAX / MICROS_PER_SECOND;
/// Borrowed zero-copy view of a single decoded `eodIntraday1M` BSON document.
///
/// Borrows `eod_search_code` directly from the underlying `&RawDocument` byte slice.
/// `open`, `high`, `low`, `close`, and `volume` are passed through as the provider's
/// split-adjusted values so [`crate::bars_1m::build_bars_1m`] can apply split un-adjustment.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RawEodIntradayBar<'a> {
pub eod_search_code: &'a str,
/// Bar start timestamp in UTC microseconds since the Unix epoch.
pub ts: i64,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub volume: f64,
}
impl<'a> RawEodIntradayBar<'a> {
/// Converts this borrowed view into an [`EodIntradayBar<K>`] using a caller-supplied key
/// mapper.
///
/// `map_key` receives `(eod_search_code, ts)` (provider code and UTC bar-start microseconds)
/// so callers can resolve an integer `listing_id` or interned key without allocating a per-row
/// `String`.
#[inline]
pub fn into_eod_intraday_bar<K, F>(self, map_key: F) -> EodIntradayBar<K>
where
F: FnOnce(&'a str, i64) -> K,
{
EodIntradayBar {
key: map_key(self.eod_search_code, self.ts),
ts: self.ts,
open: self.open,
high: self.high,
low: self.low,
close: self.close,
volume: self.volume,
}
}
/// Fallible conversion into [`EodIntradayBar<K>`] using a caller-supplied key resolver.
#[inline]
pub fn try_into_eod_intraday_bar<K, F>(self, map_key: F) -> Option<EodIntradayBar<K>>
where
F: FnOnce(&'a str, i64) -> Option<K>,
{
let key = map_key(self.eod_search_code, self.ts)?;
Some(EodIntradayBar {
key,
ts: self.ts,
open: self.open,
high: self.high,
low: self.low,
close: self.close,
volume: self.volume,
})
}
}
/// Typed errors returned while decoding raw `eodIntraday1M` BSON documents or length-prefixed
/// buffers.
///
/// Every field-level error names the offending BSON field in both its structure and `Display`
/// output; framing errors carry byte offsets; no input path panics.
#[derive(Debug, Clone, PartialEq)]
pub enum BsonEodIntradayError {
/// A required field was absent from the document.
MissingField { field: &'static str },
/// A required string field was empty or contained only whitespace.
EmptyField { field: &'static str },
/// A required field had an unexpected BSON element type (including `Null`).
WrongType {
field: &'static str,
actual: ElementType,
},
/// `timestamp` was negative, non-integral, non-finite, or overflowed `i64` microseconds.
InvalidTimestamp { field: &'static str },
/// An OHLC field was non-finite or `<= 0.0`, or `volume` was non-finite or `< 0.0`.
InvalidNumber { field: &'static str, value: f64 },
/// Buffer ended before a complete 4-byte length prefix or declared document body.
TruncatedDocument {
offset: usize,
remaining: usize,
declared_len: Option<i32>,
},
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
/// document slice).
CorruptDocumentLength { offset: usize, declared_len: i32 },
/// Underlying BSON framing or element bytes were malformed.
CorruptBson { offset: usize, detail: String },
}
impl fmt::Display for BsonEodIntradayError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingField { field } => {
write!(f, "eodIntraday1M BSON missing required field '{field}'")
}
Self::EmptyField { field } => {
write!(
f,
"eodIntraday1M BSON field '{field}' must not be empty or blank"
)
}
Self::WrongType { field, actual } => {
write!(
f,
"eodIntraday1M BSON field '{field}' has unexpected BSON type {actual:?}"
)
}
Self::InvalidTimestamp { field } => {
write!(
f,
"eodIntraday1M BSON field '{field}' is not a valid non-negative integral Unix-seconds timestamp within i64 microsecond range"
)
}
Self::InvalidNumber { field, value } => {
if *field == "volume" {
write!(
f,
"eodIntraday1M BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0"
)
} else {
write!(
f,
"eodIntraday1M BSON field '{field}' has invalid numeric value {value}: must be finite and > 0"
)
}
}
Self::TruncatedDocument {
offset,
remaining,
declared_len,
} => match declared_len {
Some(len) => write!(
f,
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
),
None => write!(
f,
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
),
},
Self::CorruptDocumentLength {
offset,
declared_len,
} => write!(
f,
"corrupt BSON document length {declared_len} at byte offset {offset}"
),
Self::CorruptBson { offset, detail } => {
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
}
}
}
}
impl Error for BsonEodIntradayError {}
#[inline]
fn map_framing_error(err: BsonEodPriceError) -> BsonEodIntradayError {
match err {
BsonEodPriceError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonEodIntradayError::TruncatedDocument {
offset,
remaining,
declared_len,
},
BsonEodPriceError::CorruptDocumentLength {
offset,
declared_len,
} => BsonEodIntradayError::CorruptDocumentLength {
offset,
declared_len,
},
BsonEodPriceError::CorruptBson { offset, detail } => {
BsonEodIntradayError::CorruptBson { offset, detail }
}
BsonEodPriceError::MissingField { field } => BsonEodIntradayError::MissingField { field },
BsonEodPriceError::EmptyField { field } => BsonEodIntradayError::EmptyField { field },
BsonEodPriceError::WrongType { field, actual } => {
BsonEodIntradayError::WrongType { field, actual }
}
BsonEodPriceError::MalformedDate { field } => {
BsonEodIntradayError::InvalidTimestamp { field }
}
BsonEodPriceError::InvalidNumber { field, value } => {
BsonEodIntradayError::InvalidNumber { field, value }
}
}
}
/// Per-batch decode and rejection accounting for [`decode_eod_intraday_buffer`].
///
/// Conservation invariant: `rows_decoded + rejected_total() == docs_seen`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BsonEodIntradayDecodeStats {
pub docs_seen: usize,
pub rows_decoded: usize,
pub rejected_missing_field: usize,
pub rejected_empty_field: usize,
pub rejected_wrong_type: usize,
pub rejected_invalid_timestamp: usize,
pub rejected_invalid_number: usize,
pub rejected_corrupt_document: usize,
}
impl BsonEodIntradayDecodeStats {
/// Total number of rejected documents across all error categories.
#[inline]
pub fn rejected_total(&self) -> usize {
self.rejected_missing_field
+ self.rejected_empty_field
+ self.rejected_wrong_type
+ self.rejected_invalid_timestamp
+ self.rejected_invalid_number
+ self.rejected_corrupt_document
}
/// Increments the rejection counter corresponding to `err`.
#[inline]
pub fn record_error(&mut self, err: &BsonEodIntradayError) {
match err {
BsonEodIntradayError::MissingField { .. } => self.rejected_missing_field += 1,
BsonEodIntradayError::EmptyField { .. } => self.rejected_empty_field += 1,
BsonEodIntradayError::WrongType { .. } => self.rejected_wrong_type += 1,
BsonEodIntradayError::InvalidTimestamp { .. } => self.rejected_invalid_timestamp += 1,
BsonEodIntradayError::InvalidNumber { .. } => self.rejected_invalid_number += 1,
BsonEodIntradayError::TruncatedDocument { .. }
| BsonEodIntradayError::CorruptDocumentLength { .. }
| BsonEodIntradayError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
}
}
/// Accumulates counters from another batch into `self`.
#[inline]
pub fn merge(&mut self, other: &Self) {
self.docs_seen += other.docs_seen;
self.rows_decoded += other.rows_decoded;
self.rejected_missing_field += other.rejected_missing_field;
self.rejected_empty_field += other.rejected_empty_field;
self.rejected_wrong_type += other.rejected_wrong_type;
self.rejected_invalid_timestamp += other.rejected_invalid_timestamp;
self.rejected_invalid_number += other.rejected_invalid_number;
self.rejected_corrupt_document += other.rejected_corrupt_document;
}
}
impl std::ops::AddAssign for BsonEodIntradayDecodeStats {
#[inline]
fn add_assign(&mut self, rhs: Self) {
self.merge(&rhs);
}
}
#[inline]
fn decode_element_value<'a>(
field: &'static str,
elem: RawElement<'a>,
offset: usize,
) -> Result<RawBsonRef<'a>, BsonEodIntradayError> {
elem.value().map_err(|err| BsonEodIntradayError::CorruptBson {
offset,
detail: format!("field '{field}': {err}"),
})
}
#[inline]
fn decode_timestamp_seconds_to_micros(val: RawBsonRef<'_>) -> Result<i64, BsonEodIntradayError> {
let secs = match val {
RawBsonRef::Int32(v) => {
if v < 0 {
return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" });
}
i64::from(v)
}
RawBsonRef::Int64(v) => {
if v < 0 {
return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" });
}
v
}
RawBsonRef::Double(v) => {
// `MAX_TIMESTAMP_SECONDS` (9_223_372_036_854 < 2^44) is well within `f64`'s exact
// 53-bit integer range, so both the upper bound and the cast are exact.
if !v.is_finite()
|| v < 0.0
|| v.fract() != 0.0
|| v > MAX_TIMESTAMP_SECONDS as f64
{
return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" });
}
v as i64
}
other => {
return Err(BsonEodIntradayError::WrongType {
field: "timestamp",
actual: other.element_type(),
});
}
};
secs.checked_mul(MICROS_PER_SECOND)
.ok_or(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" })
}
#[inline]
fn decode_positive_number(
field: &'static str,
val: RawBsonRef<'_>,
) -> Result<f64, BsonEodIntradayError> {
match val {
RawBsonRef::Double(v) => {
if !v.is_finite() || v <= 0.0 {
return Err(BsonEodIntradayError::InvalidNumber { field, value: v });
}
Ok(v)
}
RawBsonRef::Int32(v) => {
if v <= 0 {
return Err(BsonEodIntradayError::InvalidNumber {
field,
value: f64::from(v),
});
}
Ok(f64::from(v))
}
RawBsonRef::Int64(v) => {
if v <= 0 {
return Err(BsonEodIntradayError::InvalidNumber {
field,
value: v as f64,
});
}
Ok(v as f64)
}
other => Err(BsonEodIntradayError::WrongType {
field,
actual: other.element_type(),
}),
}
}
#[inline]
fn decode_non_negative_number(
field: &'static str,
val: RawBsonRef<'_>,
) -> Result<f64, BsonEodIntradayError> {
match val {
RawBsonRef::Double(v) => {
if !v.is_finite() || v < 0.0 {
return Err(BsonEodIntradayError::InvalidNumber { field, value: v });
}
if v == 0.0 {
Ok(0.0)
} else {
Ok(v)
}
}
RawBsonRef::Int32(v) => {
if v < 0 {
return Err(BsonEodIntradayError::InvalidNumber {
field,
value: f64::from(v),
});
}
Ok(f64::from(v))
}
RawBsonRef::Int64(v) => {
if v < 0 {
return Err(BsonEodIntradayError::InvalidNumber {
field,
value: v as f64,
});
}
Ok(v as f64)
}
other => Err(BsonEodIntradayError::WrongType {
field,
actual: other.element_type(),
}),
}
}
fn decode_eod_intraday_doc_at<'a>(
doc: &'a RawDocument,
offset: usize,
) -> Result<RawEodIntradayBar<'a>, BsonEodIntradayError> {
let mut eod_search_code: Option<&'a str> = None;
let mut ts: Option<i64> = None;
let mut open: Option<f64> = None;
let mut high: Option<f64> = None;
let mut low: Option<f64> = None;
let mut close: Option<f64> = None;
let mut volume: Option<f64> = None;
let mut first_semantic_err: Option<BsonEodIntradayError> = None;
for elem_res in doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonEodIntradayError::CorruptBson {
offset,
detail: err.to_string(),
})?;
let key = elem.key();
if key == cstr!("eodSearchCode") {
match decode_element_value("eodSearchCode", elem, offset)? {
RawBsonRef::String(s) => {
if s.trim().is_empty() {
if first_semantic_err.is_none() {
first_semantic_err = Some(BsonEodIntradayError::EmptyField {
field: "eodSearchCode",
});
}
} else {
eod_search_code = Some(s);
}
}
other => {
if first_semantic_err.is_none() {
first_semantic_err = Some(BsonEodIntradayError::WrongType {
field: "eodSearchCode",
actual: other.element_type(),
});
}
}
}
} else if key == cstr!("timestamp") {
let val = decode_element_value("timestamp", elem, offset)?;
match decode_timestamp_seconds_to_micros(val) {
Ok(micros) => ts = Some(micros),
Err(err) => {
if first_semantic_err.is_none() {
first_semantic_err = Some(err);
}
}
}
} else if key == cstr!("open") {
let val = decode_element_value("open", elem, offset)?;
match decode_positive_number("open", val) {
Ok(v) => open = Some(v),
Err(err) => {
if first_semantic_err.is_none() {
first_semantic_err = Some(err);
}
}
}
} else if key == cstr!("high") {
let val = decode_element_value("high", elem, offset)?;
match decode_positive_number("high", val) {
Ok(v) => high = Some(v),
Err(err) => {
if first_semantic_err.is_none() {
first_semantic_err = Some(err);
}
}
}
} else if key == cstr!("low") {
let val = decode_element_value("low", elem, offset)?;
match decode_positive_number("low", val) {
Ok(v) => low = Some(v),
Err(err) => {
if first_semantic_err.is_none() {
first_semantic_err = Some(err);
}
}
}
} else if key == cstr!("close") {
let val = decode_element_value("close", elem, offset)?;
match decode_positive_number("close", val) {
Ok(v) => close = Some(v),
Err(err) => {
if first_semantic_err.is_none() {
first_semantic_err = Some(err);
}
}
}
} else if key == cstr!("volume") {
let val = decode_element_value("volume", elem, offset)?;
match decode_non_negative_number("volume", val) {
Ok(v) => volume = Some(v),
Err(err) => {
if first_semantic_err.is_none() {
first_semantic_err = Some(err);
}
}
}
} else {
// Validate skipped top-level payloads via borrowed `RawBsonRef` views (zero
// allocation) so malformed bytes (e.g. invalid UTF-8 in `datetime`) still reject the
// document as `CorruptBson` at its frame offset.
elem.value().map_err(|err| BsonEodIntradayError::CorruptBson {
offset,
detail: format!("field '{}': {err}", key.as_str()),
})?;
}
}
if let Some(err) = first_semantic_err {
return Err(err);
}
let Some(eod_search_code) = eod_search_code else {
return Err(BsonEodIntradayError::MissingField {
field: "eodSearchCode",
});
};
let Some(ts) = ts else {
return Err(BsonEodIntradayError::MissingField { field: "timestamp" });
};
let Some(open) = open else {
return Err(BsonEodIntradayError::MissingField { field: "open" });
};
let Some(high) = high else {
return Err(BsonEodIntradayError::MissingField { field: "high" });
};
let Some(low) = low else {
return Err(BsonEodIntradayError::MissingField { field: "low" });
};
let Some(close) = close else {
return Err(BsonEodIntradayError::MissingField { field: "close" });
};
let Some(volume) = volume else {
return Err(BsonEodIntradayError::MissingField { field: "volume" });
};
Ok(RawEodIntradayBar {
eod_search_code,
ts,
open,
high,
low,
close,
volume,
})
}
/// Decodes a single `&RawDocument` representing an `eodIntraday1M` MongoDB document in one forward
/// pass without allocating a `String` or owned `bson::Document`.
#[inline]
pub fn decode_eod_intraday_doc<'a>(
doc: &'a RawDocument,
) -> Result<RawEodIntradayBar<'a>, BsonEodIntradayError> {
decode_eod_intraday_doc_at(doc, 0)
}
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
/// [`RawEodIntradayBar`].
pub fn decode_eod_intraday_bytes<'a>(
bytes: &'a [u8],
) -> Result<RawEodIntradayBar<'a>, BsonEodIntradayError> {
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
decode_eod_intraday_doc_at(doc, 0)
}
/// Streams a concatenated length-prefixed BSON buffer through [`decode_eod_intraday_doc`],
/// invoking `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected
/// document without aborting the stream on per-document errors.
///
/// Always maintains `stats.rows_decoded + stats.rejected_total() == stats.docs_seen`.
pub fn decode_eod_intraday_buffer<'a, F, E>(
buf: &'a [u8],
mut on_bar: F,
mut on_error: E,
) -> BsonEodIntradayDecodeStats
where
F: FnMut(RawEodIntradayBar<'a>),
E: FnMut(usize, BsonEodIntradayError),
{
let mut stats = BsonEodIntradayDecodeStats::default();
let mut iter = iter_raw_bson_docs(buf);
while let Some(item) = iter.next_with_offset() {
stats.docs_seen += 1;
match item {
Ok((doc_offset, doc)) => match decode_eod_intraday_doc_at(doc, doc_offset) {
Ok(bar) => {
stats.rows_decoded += 1;
on_bar(bar);
}
Err(err) => {
stats.record_error(&err);
on_error(doc_offset, err);
}
},
Err((doc_offset, err)) => {
let mapped = map_framing_error(err);
stats.record_error(&mapped);
on_error(doc_offset, mapped);
}
}
}
stats
}
#[cfg(test)]
#[path = "bson_eod_intraday_tests.rs"]
mod tests;

View file

@ -0,0 +1,896 @@
use bson::oid::ObjectId;
use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf};
use bson::spec::ElementType;
use bson::DateTime;
use super::*;
use crate::bars_1m::{build_bars_1m, IntradaySession, BARS_1M_SOURCE_EOD};
use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable};
fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).unwrap()
}
fn make_valid_doc(
code: &str,
timestamp_sec: i64,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
) -> RawDocumentBuf {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), code);
doc.append(cstr!("timestamp"), timestamp_sec);
doc.append(cstr!("open"), open);
doc.append(cstr!("high"), high);
doc.append(cstr!("low"), low);
doc.append(cstr!("close"), close);
doc.append(cstr!("volume"), volume);
doc
}
fn make_doc_with_timestamp(timestamp: RawBsonRef<'_>) -> RawDocumentBuf {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), "NVDA.US");
doc.append(cstr!("timestamp"), timestamp);
doc.append(cstr!("open"), 120.15_f64);
doc.append(cstr!("high"), 120.42_f64);
doc.append(cstr!("low"), 120.05_f64);
doc.append(cstr!("close"), 120.38_f64);
doc.append(cstr!("volume"), 842_500.0_f64);
doc
}
fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) {
let diff = (actual - expected).abs();
let scale = expected.abs().max(1.0);
assert!(
diff <= rel_tol * scale,
"actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}"
);
}
#[test]
fn decodes_nvda_fixture_across_int32_int64_double_timestamps_and_ignores_metadata() {
const TS_SEC: i32 = 1_717_767_000;
const EXPECTED_TS_MICROS: i64 = 1_717_767_000_000_000;
let mut nested = RawDocumentBuf::new();
nested.append(cstr!("provider"), "eodhd");
nested.append(cstr!("interval"), "1m");
let mut tags = RawArrayBuf::new();
tags.push("us");
tags.push("intraday");
let mut doc_i32 = RawDocumentBuf::new();
doc_i32.append(
cstr!("_id"),
ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
);
doc_i32.append(cstr!("symbol"), "NVDA");
doc_i32.append(cstr!("exchange"), "US");
doc_i32.append(cstr!("eodSearchCode"), "NVDA.US");
doc_i32.append(cstr!("datetime"), "2024-06-07 13:30:00");
doc_i32.append(cstr!("timestamp"), TS_SEC);
doc_i32.append(cstr!("gmtoffset"), 0_i32);
doc_i32.append(cstr!("open"), 119.77_f64);
doc_i32.append(cstr!("high"), 121.692_f64);
doc_i32.append(cstr!("low"), 118.022_f64);
doc_i32.append(cstr!("close"), 120.888_f64);
doc_i32.append(cstr!("volume"), 412_390.0_f64);
doc_i32.append(cstr!("source"), "eod");
doc_i32.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
doc_i32.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
let bar_i32 = decode_eod_intraday_doc(&doc_i32).unwrap();
assert_eq!(bar_i32.eod_search_code, "NVDA.US");
assert_eq!(bar_i32.ts, EXPECTED_TS_MICROS);
assert_eq!(bar_i32.open.to_bits(), 119.77_f64.to_bits());
assert_eq!(bar_i32.high.to_bits(), 121.692_f64.to_bits());
assert_eq!(bar_i32.low.to_bits(), 118.022_f64.to_bits());
assert_eq!(bar_i32.close.to_bits(), 120.888_f64.to_bits());
assert_eq!(bar_i32.volume.to_bits(), 412_390.0_f64.to_bits());
// decode_eod_intraday_bytes matches decode_eod_intraday_doc bit-for-bit.
let from_bytes = decode_eod_intraday_bytes(doc_i32.as_bytes()).unwrap();
assert_eq!(from_bytes, bar_i32);
// Same document with timestamp as Int64 and as integral Double decodes identically.
let mut doc_i64 = RawDocumentBuf::new();
doc_i64.append(cstr!("eodSearchCode"), "NVDA.US");
doc_i64.append(cstr!("timestamp"), i64::from(TS_SEC));
doc_i64.append(cstr!("open"), 119.77_f64);
doc_i64.append(cstr!("high"), 121.692_f64);
doc_i64.append(cstr!("low"), 118.022_f64);
doc_i64.append(cstr!("close"), 120.888_f64);
doc_i64.append(cstr!("volume"), 412_390.0_f64);
let mut doc_f64 = RawDocumentBuf::new();
doc_f64.append(cstr!("eodSearchCode"), "NVDA.US");
doc_f64.append(cstr!("timestamp"), f64::from(TS_SEC));
doc_f64.append(cstr!("open"), 119.77_f64);
doc_f64.append(cstr!("high"), 121.692_f64);
doc_f64.append(cstr!("low"), 118.022_f64);
doc_f64.append(cstr!("close"), 120.888_f64);
doc_f64.append(cstr!("volume"), 412_390.0_f64);
let bar_i64 = decode_eod_intraday_doc(&doc_i64).unwrap();
let bar_f64 = decode_eod_intraday_doc(&doc_f64).unwrap();
assert_eq!(bar_i64, bar_i32);
assert_eq!(bar_f64, bar_i32);
// Verify into_eod_intraday_bar and try_into_eod_intraday_bar pass exact (code, ts).
let mut seen_into: Option<(&str, i64)> = None;
let mapped = bar_i32.into_eod_intraday_bar(|code, ts| {
seen_into = Some((code, ts));
42_u64
});
assert_eq!(seen_into, Some(("NVDA.US", EXPECTED_TS_MICROS)));
assert_eq!(mapped.key, 42_u64);
assert_eq!(mapped.ts, EXPECTED_TS_MICROS);
assert_eq!(mapped.close.to_bits(), 120.888_f64.to_bits());
let mut seen_try_some: Option<(&str, i64)> = None;
let try_some = bar_i32.try_into_eod_intraday_bar(|code, ts| {
seen_try_some = Some((code, ts));
Some(99_u64)
});
assert_eq!(seen_try_some, Some(("NVDA.US", EXPECTED_TS_MICROS)));
assert_eq!(try_some.unwrap().key, 99_u64);
let try_none: Option<EodIntradayBar<u64>> = bar_i32.try_into_eod_intraday_bar(|code, ts| {
assert_eq!(code, "NVDA.US");
assert_eq!(ts, EXPECTED_TS_MICROS);
None
});
assert!(try_none.is_none());
}
#[test]
fn borrows_eod_search_code_zero_copy_from_input_buffer() {
let doc = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0);
let bytes = doc.as_bytes();
let buf_start = bytes.as_ptr() as usize;
let buf_end = buf_start + bytes.len();
let bar = decode_eod_intraday_bytes(bytes).unwrap();
let code_start = bar.eod_search_code.as_ptr() as usize;
let code_end = code_start + bar.eod_search_code.len();
assert!(
code_start >= buf_start && code_end <= buf_end,
"expected eod_search_code pointer {code_start:#x}..{code_end:#x} inside input buffer {buf_start:#x}..{buf_end:#x}"
);
assert_eq!(bar.eod_search_code, "NVDA.US");
}
#[test]
fn accepts_mixed_numeric_types_zero_volume_and_timestamp_boundaries() {
let mut mixed = RawDocumentBuf::new();
mixed.append(cstr!("eodSearchCode"), "SHOP.TO");
mixed.append(cstr!("timestamp"), 0_i32);
mixed.append(cstr!("open"), 100_i32);
mixed.append(cstr!("high"), 105_i64);
mixed.append(cstr!("low"), 99.5_f64);
mixed.append(cstr!("close"), 104_i32);
mixed.append(cstr!("volume"), 5_000_000_000_i64);
let bar = decode_eod_intraday_doc(&mixed).unwrap();
assert_eq!(bar.eod_search_code, "SHOP.TO");
assert_eq!(bar.ts, 0);
assert_eq!(bar.open.to_bits(), 100.0_f64.to_bits());
assert_eq!(bar.high.to_bits(), 105.0_f64.to_bits());
assert_eq!(bar.low.to_bits(), 99.5_f64.to_bits());
assert_eq!(bar.close.to_bits(), 104.0_f64.to_bits());
assert_eq!(bar.volume.to_bits(), 5_000_000_000.0_f64.to_bits());
// Epoch zero in Int32, Int64, Double (+0.0 and -0.0).
for zero_ts in [
RawBsonRef::Int32(0),
RawBsonRef::Int64(0),
RawBsonRef::Double(0.0),
RawBsonRef::Double(-0.0),
] {
let doc = make_doc_with_timestamp(zero_ts);
let decoded = decode_eod_intraday_doc(&doc).unwrap();
assert_eq!(decoded.ts, 0);
}
// Largest accepted whole second in Int64 and Double.
let expected_max_micros = MAX_TIMESTAMP_SECONDS * 1_000_000;
for max_ts in [
RawBsonRef::Int64(MAX_TIMESTAMP_SECONDS),
RawBsonRef::Double(MAX_TIMESTAMP_SECONDS as f64),
] {
let doc = make_doc_with_timestamp(max_ts);
let decoded = decode_eod_intraday_doc(&doc).unwrap();
assert_eq!(decoded.ts, expected_max_micros);
}
// Zero volume in Double (+0.0, -0.0), Int32 (0), Int64 (0) normalizes to +0.0.
for zero_vol in [
RawBsonRef::Double(0.0),
RawBsonRef::Double(-0.0),
RawBsonRef::Int32(0),
RawBsonRef::Int64(0),
] {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), "NVDA.US");
doc.append(cstr!("timestamp"), 1_717_767_000_i64);
doc.append(cstr!("open"), 10.0_f64);
doc.append(cstr!("high"), 11.0_f64);
doc.append(cstr!("low"), 9.5_f64);
doc.append(cstr!("close"), 10.5_f64);
doc.append(cstr!("volume"), zero_vol);
let decoded = decode_eod_intraday_doc(&doc).unwrap();
assert_eq!(decoded.volume.to_bits(), 0.0_f64.to_bits());
}
}
#[test]
fn rejects_invalid_eod_search_code_variants_with_matching_stats() {
// Missing eodSearchCode
let mut missing = RawDocumentBuf::new();
missing.append(cstr!("timestamp"), 1_717_767_000_i64);
missing.append(cstr!("open"), 10.0_f64);
missing.append(cstr!("high"), 11.0_f64);
missing.append(cstr!("low"), 9.0_f64);
missing.append(cstr!("close"), 10.5_f64);
missing.append(cstr!("volume"), 100.0_f64);
let err = decode_eod_intraday_doc(&missing).unwrap_err();
assert_eq!(
err,
BsonEodIntradayError::MissingField {
field: "eodSearchCode"
}
);
let mut stats = BsonEodIntradayDecodeStats::default();
stats.record_error(&err);
assert_eq!(stats.rejected_missing_field, 1);
assert_eq!(stats.rejected_total(), 1);
// Empty and whitespace-only keys
for blank in ["", " ", "\t\n\r "] {
let doc = make_valid_doc(blank, 1_717_767_000, 10.0, 11.0, 9.0, 10.5, 100.0);
let err = decode_eod_intraday_doc(&doc).unwrap_err();
assert_eq!(
err,
BsonEodIntradayError::EmptyField {
field: "eodSearchCode"
}
);
let mut s = BsonEodIntradayDecodeStats::default();
s.record_error(&err);
assert_eq!(s.rejected_empty_field, 1);
assert_eq!(s.rejected_total(), 1);
}
// Wrong BSON types for eodSearchCode
let wrong_types: [(RawBsonRef<'_>, ElementType); 3] = [
(RawBsonRef::Null, ElementType::Null),
(RawBsonRef::Int32(123), ElementType::Int32),
(RawBsonRef::Boolean(true), ElementType::Boolean),
];
for (val, expected_type) in wrong_types {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), val);
doc.append(cstr!("timestamp"), 1_717_767_000_i64);
doc.append(cstr!("open"), 10.0_f64);
doc.append(cstr!("high"), 11.0_f64);
doc.append(cstr!("low"), 9.0_f64);
doc.append(cstr!("close"), 10.5_f64);
doc.append(cstr!("volume"), 100.0_f64);
let err = decode_eod_intraday_doc(&doc).unwrap_err();
assert_eq!(
err,
BsonEodIntradayError::WrongType {
field: "eodSearchCode",
actual: expected_type,
}
);
let mut s = BsonEodIntradayDecodeStats::default();
s.record_error(&err);
assert_eq!(s.rejected_wrong_type, 1);
assert_eq!(s.rejected_total(), 1);
}
}
#[test]
fn rejects_invalid_timestamp_variants_with_matching_stats() {
// Missing timestamp
let mut missing = RawDocumentBuf::new();
missing.append(cstr!("eodSearchCode"), "NVDA.US");
missing.append(cstr!("open"), 10.0_f64);
missing.append(cstr!("high"), 11.0_f64);
missing.append(cstr!("low"), 9.0_f64);
missing.append(cstr!("close"), 10.5_f64);
missing.append(cstr!("volume"), 100.0_f64);
let err = decode_eod_intraday_doc(&missing).unwrap_err();
assert_eq!(err, BsonEodIntradayError::MissingField { field: "timestamp" });
let mut stats = BsonEodIntradayDecodeStats::default();
stats.record_error(&err);
assert_eq!(stats.rejected_missing_field, 1);
assert_eq!(stats.rejected_total(), 1);
// Wrong BSON types for timestamp
let wrong_types: [(RawBsonRef<'_>, ElementType); 4] = [
(RawBsonRef::Null, ElementType::Null),
(RawBsonRef::String("1717767000"), ElementType::String),
(
RawBsonRef::DateTime(DateTime::from_millis(1_717_767_000_000)),
ElementType::DateTime,
),
(RawBsonRef::Boolean(false), ElementType::Boolean),
];
for (val, expected_type) in wrong_types {
let doc = make_doc_with_timestamp(val);
let err = decode_eod_intraday_doc(&doc).unwrap_err();
assert_eq!(
err,
BsonEodIntradayError::WrongType {
field: "timestamp",
actual: expected_type,
}
);
let mut s = BsonEodIntradayDecodeStats::default();
s.record_error(&err);
assert_eq!(s.rejected_wrong_type, 1);
assert_eq!(s.rejected_total(), 1);
}
// Invalid numeric timestamps: fractional, NaN, inf, -inf, negative, overflowing
let invalid_timestamps: [RawBsonRef<'_>; 11] = [
RawBsonRef::Double(1_717_767_000.5),
RawBsonRef::Double(0.25),
RawBsonRef::Double(f64::NAN),
RawBsonRef::Double(f64::INFINITY),
RawBsonRef::Double(f64::NEG_INFINITY),
RawBsonRef::Int32(-1),
RawBsonRef::Int64(-1),
RawBsonRef::Double(-1.0),
RawBsonRef::Int64(MAX_TIMESTAMP_SECONDS + 1),
RawBsonRef::Int64(i64::MAX),
RawBsonRef::Double((MAX_TIMESTAMP_SECONDS + 1) as f64),
];
for bad_ts in invalid_timestamps {
let doc = make_doc_with_timestamp(bad_ts);
let err = decode_eod_intraday_doc(&doc).unwrap_err();
assert_eq!(
err,
BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }
);
let mut s = BsonEodIntradayDecodeStats::default();
s.record_error(&err);
assert_eq!(s.rejected_invalid_timestamp, 1);
assert_eq!(s.rejected_total(), 1);
}
}
#[test]
fn rejects_invalid_ohlc_and_volume_variants_with_matching_stats() {
let ohlc_fields = ["open", "high", "low", "close"];
for target in ohlc_fields {
// Missing field
let mut missing = RawDocumentBuf::new();
missing.append(cstr!("eodSearchCode"), "NVDA.US");
missing.append(cstr!("timestamp"), 1_717_767_000_i64);
for (f, key) in [
("open", cstr!("open")),
("high", cstr!("high")),
("low", cstr!("low")),
("close", cstr!("close")),
("volume", cstr!("volume")),
] {
if f != target {
missing.append(key, 10.0_f64);
}
}
let err = decode_eod_intraday_doc(&missing).unwrap_err();
assert_eq!(err, BsonEodIntradayError::MissingField { field: target });
let mut s = BsonEodIntradayDecodeStats::default();
s.record_error(&err);
assert_eq!(s.rejected_missing_field, 1);
assert_eq!(s.rejected_total(), 1);
let build_with_field = |val: RawBsonRef<'_>| {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), "NVDA.US");
doc.append(cstr!("timestamp"), 1_717_767_000_i64);
for (name, key) in [
("open", cstr!("open")),
("high", cstr!("high")),
("low", cstr!("low")),
("close", cstr!("close")),
("volume", cstr!("volume")),
] {
if name == target {
doc.append(key, val);
} else {
doc.append(key, 10.0_f64);
}
}
doc
};
// Null and wrong types -> WrongType
for (val, expected_type) in [
(RawBsonRef::Null, ElementType::Null),
(RawBsonRef::String("10.0"), ElementType::String),
(RawBsonRef::Boolean(true), ElementType::Boolean),
] {
let doc = build_with_field(val);
let err = decode_eod_intraday_doc(&doc).unwrap_err();
assert_eq!(
err,
BsonEodIntradayError::WrongType {
field: target,
actual: expected_type,
}
);
let mut st = BsonEodIntradayDecodeStats::default();
st.record_error(&err);
assert_eq!(st.rejected_wrong_type, 1);
assert_eq!(st.rejected_total(), 1);
}
// Non-finite, zero, and negative -> InvalidNumber
for bad_num in [
RawBsonRef::Double(f64::NAN),
RawBsonRef::Double(f64::INFINITY),
RawBsonRef::Double(f64::NEG_INFINITY),
RawBsonRef::Double(0.0),
RawBsonRef::Double(-0.0),
RawBsonRef::Double(-1.25),
RawBsonRef::Int32(0),
RawBsonRef::Int32(-5),
RawBsonRef::Int64(0),
RawBsonRef::Int64(-5),
] {
let doc = build_with_field(bad_num);
let err = decode_eod_intraday_doc(&doc).unwrap_err();
match &err {
BsonEodIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, target),
other => panic!("expected InvalidNumber for {target}, got {other:?}"),
}
let mut st = BsonEodIntradayDecodeStats::default();
st.record_error(&err);
assert_eq!(st.rejected_invalid_number, 1);
assert_eq!(st.rejected_total(), 1);
}
}
// Volume: missing, Null/wrong-type, negative/NaN/inf
let mut missing_vol = RawDocumentBuf::new();
missing_vol.append(cstr!("eodSearchCode"), "NVDA.US");
missing_vol.append(cstr!("timestamp"), 1_717_767_000_i64);
missing_vol.append(cstr!("open"), 10.0_f64);
missing_vol.append(cstr!("high"), 11.0_f64);
missing_vol.append(cstr!("low"), 9.0_f64);
missing_vol.append(cstr!("close"), 10.5_f64);
let err = decode_eod_intraday_doc(&missing_vol).unwrap_err();
assert_eq!(err, BsonEodIntradayError::MissingField { field: "volume" });
let build_with_vol = |val: RawBsonRef<'_>| {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), "NVDA.US");
doc.append(cstr!("timestamp"), 1_717_767_000_i64);
doc.append(cstr!("open"), 10.0_f64);
doc.append(cstr!("high"), 11.0_f64);
doc.append(cstr!("low"), 9.0_f64);
doc.append(cstr!("close"), 10.5_f64);
doc.append(cstr!("volume"), val);
doc
};
for (val, expected_type) in [
(RawBsonRef::Null, ElementType::Null),
(RawBsonRef::String("100"), ElementType::String),
(RawBsonRef::Boolean(false), ElementType::Boolean),
] {
let doc = build_with_vol(val);
let err = decode_eod_intraday_doc(&doc).unwrap_err();
assert_eq!(
err,
BsonEodIntradayError::WrongType {
field: "volume",
actual: expected_type,
}
);
let mut st = BsonEodIntradayDecodeStats::default();
st.record_error(&err);
assert_eq!(st.rejected_wrong_type, 1);
assert_eq!(st.rejected_total(), 1);
}
for bad_vol in [
RawBsonRef::Double(-0.01),
RawBsonRef::Double(f64::NAN),
RawBsonRef::Double(f64::INFINITY),
RawBsonRef::Double(f64::NEG_INFINITY),
RawBsonRef::Int32(-1),
RawBsonRef::Int64(-1),
] {
let doc = build_with_vol(bad_vol);
let err = decode_eod_intraday_doc(&doc).unwrap_err();
match &err {
BsonEodIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, "volume"),
other => panic!("expected InvalidNumber for volume, got {other:?}"),
}
let mut st = BsonEodIntradayDecodeStats::default();
st.record_error(&err);
assert_eq!(st.rejected_invalid_number, 1);
assert_eq!(st.rejected_total(), 1);
}
}
#[test]
fn rejects_truncated_and_corrupt_single_doc_bytes_without_panicking() {
// Truncated header (< 4 bytes)
assert_eq!(
decode_eod_intraday_bytes(&[0x10, 0x00]),
Err(BsonEodIntradayError::TruncatedDocument {
offset: 0,
remaining: 2,
declared_len: None,
})
);
// Declared length < 5
assert_eq!(
decode_eod_intraday_bytes(&[4, 0, 0, 0]),
Err(BsonEodIntradayError::CorruptDocumentLength {
offset: 0,
declared_len: 4,
})
);
// Truncated body (declared_len > remaining)
let valid = make_valid_doc("NVDA.US", 1_717_767_000, 10.0, 11.0, 9.0, 10.5, 100.0);
let truncated = &valid.as_bytes()[..valid.as_bytes().len() - 3];
assert_eq!(
decode_eod_intraday_bytes(truncated),
Err(BsonEodIntradayError::TruncatedDocument {
offset: 0,
remaining: truncated.len(),
declared_len: Some(valid.as_bytes().len() as i32),
})
);
// Trailing extra bytes on single-doc decode -> CorruptDocumentLength
let mut with_trailing = valid.as_bytes().to_vec();
with_trailing.push(0x00);
assert_eq!(
decode_eod_intraday_bytes(&with_trailing),
Err(BsonEodIntradayError::CorruptDocumentLength {
offset: 0,
declared_len: valid.as_bytes().len() as i32,
})
);
// Malformed BSON (missing trailing null terminator)
let mut bad_term = valid.as_bytes().to_vec();
*bad_term.last_mut().unwrap() = 0xFF;
match decode_eod_intraday_bytes(&bad_term) {
Err(BsonEodIntradayError::CorruptBson { offset: 0, .. }) => {}
other => panic!("expected CorruptBson, got {other:?}"),
}
}
#[test]
fn rejects_corrupt_utf8_in_skipped_top_level_field_and_recovers_to_next_frame() {
// Build a valid document with a skipped `datetime` string field, then corrupt one payload byte
// inside `datetime` to invalid UTF-8 (0xFF) while leaving all lengths and NUL terminators
// intact.
const DATETIME_MARKER: &[u8] = b"2024-06-07 13:30:00";
let mut doc_with_datetime = make_valid_doc(
"NVDA.US",
1_717_767_000,
120.50,
121.25,
120.10,
120.90,
1_000.0,
);
doc_with_datetime.append(cstr!("datetime"), "2024-06-07 13:30:00");
let mut corrupt_bytes = doc_with_datetime.as_bytes().to_vec();
let marker_pos = corrupt_bytes
.windows(DATETIME_MARKER.len())
.position(|w| w == DATETIME_MARKER)
.expect("datetime payload must exist in serialized BSON");
corrupt_bytes[marker_pos + 4] = 0xFF;
// Single-document decode must reject as CorruptBson at offset 0.
match decode_eod_intraday_bytes(&corrupt_bytes) {
Err(BsonEodIntradayError::CorruptBson { offset: 0, detail }) => {
assert!(
detail.contains("datetime"),
"expected offending field name in detail, got: {detail}"
);
}
other => panic!("expected CorruptBson at offset 0, got {other:?}"),
}
// Buffer decode with a preceding valid frame and a following valid frame: rejects the
// damaged frame at its exact byte offset, increments `rejected_corrupt_document`, and
// recovers cleanly to decode the next frame.
let valid_before =
make_valid_doc("AAPL.US", 1_717_766_940, 195.0, 196.0, 194.5, 195.5, 500.0);
let valid_after =
make_valid_doc("MSFT.US", 1_717_767_060, 420.0, 421.0, 419.5, 420.5, 750.0);
let mut buf = Vec::new();
buf.extend_from_slice(valid_before.as_bytes());
let corrupt_offset = buf.len();
buf.extend_from_slice(&corrupt_bytes);
buf.extend_from_slice(valid_after.as_bytes());
let mut rows = Vec::new();
let mut errors = Vec::new();
let stats = decode_eod_intraday_buffer(
&buf,
|bar| rows.push((bar.eod_search_code.to_owned(), bar.ts, bar.close)),
|off, err| errors.push((off, err)),
);
assert_eq!(
rows,
vec![
("AAPL.US".to_owned(), 1_717_766_940_000_000, 195.5),
("MSFT.US".to_owned(), 1_717_767_060_000_000, 420.5),
]
);
assert_eq!(stats.docs_seen, 3);
assert_eq!(stats.rows_decoded, 2);
assert_eq!(stats.rejected_corrupt_document, 1);
assert_eq!(stats.rejected_total(), 1);
assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total());
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].0, corrupt_offset);
assert!(matches!(
&errors[0].1,
BsonEodIntradayError::CorruptBson { offset, detail }
if *offset == corrupt_offset && detail.contains("datetime")
));
}
#[test]
fn decodes_mixed_buffer_preserving_order_recovering_past_corrupt_frame_and_merging_stats() {
let valid1 = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0);
let empty_key = make_valid_doc(" ", 1_717_767_060, 120.5, 121.0, 120.0, 120.8, 500.0);
let bad_ts = make_doc_with_timestamp(RawBsonRef::Double(1_717_767_120.5));
let bad_price = make_valid_doc("NVDA.US", 1_717_767_180, 0.0, 121.0, 119.0, 120.0, 200.0);
let mut wrong_type = RawDocumentBuf::new();
wrong_type.append(cstr!("eodSearchCode"), "NVDA.US");
wrong_type.append(cstr!("timestamp"), 1_717_767_240_i64);
wrong_type.append(cstr!("open"), RawBsonRef::Null);
wrong_type.append(cstr!("high"), 121.0_f64);
wrong_type.append(cstr!("low"), 119.0_f64);
wrong_type.append(cstr!("close"), 120.0_f64);
wrong_type.append(cstr!("volume"), 200.0_f64);
let mut missing_field = RawDocumentBuf::new();
missing_field.append(cstr!("eodSearchCode"), "NVDA.US");
missing_field.append(cstr!("timestamp"), 1_717_767_300_i64);
missing_field.append(cstr!("open"), 120.0_f64);
missing_field.append(cstr!("high"), 121.0_f64);
missing_field.append(cstr!("low"), 119.0_f64);
missing_field.append(cstr!("close"), 120.0_f64);
// Valid length-framed doc whose trailing terminator is corrupt -> CorruptBson, but buffer
// iteration recovers and decodes valid2 after it.
let mut corrupt_framed = valid1.as_bytes().to_vec();
*corrupt_framed.last_mut().unwrap() = 0xAA;
let valid2 = make_valid_doc("AAPL.US", 1_717_767_360, 195.0, 196.0, 194.5, 195.5, 0.0);
let mut buf = Vec::new();
buf.extend_from_slice(valid1.as_bytes());
let off_empty = buf.len();
buf.extend_from_slice(empty_key.as_bytes());
let off_bad_ts = buf.len();
buf.extend_from_slice(bad_ts.as_bytes());
let off_bad_price = buf.len();
buf.extend_from_slice(bad_price.as_bytes());
let off_wrong_type = buf.len();
buf.extend_from_slice(wrong_type.as_bytes());
let off_missing = buf.len();
buf.extend_from_slice(missing_field.as_bytes());
let off_corrupt = buf.len();
buf.extend_from_slice(&corrupt_framed);
buf.extend_from_slice(valid2.as_bytes());
let mut rows = Vec::new();
let mut errors = Vec::new();
let stats = decode_eod_intraday_buffer(
&buf,
|bar| rows.push((bar.eod_search_code.to_owned(), bar.ts, bar.close, bar.volume)),
|offset, err| errors.push((offset, err)),
);
assert_eq!(rows.len(), 2);
assert_eq!(rows[0], ("NVDA.US".to_owned(), 1_717_767_000_000_000, 120.5, 1000.0));
assert_eq!(rows[1], ("AAPL.US".to_owned(), 1_717_767_360_000_000, 195.5, 0.0));
assert_eq!(stats.docs_seen, 8);
assert_eq!(stats.rows_decoded, 2);
assert_eq!(stats.rejected_empty_field, 1);
assert_eq!(stats.rejected_invalid_timestamp, 1);
assert_eq!(stats.rejected_invalid_number, 1);
assert_eq!(stats.rejected_wrong_type, 1);
assert_eq!(stats.rejected_missing_field, 1);
assert_eq!(stats.rejected_corrupt_document, 1);
assert_eq!(stats.rejected_total(), 6);
assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total());
assert_eq!(errors.len(), 6);
assert_eq!(errors[0].0, off_empty);
assert_eq!(errors[1].0, off_bad_ts);
assert_eq!(errors[2].0, off_bad_price);
assert_eq!(errors[3].0, off_wrong_type);
assert_eq!(errors[4].0, off_missing);
assert_eq!(errors[5].0, off_corrupt);
assert!(matches!(
errors[5].1,
BsonEodIntradayError::CorruptBson { offset, .. } if offset == off_corrupt
));
// Verify BsonEodIntradayDecodeStats::merge sums every counter.
let mut merged = BsonEodIntradayDecodeStats {
docs_seen: 10,
rows_decoded: 4,
rejected_missing_field: 1,
rejected_empty_field: 1,
rejected_wrong_type: 1,
rejected_invalid_timestamp: 1,
rejected_invalid_number: 1,
rejected_corrupt_document: 1,
};
merged.merge(&stats);
assert_eq!(
merged,
BsonEodIntradayDecodeStats {
docs_seen: 18,
rows_decoded: 6,
rejected_missing_field: 2,
rejected_empty_field: 2,
rejected_wrong_type: 2,
rejected_invalid_timestamp: 2,
rejected_invalid_number: 2,
rejected_corrupt_document: 2,
}
);
assert_eq!(merged.docs_seen, merged.rows_decoded + merged.rejected_total());
// Truncated tail stops cleanly and still maintains conservation invariant.
let mut with_trunc = buf.clone();
let trunc_off = with_trunc.len();
with_trunc.extend_from_slice(&valid2.as_bytes()[..10]);
let mut trunc_errs = Vec::new();
let trunc_stats = decode_eod_intraday_buffer(
&with_trunc,
|_| {},
|off, err| trunc_errs.push((off, err)),
);
assert_eq!(trunc_stats.docs_seen, 9);
assert_eq!(trunc_stats.rows_decoded, 2);
assert_eq!(trunc_stats.rejected_corrupt_document, 2);
assert_eq!(
trunc_stats.docs_seen,
trunc_stats.rows_decoded + trunc_stats.rejected_total()
);
assert_eq!(trunc_errs.last().unwrap().0, trunc_off);
assert!(matches!(
trunc_errs.last().unwrap().1,
BsonEodIntradayError::TruncatedDocument { offset, remaining: 10, declared_len: Some(_) }
if offset == trunc_off
));
}
#[test]
fn decoded_nvda_bars_feed_build_bars_1m_end_to_end_with_10_for_1_split() {
// NVDA 10:1 split ex-date: 2024-06-10.
// Bar 1: 2024-06-07 15:59 ET (EDT, UTC-4) = 2024-06-07 19:59:00 UTC = 1_717_790_340 s.
// Bar 2: 2024-06-10 09:30 ET (EDT, UTC-4) = 2024-06-10 13:30:00 UTC = 1_718_026_200 s.
const PRE_SPLIT_TS_SEC: i64 = 1_717_790_340;
const EX_DATE_TS_SEC: i64 = 1_718_026_200;
// Provider's retroactively split-adjusted 1m values.
let pre_split_doc = make_valid_doc(
"NVDA.US",
PRE_SPLIT_TS_SEC,
120.80,
121.05,
120.72,
120.888,
2_500_000.0,
);
let ex_date_doc = make_valid_doc(
"NVDA.US",
EX_DATE_TS_SEC,
120.37,
121.10,
120.15,
120.95,
1_800_000.0,
);
let mut raw_buf = Vec::new();
raw_buf.extend_from_slice(pre_split_doc.as_bytes());
raw_buf.extend_from_slice(ex_date_doc.as_bytes());
let splits = SplitTable::from_events([(
"NVDA.US".to_owned(),
SplitEvent {
ex_date: day(2024, 6, 10),
ratio: 10.0,
},
)])
.unwrap();
let empty_splits = SplitTable::<String>::default();
let run_once = |table: &SplitTable<String>| {
let mut bars = Vec::new();
let mut decode_errors = Vec::new();
let decode_stats = decode_eod_intraday_buffer(
&raw_buf,
|raw| bars.push(raw.into_eod_intraday_bar(|code, _ts| code.to_owned())),
|off, err| decode_errors.push((off, err)),
);
assert!(decode_errors.is_empty());
assert_eq!(decode_stats.docs_seen, 2);
assert_eq!(decode_stats.rows_decoded, 2);
let built = build_bars_1m(bars, table);
(decode_stats, built)
};
let (stats_split, built_split) = run_once(&splits);
let (stats_empty, built_empty) = run_once(&empty_splits);
let (stats_replay, built_replay) = run_once(&splits);
// Deterministic replay produces identical rows and stats.
assert_eq!(stats_split, stats_replay);
assert_eq!(built_split.rows, built_replay.rows);
assert_eq!(built_split.stats, built_replay.stats);
assert_eq!(stats_split, stats_empty);
assert_eq!(built_split.rows.len(), 2);
assert_eq!(built_empty.rows.len(), 2);
// Pre-split bar: OHLC * 10, volume / 10, dollar volume (close * volume) conserved.
let pre_split = &built_split.rows[0];
let pre_empty = &built_empty.rows[0];
assert_eq!(pre_split.key, "NVDA.US");
assert_eq!(pre_split.ts, PRE_SPLIT_TS_SEC * 1_000_000);
assert_eq!(pre_split.session_date, day(2024, 6, 7));
assert_eq!(pre_split.session, IntradaySession::Rth);
assert_eq!(pre_split.source, BARS_1M_SOURCE_EOD);
assert_rel_eq(pre_split.open, pre_empty.open * 10.0, 1e-12);
assert_rel_eq(pre_split.high, pre_empty.high * 10.0, 1e-12);
assert_rel_eq(pre_split.low, pre_empty.low * 10.0, 1e-12);
assert_rel_eq(pre_split.close, 1_208.88, 1e-12);
assert_rel_eq(pre_split.close, pre_empty.close * 10.0, 1e-12);
assert_rel_eq(pre_split.volume, pre_empty.volume / 10.0, 1e-12);
assert_rel_eq(
pre_split.close * pre_split.volume,
pre_empty.close * pre_empty.volume,
1e-12,
);
// Ex-date bar: unchanged by the 2024-06-10 split (strict ex_date > session_date boundary).
let ex_split = &built_split.rows[1];
let ex_empty = &built_empty.rows[1];
assert_eq!(ex_split.ts, EX_DATE_TS_SEC * 1_000_000);
assert_eq!(ex_split.session_date, day(2024, 6, 10));
assert_eq!(ex_split.session, IntradaySession::Rth);
assert_eq!(ex_split.open.to_bits(), ex_empty.open.to_bits());
assert_eq!(ex_split.high.to_bits(), ex_empty.high.to_bits());
assert_eq!(ex_split.low.to_bits(), ex_empty.low.to_bits());
assert_eq!(ex_split.close.to_bits(), ex_empty.close.to_bits());
assert_eq!(ex_split.volume.to_bits(), ex_empty.volume.to_bits());
}

View file

@ -24,6 +24,10 @@ use std::io;
use crate::bson_ceo_shorts::{
decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames,
};
use crate::bson_eod_intraday::{
decode_eod_intraday_buffer, BsonEodIntradayDecodeStats, BsonEodIntradayError,
RawEodIntradayBar,
};
use crate::bson_eod_prices::{
decode_eod_price_buffer, BsonEodDecodeStats, BsonEodPriceError, RawEodDailyBar,
};
@ -531,6 +535,84 @@ fn rebase_qm_error(base: u64, err: BsonQmActionError) -> BsonQmActionError {
}
}
#[inline]
fn rebase_eod_intraday_error(base: u64, err: BsonEodIntradayError) -> BsonEodIntradayError {
match err {
BsonEodIntradayError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonEodIntradayError::TruncatedDocument {
offset: rebase_offset(base, offset),
remaining,
declared_len,
},
BsonEodIntradayError::CorruptDocumentLength {
offset,
declared_len,
} => BsonEodIntradayError::CorruptDocumentLength {
offset: rebase_offset(base, offset),
declared_len,
},
BsonEodIntradayError::CorruptBson { offset, detail } => {
BsonEodIntradayError::CorruptBson {
offset: rebase_offset(base, offset),
detail,
}
}
other => other,
}
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_intraday_buffer`],
/// accumulating [`BsonEodIntradayDecodeStats`] and rebasing per-document error offsets to
/// absolute stream byte offsets.
pub fn decode_eod_intraday_chunks<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
mut on_bar: F,
mut on_error: E,
) -> Result<BsonEodIntradayDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawEodIntradayBar<'a>),
E: FnMut(u64, BsonEodIntradayError),
{
let mut total = BsonEodIntradayDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_eod_intraday_buffer(
chunk.bytes,
&mut on_bar,
|local_offset, err| {
let abs_offset = base + local_offset as u64;
on_error(abs_offset, rebase_eod_intraday_error(base, err));
},
);
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `eodIntraday1M` [`std::io::Read`] source through
/// [`decode_eod_intraday_buffer`] with bounded memory.
///
/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset
/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`.
pub fn decode_eod_intraday_stream<R, F, E>(
reader: R,
options: BsonStreamOptions,
on_bar: F,
on_error: E,
) -> Result<BsonEodIntradayDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawEodIntradayBar<'a>),
E: FnMut(u64, BsonEodIntradayError),
{
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_eod_intraday_chunks(&mut chunk_reader, on_bar, on_error)
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_price_buffer`],
/// accumulating [`BsonEodDecodeStats`] and rebasing per-document error offsets to absolute stream
/// byte offsets.

View file

@ -4,6 +4,9 @@ use std::io::{self, Cursor, Read};
use bson::raw::{cstr, RawDocumentBuf};
use bson::DateTime;
use crate::bson_eod_intraday::{
decode_eod_intraday_buffer, BsonEodIntradayError,
};
use crate::bson_eod_prices::{
decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats,
};
@ -12,9 +15,10 @@ use crate::bson_qm_actions::{
};
use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError};
use crate::bson_stream::{
decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_price_stream,
decode_qm_split_stream, BsonStreamError, BsonStreamOptions, RawBsonChunkReader,
DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_stream,
decode_qm_dividend_stream, decode_qm_price_stream, decode_qm_split_stream, BsonStreamError,
BsonStreamOptions, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES,
MIN_BSON_DOC_BYTES,
};
#[derive(Debug, Clone, Copy)]
@ -2113,3 +2117,164 @@ fn decode_qm_price_stream_matches_buffer_rebases_offsets_and_fails_on_framing()
.unwrap_err();
assert!(matches!(err, BsonStreamError::TruncatedDocument { .. }));
}
#[test]
fn decode_eod_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() {
let make_doc = |code: &str, ts: i64, open: f64, close: f64, vol: f64| -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), code);
doc.append(cstr!("timestamp"), ts);
doc.append(cstr!("open"), open);
doc.append(cstr!("high"), open.max(close) + 0.5);
doc.append(cstr!("low"), open.min(close) - 0.5);
doc.append(cstr!("close"), close);
doc.append(cstr!("volume"), vol);
doc.into_bytes()
};
let mut fixture = Vec::new();
fixture.extend_from_slice(&make_doc("NVDA.US", 1_717_767_000, 120.0, 120.5, 1000.0));
fixture.extend_from_slice(&make_doc("AAPL.US", 1_717_767_060, 195.0, 195.25, 0.0));
// Semantic error: invalid timestamp (negative)
let bad_ts_offset = fixture.len() as u64;
fixture.extend_from_slice(&make_doc("NVDA.US", -60, 120.0, 120.5, 100.0));
// Valid length-framed doc with corrupt trailing terminator -> CorruptBson with embedded offset
let mut corrupt_bytes = make_doc("MSFT.US", 1_717_767_120, 420.0, 421.0, 500.0);
*corrupt_bytes.last_mut().unwrap() = 0xEE;
let corrupt_offset = fixture.len() as u64;
fixture.extend_from_slice(&corrupt_bytes);
fixture.extend_from_slice(&make_doc("SHOP.TO", 1_717_767_180, 88.0, 88.4, 2500.0));
let mut expected_rows = Vec::new();
let mut expected_errs = Vec::new();
let expected_stats = decode_eod_intraday_buffer(
&fixture,
|b| {
expected_rows.push((
b.eod_search_code.to_owned(),
b.ts,
b.open.to_bits(),
b.high.to_bits(),
b.low.to_bits(),
b.close.to_bits(),
b.volume.to_bits(),
))
},
|off, err| expected_errs.push((off as u64, err)),
);
assert_eq!(expected_stats.docs_seen, 5);
assert_eq!(expected_stats.rows_decoded, 3);
assert_eq!(expected_stats.rejected_invalid_timestamp, 1);
assert_eq!(expected_stats.rejected_corrupt_document, 1);
assert_eq!(expected_stats.rejected_total(), 2);
// Exercise decode_eod_intraday_stream across small capacities and short reads splitting
// length prefixes and document bodies.
for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (512, 13)] {
let opts = BsonStreamOptions {
chunk_capacity_bytes: cap,
max_doc_bytes: 4096,
};
let mut got_rows = Vec::new();
let mut got_errs = Vec::new();
let got_stats = decode_eod_intraday_stream(
FixedStepReader::new(&fixture, step),
opts,
|b| {
got_rows.push((
b.eod_search_code.to_owned(),
b.ts,
b.open.to_bits(),
b.high.to_bits(),
b.low.to_bits(),
b.close.to_bits(),
b.volume.to_bits(),
))
},
|off, err| got_errs.push((off, err)),
)
.unwrap();
assert_eq!(got_stats, expected_stats);
assert_eq!(got_rows, expected_rows);
assert_eq!(got_errs, expected_errs);
assert_eq!(got_errs[0].0, bad_ts_offset);
assert!(matches!(
got_errs[1],
(off, BsonEodIntradayError::CorruptBson { offset, .. })
if off == corrupt_offset && offset as u64 == corrupt_offset
));
}
// Exercise decode_eod_intraday_chunks directly with random read sizes and EINTR interrupts.
let opts = BsonStreamOptions {
chunk_capacity_bytes: 32,
max_doc_bytes: 4096,
};
let mut chunk_reader =
RawBsonChunkReader::with_options(RandomInterruptReader::new(&fixture, 0x141, true), opts)
.unwrap();
let mut chunk_rows = Vec::new();
let mut chunk_errs = Vec::new();
let chunk_stats = decode_eod_intraday_chunks(
&mut chunk_reader,
|b| {
chunk_rows.push((
b.eod_search_code.to_owned(),
b.ts,
b.open.to_bits(),
b.high.to_bits(),
b.low.to_bits(),
b.close.to_bits(),
b.volume.to_bits(),
))
},
|off, err| chunk_errs.push((off, err)),
)
.unwrap();
assert_eq!(chunk_stats, expected_stats);
assert_eq!(chunk_rows, expected_rows);
assert_eq!(chunk_errs, expected_errs);
// Truncated trailing document must deliver the complete prefix first and then return
// BsonStreamError::TruncatedDocument at the exact tail offset.
let mut truncated = fixture.clone();
let trunc_offset = truncated.len() as u64;
truncated.extend_from_slice(&120_i32.to_le_bytes());
truncated.extend_from_slice(&[0x02, b'a', 0x00]);
let mut prefix_rows = Vec::new();
let mut prefix_errs = Vec::new();
let err = decode_eod_intraday_stream(
FixedStepReader::new(&truncated, 5),
BsonStreamOptions {
chunk_capacity_bytes: 32,
max_doc_bytes: 4096,
},
|b| {
prefix_rows.push((
b.eod_search_code.to_owned(),
b.ts,
b.open.to_bits(),
b.high.to_bits(),
b.low.to_bits(),
b.close.to_bits(),
b.volume.to_bits(),
))
},
|off, e| prefix_errs.push((off, e)),
)
.unwrap_err();
assert_eq!(prefix_rows, expected_rows);
assert_eq!(prefix_errs, expected_errs);
assert!(matches!(
err,
BsonStreamError::TruncatedDocument {
offset,
remaining: 7,
declared_len: Some(120),
} if offset == trunc_offset
));
}

View file

@ -19,7 +19,7 @@ use crate::bench::{
DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS,
DEFAULT_CURATE_FX_CMD_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS,
DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
DEFAULT_FUNDAMENTALS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS,
DEFAULT_FUNDAMENTALS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_ILP_BARS_1M_BENCH_ROWS,
DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS,
DEFAULT_PARQUET_BARS_BENCH_ROWS,
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
@ -73,6 +73,7 @@ pub enum CliAction {
BenchCorporateActions(usize),
BenchBars(usize),
BenchBars1m(usize),
BenchIlpBars1m(usize),
BenchFx(usize),
BenchShorts(usize),
BenchEvents(usize),
@ -133,6 +134,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
{name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\
{name} bench-bars [rows] Run fixed-seed bars_1d build + cross-check benchmark (default: {DEFAULT_BARS_BENCH_ROWS})\n\
{name} bench-bars-1m [rows] Run fixed-seed bars_1m build + session-close cross-check benchmark (default: {DEFAULT_BARS_1M_BENCH_ROWS})\n\
{name} bench-ilp-bars-1m [rows] Run fixed-seed QuestDB ILP v2 bars_1m encode + sharded batch benchmark (default: {DEFAULT_ILP_BARS_1M_BENCH_ROWS})\n\
{name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\
{name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\
{name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\
@ -180,6 +182,7 @@ pub fn format_usage_stderr(name: &str) -> String {
{name} bench-corporate-actions [events]\n\
{name} bench-bars [rows]\n\
{name} bench-bars-1m [rows]\n\
{name} bench-ilp-bars-1m [rows]\n\
{name} bench-fx [rows]\n\
{name} bench-shorts [rows]\n\
{name} bench-events [rows]\n\
@ -1478,6 +1481,14 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
)),
},
["bench-bars-1m", _, ..] => Err("too many arguments for bench-bars-1m".to_string()),
["bench-ilp-bars-1m"] => Ok(CliAction::BenchIlpBars1m(DEFAULT_ILP_BARS_1M_BENCH_ROWS)),
["bench-ilp-bars-1m", raw] => match raw.parse::<usize>() {
Ok(n) if n > 0 => Ok(CliAction::BenchIlpBars1m(n)),
_ => Err(format!(
"invalid row count '{raw}' (expected a positive integer)"
)),
},
["bench-ilp-bars-1m", _, ..] => Err("too many arguments for bench-ilp-bars-1m".to_string()),
["bench-fx"] => Ok(CliAction::BenchFx(DEFAULT_FX_BENCH_ROWS)),
["bench-fx", raw] => match raw.parse::<usize>() {
Ok(n) if n > 0 => Ok(CliAction::BenchFx(n)),
@ -3421,6 +3432,20 @@ mod tests {
assert!(parse_args(&to_args(&["bench-curate-events-cmd", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-curate-events-cmd", "1", "2"])).is_err());
// bench-ilp-bars-1m
assert_eq!(
parse_args(&to_args(&["bench-ilp-bars-1m"])),
Ok(CliAction::BenchIlpBars1m(DEFAULT_ILP_BARS_1M_BENCH_ROWS))
);
assert_eq!(
parse_args(&to_args(&["bench-ilp-bars-1m", "2500"])),
Ok(CliAction::BenchIlpBars1m(2_500))
);
assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "0"])).is_err());
assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "-5"])).is_err());
assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "1", "2"])).is_err());
// bench-fundamentals
assert_eq!(
parse_args(&to_args(&["bench-fundamentals"])),

567
tools/curate-etl/src/ilp.rs Normal file
View file

@ -0,0 +1,567 @@
//! Pure, socket-free QuestDB ILP v2 line encoder and sharded batch writer for
//! `bars_1m` and `fx_1m`.
//!
//! # Wire format (QuestDB ILP Protocol Version 2)
//!
//! Verified against the official `questdb-rs` client source in
//! `questdb/c-questdb-client` (`main` branch, `questdb-rs`):
//! - Binary `DOUBLE` type tag (`DOUBLE_TYPE = 16` / `0x10`):
//! `questdb-rs/src/ingress.rs` lines 157–159.
//! - Tag/field separators and binary `f64` field encoding (`<name>==\x10<8 LE IEEE-754 bytes>`):
//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 569–713.
//! - ILP escaping for `SYMBOL` values (space, `,`, `=`, `\n`, `\r`, and `\` prefixed with `\`):
//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 36–84.
//! - Timestamp column microsecond suffix (`<name>=<epoch_micros>t`):
//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1026–1047.
//! - Designated timestamp microsecond suffix (` <epoch_micros>t\n`, non-negative):
//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1087–1116.
//!
//! # Table contracts
//!
//! Column names and types match `M2_INTRADAY_SCHEMAS` in `libs/data/questdb/src/schema.ts`
//! and `design/DATA-CONTRACTS.md` §3.B:
//! - `bars_1m`: symbols `listing_id`, `session`, `source`; binary doubles `open`, `high`, `low`,
//! `close`, `volume` (`vwap` is omitted / NULL); timestamp column `known_at`; designated
//! timestamp `ts` (UTC microseconds).
//! - `fx_1m`: symbols `pair`, `source`; binary doubles `open`, `high`, `low`, `close`;
//! designated timestamp `ts` (UTC microseconds).
//!
//! # Deterministic sharding
//!
//! [`IlpShardedWriter`] routes rows deterministically using 64-bit FNV-1a modulo shard count
//! (`fnv1a_64(key_bytes) % shard_count`):
//! - `bars_1m` hashes `listing_id` as its 4-byte little-endian representation
//! (`listing_id.to_le_bytes()`).
//! - `fx_1m` hashes `pair` as its raw UTF-8 bytes (`pair.as_bytes()`).
//!
//! All rows for a given key always land on the same shard in their exact input order, preserving
//! the per-key ordering required by `DEDUP UPSERT KEYS(ts, listing_id)` / `KEYS(ts, pair)`.
use std::error::Error;
use std::fmt;
use std::io::{self, Write};
use crate::bars_1m::Bar1mRow;
/// QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`).
pub const ILP_V2_DOUBLE_TYPE: u8 = 0x10;
/// Canonical QuestDB table name for 1-minute equity bars.
pub const TABLE_BARS_1M: &str = "bars_1m";
/// Canonical QuestDB table name for 1-minute FX bars.
pub const TABLE_FX_1M: &str = "fx_1m";
/// 64-bit FNV-1a offset basis used for deterministic shard routing.
pub const FNV1A_64_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
/// 64-bit FNV-1a prime used for deterministic shard routing.
pub const FNV1A_64_PRIME: u64 = 0x0000_0100_0000_01b3;
/// Default maximum buffered bytes per shard before flushing a batch (1 MiB).
pub const DEFAULT_ILP_MAX_BATCH_BYTES: usize = 1_048_576;
/// Default maximum buffered rows per shard before flushing a batch.
pub const DEFAULT_ILP_MAX_BATCH_ROWS: usize = 10_000;
/// A single `fx_1m` 1-minute FX bar input for QuestDB ILP v2 encoding.
///
/// Matches `M2_INTRADAY_SCHEMAS.fx_1m` in `libs/data/questdb/src/schema.ts`:
/// `pair` (SYMBOL), `open`/`high`/`low`/`close` (DOUBLE), `source` (SYMBOL), `ts` (TIMESTAMP).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Fx1mRow<'a> {
pub pair: &'a str,
/// Bar start timestamp in UTC microseconds since the Unix epoch (must be `>= 0`).
pub ts: i64,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub source: &'a str,
}
/// Typed validation errors returned by [`encode_bar_1m`] and [`encode_fx_1m`].
///
/// Encoding is atomic: when an error is returned, the caller's destination buffer is left
/// completely unmodified.
#[derive(Debug, Clone, PartialEq)]
pub enum IlpEncodeError {
/// A `DOUBLE` field was non-finite (`NaN`, `+inf`, or `-inf`).
NonFiniteDouble { field: &'static str, value: f64 },
/// The designated timestamp `ts` was negative (QuestDB ILP requires `ts >= 0`).
NegativeTimestamp { field: &'static str, value: i64 },
/// A required `SYMBOL` column value was empty.
EmptySymbol { field: &'static str },
}
impl fmt::Display for IlpEncodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::NonFiniteDouble { field, value } => {
write!(f, "non-finite ILP double field '{field}': {value}")
}
Self::NegativeTimestamp { field, value } => {
write!(
f,
"negative ILP designated timestamp '{field}': {value} (must be >= 0)"
)
}
Self::EmptySymbol { field } => {
write!(f, "empty ILP symbol field '{field}'")
}
}
}
}
impl Error for IlpEncodeError {}
/// Batching limits for [`IlpShardedWriter`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IlpWriterOptions {
/// Maximum buffered bytes per shard before flushing (must be `>= 1`).
pub max_batch_bytes: usize,
/// Maximum buffered rows per shard before flushing (must be `>= 1`).
pub max_batch_rows: usize,
}
impl Default for IlpWriterOptions {
fn default() -> Self {
Self {
max_batch_bytes: DEFAULT_ILP_MAX_BATCH_BYTES,
max_batch_rows: DEFAULT_ILP_MAX_BATCH_ROWS,
}
}
}
/// Summary statistics returned by [`IlpShardedWriter::finish`].
///
/// Conservation invariants:
/// - `per_shard_rows.iter().sum::<usize>() == rows`
/// - `bytes` equals the exact sum of bytes written across all successful shard `write_all` calls.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IlpWriteStats {
pub rows: usize,
pub bytes: usize,
pub flushes: usize,
pub per_shard_rows: Vec<usize>,
}
/// Typed errors returned by [`IlpShardedWriter`].
#[derive(Debug)]
pub enum IlpWriterError {
/// No sinks were provided to [`IlpShardedWriter::new`].
EmptySinks,
/// [`IlpWriterOptions::max_batch_bytes`] was `0`.
ZeroMaxBatchBytes,
/// [`IlpWriterOptions::max_batch_rows`] was `0`.
ZeroMaxBatchRows,
/// Row encoding failed before mutating any shard buffer.
Encode(IlpEncodeError),
/// A sink `write_all` or `flush` call failed on `shard`.
Io { shard: usize, source: io::Error },
/// A previous I/O failure on `failed_shard` poisoned the writer; no further writes are allowed.
Poisoned { failed_shard: usize },
}
impl fmt::Display for IlpWriterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptySinks => write!(f, "ILP sharded writer requires at least one sink"),
Self::ZeroMaxBatchBytes => {
write!(f, "ILP writer max_batch_bytes must be >= 1")
}
Self::ZeroMaxBatchRows => {
write!(f, "ILP writer max_batch_rows must be >= 1")
}
Self::Encode(err) => write!(f, "ILP encode error: {err}"),
Self::Io { shard, source } => {
write!(f, "ILP writer I/O error on shard {shard}: {source}")
}
Self::Poisoned { failed_shard } => write!(
f,
"ILP writer is poisoned after prior I/O error on shard {failed_shard}"
),
}
}
}
impl Error for IlpWriterError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Encode(err) => Some(err),
Self::Io { source, .. } => Some(source),
Self::EmptySinks
| Self::ZeroMaxBatchBytes
| Self::ZeroMaxBatchRows
| Self::Poisoned { .. } => None,
}
}
}
impl From<IlpEncodeError> for IlpWriterError {
fn from(err: IlpEncodeError) -> Self {
Self::Encode(err)
}
}
/// Computes the 64-bit FNV-1a hash of `bytes`.
#[inline]
pub fn fnv1a_64(bytes: &[u8]) -> u64 {
let mut hash = FNV1A_64_OFFSET_BASIS;
for &b in bytes {
hash ^= u64::from(b);
hash = hash.wrapping_mul(FNV1A_64_PRIME);
}
hash
}
/// Deterministic shard index for an equity `listing_id` (`i32` hashed as 4 little-endian bytes).
#[inline]
pub fn shard_for_listing_id(listing_id: i32, shard_count: usize) -> usize {
debug_assert!(shard_count > 0);
(fnv1a_64(&listing_id.to_le_bytes()) % (shard_count as u64)) as usize
}
/// Deterministic shard index for an FX `pair` (hashed as raw UTF-8 bytes).
#[inline]
pub fn shard_for_fx_pair(pair: &str, shard_count: usize) -> usize {
debug_assert!(shard_count > 0);
(fnv1a_64(pair.as_bytes()) % (shard_count as u64)) as usize
}
#[inline]
fn validate_finite(field: &'static str, value: f64) -> Result<(), IlpEncodeError> {
if value.is_finite() {
Ok(())
} else {
Err(IlpEncodeError::NonFiniteDouble { field, value })
}
}
#[inline]
fn validate_non_negative_ts(field: &'static str, value: i64) -> Result<(), IlpEncodeError> {
if value >= 0 {
Ok(())
} else {
Err(IlpEncodeError::NegativeTimestamp { field, value })
}
}
/// Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`.
#[inline]
fn write_escaped_symbol(buf: &mut Vec<u8>, value: &str) {
let bytes = value.as_bytes();
let mut last = 0usize;
for (i, &b) in bytes.iter().enumerate() {
if matches!(b, b' ' | b',' | b'=' | b'\n' | b'\r' | b'\\') {
if last < i {
buf.extend_from_slice(&bytes[last..i]);
}
buf.push(b'\\');
buf.push(b);
last = i + 1;
}
}
if last < bytes.len() {
buf.extend_from_slice(&bytes[last..]);
}
}
#[inline]
fn write_i64_decimal(buf: &mut Vec<u8>, value: i64) {
let mut tmp = [0u8; 20];
let negative = value < 0;
let mut mag = value.unsigned_abs();
let mut pos = tmp.len();
if mag == 0 {
pos -= 1;
tmp[pos] = b'0';
} else {
while mag > 0 {
pos -= 1;
tmp[pos] = b'0' + (mag % 10) as u8;
mag /= 10;
}
}
if negative {
pos -= 1;
tmp[pos] = b'-';
}
buf.extend_from_slice(&tmp[pos..]);
}
#[inline]
fn write_binary_f64(buf: &mut Vec<u8>, name: &str, value: f64) {
buf.extend_from_slice(name.as_bytes());
buf.extend_from_slice(&[b'=', b'=', ILP_V2_DOUBLE_TYPE]);
buf.extend_from_slice(&value.to_le_bytes());
}
/// Encodes one curated `bars_1m` row in QuestDB ILP v2 format into `buf`.
///
/// Emits:
/// - Table `bars_1m`
/// - Symbols `listing_id` (decimal `row.key`), `session` (`PRE`/`RTH`/`POST`), `source`
/// - Binary `f64` columns `open`, `high`, `low`, `close`, `volume` (`vwap` omitted / NULL)
/// - Timestamp column `known_at=<known_at_micros>t`
/// - Designated timestamp ` <row.ts>t\n`
///
/// Validates all doubles, `source`, and non-negative `row.ts` before appending any bytes so
/// `buf` is left untouched on error.
pub fn encode_bar_1m(
buf: &mut Vec<u8>,
row: &Bar1mRow<i32>,
known_at_micros: i64,
) -> Result<(), IlpEncodeError> {
if row.source.is_empty() {
return Err(IlpEncodeError::EmptySymbol { field: "source" });
}
validate_finite("open", row.open)?;
validate_finite("high", row.high)?;
validate_finite("low", row.low)?;
validate_finite("close", row.close)?;
validate_finite("volume", row.volume)?;
validate_non_negative_ts("ts", row.ts)?;
buf.extend_from_slice(TABLE_BARS_1M.as_bytes());
buf.extend_from_slice(b",listing_id=");
write_i64_decimal(buf, i64::from(row.key));
buf.extend_from_slice(b",session=");
buf.extend_from_slice(row.session.as_str().as_bytes());
buf.extend_from_slice(b",source=");
write_escaped_symbol(buf, row.source);
buf.push(b' ');
write_binary_f64(buf, "open", row.open);
buf.push(b',');
write_binary_f64(buf, "high", row.high);
buf.push(b',');
write_binary_f64(buf, "low", row.low);
buf.push(b',');
write_binary_f64(buf, "close", row.close);
buf.push(b',');
write_binary_f64(buf, "volume", row.volume);
buf.extend_from_slice(b",known_at=");
write_i64_decimal(buf, known_at_micros);
buf.extend_from_slice(b"t ");
write_i64_decimal(buf, row.ts);
buf.extend_from_slice(b"t\n");
Ok(())
}
/// Encodes one `fx_1m` row in QuestDB ILP v2 format into `buf`.
///
/// Emits:
/// - Table `fx_1m`
/// - Symbols `pair`, `source`
/// - Binary `f64` columns `open`, `high`, `low`, `close`
/// - Designated timestamp ` <row.ts>t\n`
///
/// Validates `pair`, `source`, all doubles, and non-negative `row.ts` before appending any bytes
/// so `buf` is left untouched on error.
pub fn encode_fx_1m(buf: &mut Vec<u8>, row: &Fx1mRow<'_>) -> Result<(), IlpEncodeError> {
if row.pair.is_empty() {
return Err(IlpEncodeError::EmptySymbol { field: "pair" });
}
if row.source.is_empty() {
return Err(IlpEncodeError::EmptySymbol { field: "source" });
}
validate_finite("open", row.open)?;
validate_finite("high", row.high)?;
validate_finite("low", row.low)?;
validate_finite("close", row.close)?;
validate_non_negative_ts("ts", row.ts)?;
buf.extend_from_slice(TABLE_FX_1M.as_bytes());
buf.extend_from_slice(b",pair=");
write_escaped_symbol(buf, row.pair);
buf.extend_from_slice(b",source=");
write_escaped_symbol(buf, row.source);
buf.push(b' ');
write_binary_f64(buf, "open", row.open);
buf.push(b',');
write_binary_f64(buf, "high", row.high);
buf.push(b',');
write_binary_f64(buf, "low", row.low);
buf.push(b',');
write_binary_f64(buf, "close", row.close);
buf.push(b' ');
write_i64_decimal(buf, row.ts);
buf.extend_from_slice(b"t\n");
Ok(())
}
struct ShardState<W> {
sink: W,
buf: Vec<u8>,
pending_rows: usize,
written_rows: usize,
}
/// Deterministic, sink-agnostic sharded QuestDB ILP v2 batch writer.
///
/// Buffers complete ILP lines per shard and flushes whole-line batches to injected [`Write`]
/// sinks when either `max_batch_rows` or `max_batch_bytes` is reached, or on [`Self::finish`].
pub struct IlpShardedWriter<W: Write + Send> {
shards: Vec<ShardState<W>>,
options: IlpWriterOptions,
scratch: Vec<u8>,
rows_written: usize,
bytes_written: usize,
flushes: usize,
poisoned_shard: Option<usize>,
}
impl<W: Write + Send> IlpShardedWriter<W> {
/// Creates a new sharded writer over `sinks` with the given batching `options`.
///
/// Returns an error if `sinks` is empty or either batch limit is zero.
pub fn new(sinks: Vec<W>, options: IlpWriterOptions) -> Result<Self, IlpWriterError> {
if sinks.is_empty() {
return Err(IlpWriterError::EmptySinks);
}
if options.max_batch_bytes == 0 {
return Err(IlpWriterError::ZeroMaxBatchBytes);
}
if options.max_batch_rows == 0 {
return Err(IlpWriterError::ZeroMaxBatchRows);
}
let initial_buf_cap = options.max_batch_bytes.min(DEFAULT_ILP_MAX_BATCH_BYTES);
let shards = sinks
.into_iter()
.map(|sink| ShardState {
sink,
buf: Vec::with_capacity(initial_buf_cap),
pending_rows: 0,
written_rows: 0,
})
.collect();
Ok(Self {
shards,
options,
scratch: Vec::with_capacity(256),
rows_written: 0,
bytes_written: 0,
flushes: 0,
poisoned_shard: None,
})
}
/// Returns the number of configured shards.
#[inline]
pub fn shard_count(&self) -> usize {
self.shards.len()
}
/// Encodes and buffers one `bars_1m` row on the shard determined by `row.key`.
pub fn write_bar_1m(
&mut self,
row: &Bar1mRow<i32>,
known_at_micros: i64,
) -> Result<(), IlpWriterError> {
if let Some(failed_shard) = self.poisoned_shard {
return Err(IlpWriterError::Poisoned { failed_shard });
}
self.scratch.clear();
encode_bar_1m(&mut self.scratch, row, known_at_micros)?;
let shard_idx = shard_for_listing_id(row.key, self.shards.len());
self.enqueue_scratch_row(shard_idx)
}
/// Encodes and buffers one `fx_1m` row on the shard determined by `row.pair`.
pub fn write_fx_1m(&mut self, row: &Fx1mRow<'_>) -> Result<(), IlpWriterError> {
if let Some(failed_shard) = self.poisoned_shard {
return Err(IlpWriterError::Poisoned { failed_shard });
}
self.scratch.clear();
encode_fx_1m(&mut self.scratch, row)?;
let shard_idx = shard_for_fx_pair(row.pair, self.shards.len());
self.enqueue_scratch_row(shard_idx)
}
/// Flushes all remaining buffered batches and underlying sinks, returning write statistics.
pub fn finish(mut self) -> Result<IlpWriteStats, IlpWriterError> {
if let Some(failed_shard) = self.poisoned_shard {
return Err(IlpWriterError::Poisoned { failed_shard });
}
for shard_idx in 0..self.shards.len() {
if !self.shards[shard_idx].buf.is_empty() {
self.flush_shard(shard_idx)?;
}
if let Err(source) = self.shards[shard_idx].sink.flush() {
self.poisoned_shard = Some(shard_idx);
return Err(IlpWriterError::Io {
shard: shard_idx,
source,
});
}
}
let per_shard_rows = self.shards.iter().map(|s| s.written_rows).collect();
Ok(IlpWriteStats {
rows: self.rows_written,
bytes: self.bytes_written,
flushes: self.flushes,
per_shard_rows,
})
}
fn enqueue_scratch_row(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> {
let row_len = self.scratch.len();
let needs_preflush = {
let shard = &self.shards[shard_idx];
!shard.buf.is_empty()
&& shard.buf.len().saturating_add(row_len) > self.options.max_batch_bytes
};
if needs_preflush {
self.flush_shard(shard_idx)?;
}
let needs_postflush = {
let shard = &mut self.shards[shard_idx];
shard.buf.extend_from_slice(&self.scratch);
shard.pending_rows += 1;
shard.pending_rows >= self.options.max_batch_rows
|| shard.buf.len() >= self.options.max_batch_bytes
};
if needs_postflush {
self.flush_shard(shard_idx)?;
}
Ok(())
}
fn flush_shard(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> {
let shard = &mut self.shards[shard_idx];
if shard.buf.is_empty() {
return Ok(());
}
if let Err(source) = shard.sink.write_all(&shard.buf) {
self.poisoned_shard = Some(shard_idx);
return Err(IlpWriterError::Io {
shard: shard_idx,
source,
});
}
let bytes = shard.buf.len();
let rows = shard.pending_rows;
shard.buf.clear();
shard.pending_rows = 0;
shard.written_rows += rows;
self.rows_written += rows;
self.bytes_written += bytes;
self.flushes += 1;
Ok(())
}
}
#[cfg(test)]
#[path = "ilp_tests.rs"]
mod tests;

View file

@ -0,0 +1,903 @@
use std::collections::HashMap;
use std::io::{self, Write};
use std::sync::{Arc, Mutex};
use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD};
use super::{
encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Fx1mRow,
IlpEncodeError, IlpShardedWriter, IlpWriterError, IlpWriterOptions, ILP_V2_DOUBLE_TYPE,
};
fn sample_bar(listing_id: i32, ts: i64) -> Bar1mRow<i32> {
Bar1mRow {
key: listing_id,
ts,
session_date: 20_100,
open: 123.45,
high: 125.75,
low: 122.125,
close: 124.5,
volume: 98_765.0,
session: IntradaySession::Rth,
source: BARS_1M_SOURCE_EOD,
}
}
fn sample_fx(pair: &'static str, ts: i64) -> Fx1mRow<'static> {
Fx1mRow {
pair,
ts,
open: 1.3625,
high: 1.3650,
low: 1.3610,
close: 1.3642,
source: "eod",
}
}
/// Minimal ILP v2 frame splitter that respects escaped symbols and fixed-width 8-byte binary
/// `DOUBLE` payloads (`==\x10<8 bytes>`), so embedded `0x0a` bytes inside binary doubles or
/// escaped `\n` in symbols never falsely split a row.
fn split_ilp_v2_rows(data: &[u8]) -> Vec<&[u8]> {
let mut rows = Vec::new();
let mut i = 0usize;
let len = data.len();
while i < len {
let start = i;
// 1. Tag set (table + symbols) ends at unescaped ASCII space.
while i < len {
match data[i] {
b'\\' => {
assert!(i + 1 < len, "dangling backslash in ILP tag set");
i += 2;
}
b' ' => {
i += 1;
break;
}
_ => i += 1,
}
}
assert!(i < len, "unexpected EOF after ILP tag set");
// 2. Field set ends at ASCII space; skip fixed 8-byte binary double payloads after `==\x10`.
while i < len {
if data[i] == b' ' {
i += 1;
break;
}
if data[i] == b'=' && i + 2 < len && data[i + 1] == b'=' && data[i + 2] == ILP_V2_DOUBLE_TYPE
{
assert!(
i + 3 + 8 <= len,
"truncated binary DOUBLE payload in ILP field set"
);
i += 3 + 8;
} else {
i += 1;
}
}
assert!(i < len, "unexpected EOF after ILP field set");
// 3. Designated timestamp runs to unescaped LF.
while i < len && data[i] != b'\n' {
i += 1;
}
assert!(i < len && data[i] == b'\n', "ILP row missing trailing LF");
i += 1;
rows.push(&data[start..i]);
}
rows
}
fn extract_tag_value<'a>(row: &'a [u8], tag_prefix: &[u8]) -> &'a [u8] {
let mut i = 0usize;
let tag_end = loop {
assert!(i < row.len(), "missing space after tag set");
match row[i] {
b'\\' => i += 2,
b' ' => break i,
_ => i += 1,
}
};
let tag_section = &row[..tag_end];
let pos = tag_section
.windows(tag_prefix.len())
.position(|w| w == tag_prefix)
.expect("expected tag prefix in row");
let val_start = pos + tag_prefix.len();
let mut j = val_start;
while j < tag_end {
match tag_section[j] {
b'\\' => j += 2,
b',' => break,
_ => j += 1,
}
}
&tag_section[val_start..j]
}
#[derive(Clone, Default)]
struct RecordingSink {
writes: Arc<Mutex<Vec<Vec<u8>>>>,
flush_calls: Arc<Mutex<usize>>,
fail_on_write_call: Option<usize>,
/// `(call_index, prefix_bytes)`: on `call_index`, accept only `prefix_bytes` and then fail
/// on the subsequent `write()` call inside `write_all()`.
partial_then_fail_on_write_call: Option<(usize, usize)>,
fail_on_flush: bool,
}
impl RecordingSink {
fn new() -> Self {
Self::default()
}
fn failing_on_write(call_index: usize) -> Self {
Self {
fail_on_write_call: Some(call_index),
..Self::default()
}
}
fn failing_after_partial_write(call_index: usize, prefix_bytes: usize) -> Self {
Self {
partial_then_fail_on_write_call: Some((call_index, prefix_bytes)),
..Self::default()
}
}
fn failing_on_flush() -> Self {
Self {
fail_on_flush: true,
..Self::default()
}
}
fn captured_writes(&self) -> Vec<Vec<u8>> {
self.writes.lock().unwrap().clone()
}
fn captured_bytes(&self) -> Vec<u8> {
self.writes
.lock()
.unwrap()
.iter()
.flat_map(|w| w.iter().copied())
.collect()
}
fn captured_flushes(&self) -> usize {
*self.flush_calls.lock().unwrap()
}
}
impl Write for RecordingSink {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut writes = self.writes.lock().unwrap();
let call_idx = writes.len();
if self.fail_on_write_call == Some(call_idx) {
return Err(io::Error::new(
io::ErrorKind::BrokenPipe,
format!("injected write failure on call {call_idx}"),
));
}
if let Some((partial_call, prefix_bytes)) = self.partial_then_fail_on_write_call {
if call_idx == partial_call {
let n = prefix_bytes.min(buf.len());
writes.push(buf[..n].to_vec());
return Ok(n);
}
if call_idx > partial_call {
return Err(io::Error::new(
io::ErrorKind::BrokenPipe,
format!("injected write failure after partial write on call {call_idx}"),
));
}
}
writes.push(buf.to_vec());
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
let mut flushes = self.flush_calls.lock().unwrap();
*flushes += 1;
if self.fail_on_flush {
return Err(io::Error::new(
io::ErrorKind::ConnectionReset,
"injected flush failure",
));
}
Ok(())
}
}
#[test]
fn golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract() {
let row = Bar1mRow {
key: 42,
ts: 1_736_951_400_000_000,
session_date: 20_103,
open: 150.25,
high: 151.75,
low: 149.5,
close: 151.125,
volume: 12_345.0,
session: IntradaySession::Rth,
source: BARS_1M_SOURCE_EOD,
};
let known_at_micros = 1_736_951_460_123_456_i64;
let mut actual = Vec::new();
encode_bar_1m(&mut actual, &row, known_at_micros).expect("encode bar_1m");
let mut expected = Vec::new();
expected.extend_from_slice(b"bars_1m,listing_id=42,session=RTH,source=eod_unadj ");
expected.extend_from_slice(b"open==\x10");
expected.extend_from_slice(&150.25_f64.to_le_bytes());
expected.extend_from_slice(b",high==\x10");
expected.extend_from_slice(&151.75_f64.to_le_bytes());
expected.extend_from_slice(b",low==\x10");
expected.extend_from_slice(&149.5_f64.to_le_bytes());
expected.extend_from_slice(b",close==\x10");
expected.extend_from_slice(&151.125_f64.to_le_bytes());
expected.extend_from_slice(b",volume==\x10");
expected.extend_from_slice(&12_345.0_f64.to_le_bytes());
expected.extend_from_slice(b",known_at=1736951460123456t 1736951400000000t\n");
assert_eq!(actual, expected);
assert!(
!actual.windows(4).any(|w| w == b"vwap"),
"vwap must be omitted for bars_1m"
);
// Round-trip every binary DOUBLE payload bit-exactly via f64::from_le_bytes.
for (prefix, expected_val) in [
(&b"open==\x10"[..], row.open),
(&b",high==\x10"[..], row.high),
(&b",low==\x10"[..], row.low),
(&b",close==\x10"[..], row.close),
(&b",volume==\x10"[..], row.volume),
] {
let pos = actual
.windows(prefix.len())
.position(|w| w == prefix)
.expect("binary double column present");
let raw: [u8; 8] = actual[pos + prefix.len()..pos + prefix.len() + 8]
.try_into()
.unwrap();
let decoded = f64::from_le_bytes(raw);
assert_eq!(decoded.to_bits(), expected_val.to_bits());
}
// Verify PRE and POST session tags as well.
let mut pre_buf = Vec::new();
let mut pre_row = row.clone();
pre_row.session = IntradaySession::Pre;
encode_bar_1m(&mut pre_buf, &pre_row, known_at_micros).unwrap();
assert!(pre_buf.starts_with(b"bars_1m,listing_id=42,session=PRE,source=eod_unadj "));
let mut post_buf = Vec::new();
let mut post_row = row;
post_row.session = IntradaySession::Post;
encode_bar_1m(&mut post_buf, &post_row, known_at_micros).unwrap();
assert!(post_buf.starts_with(b"bars_1m,listing_id=42,session=POST,source=eod_unadj "));
}
#[test]
fn golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract() {
let row = Fx1mRow {
pair: "USD.CAD",
ts: 1_736_951_400_000_000,
open: 1.3625,
high: 1.365,
low: 1.36125,
close: 1.364375,
source: "eod",
};
let mut actual = Vec::new();
encode_fx_1m(&mut actual, &row).expect("encode fx_1m");
let mut expected = Vec::new();
expected.extend_from_slice(b"fx_1m,pair=USD.CAD,source=eod ");
expected.extend_from_slice(b"open==\x10");
expected.extend_from_slice(&1.3625_f64.to_le_bytes());
expected.extend_from_slice(b",high==\x10");
expected.extend_from_slice(&1.365_f64.to_le_bytes());
expected.extend_from_slice(b",low==\x10");
expected.extend_from_slice(&1.36125_f64.to_le_bytes());
expected.extend_from_slice(b",close==\x10");
expected.extend_from_slice(&1.364375_f64.to_le_bytes());
expected.extend_from_slice(b" 1736951400000000t\n");
assert_eq!(actual, expected);
assert!(!actual.windows(8).any(|w| w == b"known_at"));
assert!(!actual.windows(6).any(|w| w == b"volume"));
for (prefix, expected_val) in [
(&b"open==\x10"[..], row.open),
(&b",high==\x10"[..], row.high),
(&b",low==\x10"[..], row.low),
(&b",close==\x10"[..], row.close),
] {
let pos = actual
.windows(prefix.len())
.position(|w| w == prefix)
.expect("binary double column present");
let raw: [u8; 8] = actual[pos + prefix.len()..pos + prefix.len() + 8]
.try_into()
.unwrap();
assert_eq!(f64::from_le_bytes(raw).to_bits(), expected_val.to_bits());
}
}
#[test]
fn symbol_escaping_and_non_finite_or_negative_ts_atomic_rejection() {
// Escaping: space, comma, '=', backslash, LF, CR, and UTF-8.
let raw_sym = "a b,c=d\\e\nf\rg caf\u{00e9}";
let expected_escaped = b"a\\ b\\,c\\=d\\\\e\\\nf\\\rg\\ caf\xc3\xa9";
let mut bar = sample_bar(7, 0);
bar.source = raw_sym;
let mut bar_buf = Vec::new();
encode_bar_1m(&mut bar_buf, &bar, -500).expect("encode escaped bar_1m");
let mut expected_prefix = b"bars_1m,listing_id=7,session=RTH,source=".to_vec();
expected_prefix.extend_from_slice(expected_escaped);
expected_prefix.push(b' ');
assert!(bar_buf.starts_with(&expected_prefix));
assert!(bar_buf.ends_with(b",known_at=-500t 0t\n"));
let fx = Fx1mRow {
pair: raw_sym,
source: "src=1,2 3\\4\n\r",
..sample_fx("USD.CAD", 123)
};
let mut fx_buf = Vec::new();
encode_fx_1m(&mut fx_buf, &fx).expect("encode escaped fx_1m");
let mut expected_fx_prefix = b"fx_1m,pair=".to_vec();
expected_fx_prefix.extend_from_slice(expected_escaped);
expected_fx_prefix.extend_from_slice(b",source=src\\=1\\,2\\ 3\\\\4\\\n\\\r ");
assert!(fx_buf.starts_with(&expected_fx_prefix));
assert!(fx_buf.ends_with(b" 123t\n"));
// Non-finite doubles in a late field must fail atomically and preserve existing buffer bytes.
let sentinel = b"EXISTING_PREFIX_BYTES".to_vec();
for bad_val in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let mut buf = sentinel.clone();
let mut bad_bar = sample_bar(1, 100);
bad_bar.volume = bad_val;
let err = encode_bar_1m(&mut buf, &bad_bar, 200).unwrap_err();
assert!(matches!(
err,
IlpEncodeError::NonFiniteDouble {
field: "volume",
..
}
));
assert_eq!(buf, sentinel, "buffer must be untouched on bars_1m error");
let mut fx_buf = sentinel.clone();
let mut bad_fx = sample_fx("USD.CAD", 100);
bad_fx.close = bad_val;
let err = encode_fx_1m(&mut fx_buf, &bad_fx).unwrap_err();
assert!(matches!(
err,
IlpEncodeError::NonFiniteDouble { field: "close", .. }
));
assert_eq!(fx_buf, sentinel, "buffer must be untouched on fx_1m error");
}
// Negative designated timestamp fails atomically.
let mut buf = sentinel.clone();
let bad_ts_bar = sample_bar(1, -1);
assert_eq!(
encode_bar_1m(&mut buf, &bad_ts_bar, 500),
Err(IlpEncodeError::NegativeTimestamp {
field: "ts",
value: -1
})
);
assert_eq!(buf, sentinel);
let mut fx_buf = sentinel.clone();
let bad_ts_fx = sample_fx("USD.CAD", -42);
assert_eq!(
encode_fx_1m(&mut fx_buf, &bad_ts_fx),
Err(IlpEncodeError::NegativeTimestamp {
field: "ts",
value: -42
})
);
assert_eq!(fx_buf, sentinel);
// Empty symbol fails atomically.
let mut buf = sentinel.clone();
let mut empty_src = sample_bar(1, 100);
empty_src.source = "";
assert_eq!(
encode_bar_1m(&mut buf, &empty_src, 100),
Err(IlpEncodeError::EmptySymbol { field: "source" })
);
assert_eq!(buf, sentinel);
let mut fx_buf = sentinel.clone();
let empty_pair = sample_fx("", 100);
assert_eq!(
encode_fx_1m(&mut fx_buf, &empty_pair),
Err(IlpEncodeError::EmptySymbol { field: "pair" })
);
assert_eq!(fx_buf, sentinel);
}
#[test]
fn sharded_writer_routes_deterministically_preserves_per_key_order_and_handles_embedded_lf() {
// Build a finite double whose IEEE-754 little-endian representation contains 0x0a (LF).
let double_with_lf = f64::from_le_bytes([0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x24, 0x40]);
assert!(double_with_lf.is_finite());
let num_shards = 4usize;
let num_listings = 64i32;
let rows_per_listing = 20usize; // 64 * 20 = 1,280 interleaved rows >= 1,000
let mut input_rows: Vec<(Bar1mRow<i32>, i64)> =
Vec::with_capacity(num_listings as usize * rows_per_listing + 2);
for step in 0..rows_per_listing {
for listing_id in 1..=num_listings {
let ts = 1_700_000_000_000_000 + (step as i64) * 60_000_000 + i64::from(listing_id);
let known_at = ts + 60_000_000;
let mut row = sample_bar(listing_id, ts);
row.open = double_with_lf;
row.close = 100.0 + (step as f64) * 0.25 + f64::from(listing_id) * 0.01;
row.volume = (step as f64 + 1.0) * 100.0;
if step == 5 && listing_id == 10 {
row.source = "eod\nwith_lf";
}
input_rows.push((row, known_at));
}
}
// Append a second version of an existing (ts, listing_id) to verify DEDUP UPSERT ordering.
let (mut revision, rev_known_at) = input_rows[0].clone();
revision.close += 0.5;
input_rows.push((revision, rev_known_at + 120_000_000));
// Expected per-listing byte sequences in input order.
let mut expected_by_listing: HashMap<i32, Vec<Vec<u8>>> = HashMap::new();
for (row, known_at) in &input_rows {
let mut line = Vec::new();
encode_bar_1m(&mut line, row, *known_at).unwrap();
expected_by_listing.entry(row.key).or_default().push(line);
}
let opts = IlpWriterOptions {
max_batch_bytes: 2048,
max_batch_rows: 17,
};
let run_once = || {
let mut sinks: Vec<Vec<u8>> = (0..num_shards).map(|_| Vec::new()).collect();
let stats = {
let sink_refs: Vec<&mut Vec<u8>> = sinks.iter_mut().collect();
let mut writer = IlpShardedWriter::new(sink_refs, opts).unwrap();
for (row, known_at) in &input_rows {
writer.write_bar_1m(row, *known_at).unwrap();
}
writer.finish().unwrap()
};
(sinks, stats)
};
let (sinks_a, stats_a) = run_once();
let (sinks_b, stats_b) = run_once();
// Byte-for-byte determinism across runs.
assert_eq!(sinks_a, sinks_b);
assert_eq!(stats_a, stats_b);
// Conservation invariants.
assert_eq!(stats_a.rows, input_rows.len());
assert_eq!(
stats_a.per_shard_rows.iter().sum::<usize>(),
stats_a.rows
);
let total_sink_bytes: usize = sinks_a.iter().map(Vec::len).sum();
assert_eq!(stats_a.bytes, total_sink_bytes);
// Parse every shard with the binary-aware ILP v2 splitter and verify routing + order.
let mut seen_shard_for_listing: HashMap<i32, usize> = HashMap::new();
let mut observed_by_listing: HashMap<i32, Vec<Vec<u8>>> = HashMap::new();
let mut total_parsed_rows = 0usize;
for (shard_idx, shard_bytes) in sinks_a.iter().enumerate() {
let parsed = split_ilp_v2_rows(shard_bytes);
assert_eq!(parsed.len(), stats_a.per_shard_rows[shard_idx]);
total_parsed_rows += parsed.len();
for row_bytes in parsed {
let id_bytes = extract_tag_value(row_bytes, b",listing_id=");
let listing_id: i32 = std::str::from_utf8(id_bytes).unwrap().parse().unwrap();
assert_eq!(
shard_idx,
shard_for_listing_id(listing_id, num_shards),
"listing_id {listing_id} routed to unexpected shard"
);
if let Some(&prev_shard) = seen_shard_for_listing.get(&listing_id) {
assert_eq!(prev_shard, shard_idx);
} else {
seen_shard_for_listing.insert(listing_id, shard_idx);
}
observed_by_listing
.entry(listing_id)
.or_default()
.push(row_bytes.to_vec());
}
}
assert_eq!(total_parsed_rows, input_rows.len());
assert_eq!(seen_shard_for_listing.len(), num_listings as usize);
assert_eq!(observed_by_listing, expected_by_listing);
// Repeated FX pairs across batches route by `pair` and preserve order.
let pairs = ["USD.CAD", "EUR.USD", "GBP.USD", "USD.JPY", "AUD.USD", "USD.CHF"];
let mut fx_sinks: Vec<Vec<u8>> = (0..num_shards).map(|_| Vec::new()).collect();
let mut expected_by_pair: HashMap<&str, Vec<Vec<u8>>> = HashMap::new();
let fx_stats = {
let refs: Vec<&mut Vec<u8>> = fx_sinks.iter_mut().collect();
let mut writer = IlpShardedWriter::new(
refs,
IlpWriterOptions {
max_batch_bytes: 512,
max_batch_rows: 3,
},
)
.unwrap();
for step in 0..10 {
for &pair in &pairs {
let mut row = sample_fx(pair, 1_700_000_000_000_000 + step * 60_000_000);
row.close += (step as f64) * 0.0001;
let mut line = Vec::new();
encode_fx_1m(&mut line, &row).unwrap();
expected_by_pair.entry(pair).or_default().push(line);
writer.write_fx_1m(&row).unwrap();
}
}
writer.finish().unwrap()
};
assert_eq!(fx_stats.rows, pairs.len() * 10);
assert_eq!(fx_stats.per_shard_rows.iter().sum::<usize>(), fx_stats.rows);
assert_eq!(fx_stats.bytes, fx_sinks.iter().map(Vec::len).sum::<usize>());
let mut observed_by_pair: HashMap<String, Vec<Vec<u8>>> = HashMap::new();
for (shard_idx, shard_bytes) in fx_sinks.iter().enumerate() {
for row_bytes in split_ilp_v2_rows(shard_bytes) {
let pair_str =
std::str::from_utf8(extract_tag_value(row_bytes, b",pair=")).unwrap();
assert_eq!(shard_idx, shard_for_fx_pair(pair_str, num_shards));
observed_by_pair
.entry(pair_str.to_string())
.or_default()
.push(row_bytes.to_vec());
}
}
for (pair, expected) in expected_by_pair {
assert_eq!(observed_by_pair.get(pair).unwrap(), &expected);
}
}
#[test]
fn batching_limits_oversized_lines_remainder_and_whole_line_boundaries() {
let row = sample_bar(42, 1_736_951_400_000_000);
let known_at = 1_736_951_460_000_000;
let mut one_line = Vec::new();
encode_bar_1m(&mut one_line, &row, known_at).unwrap();
let row_len = one_line.len();
// 1. Exact row limit (max_batch_rows = 3) + 1 remainder row.
let sink = RecordingSink::new();
let mut writer = IlpShardedWriter::new(
vec![sink.clone()],
IlpWriterOptions {
max_batch_bytes: 100_000,
max_batch_rows: 3,
},
)
.unwrap();
for _ in 0..7 {
writer.write_bar_1m(&row, known_at).unwrap();
}
let stats = writer.finish().unwrap();
let writes = sink.captured_writes();
assert_eq!(writes.len(), 3);
assert_eq!(stats.flushes, 3);
assert_eq!(stats.rows, 7);
assert_eq!(stats.bytes, 7 * row_len);
assert_eq!(sink.captured_flushes(), 1);
assert_eq!(split_ilp_v2_rows(&writes[0]).len(), 3);
assert_eq!(split_ilp_v2_rows(&writes[1]).len(), 3);
assert_eq!(split_ilp_v2_rows(&writes[2]).len(), 1);
assert!(writes.iter().all(|w| w.ends_with(b"\n")));
// 2. Exact byte limit (2 * row_len): flushes after every 2 rows.
let sink = RecordingSink::new();
let mut writer = IlpShardedWriter::new(
vec![sink.clone()],
IlpWriterOptions {
max_batch_bytes: 2 * row_len,
max_batch_rows: 100,
},
)
.unwrap();
for _ in 0..5 {
writer.write_bar_1m(&row, known_at).unwrap();
}
let stats = writer.finish().unwrap();
let writes = sink.captured_writes();
assert_eq!(writes.len(), 3);
assert_eq!(stats.flushes, 3);
assert_eq!(split_ilp_v2_rows(&writes[0]).len(), 2);
assert_eq!(split_ilp_v2_rows(&writes[1]).len(), 2);
assert_eq!(split_ilp_v2_rows(&writes[2]).len(), 1);
// 3. Next line would exceed remaining capacity (2 * row_len - 1): flushes before appending.
let sink = RecordingSink::new();
let mut writer = IlpShardedWriter::new(
vec![sink.clone()],
IlpWriterOptions {
max_batch_bytes: 2 * row_len - 1,
max_batch_rows: 100,
},
)
.unwrap();
for _ in 0..3 {
writer.write_bar_1m(&row, known_at).unwrap();
}
let stats = writer.finish().unwrap();
let writes = sink.captured_writes();
assert_eq!(writes.len(), 3);
assert_eq!(stats.flushes, 3);
for w in &writes {
assert_eq!(w.len(), row_len);
assert_eq!(split_ilp_v2_rows(w).len(), 1);
}
// 4. Individually oversized line (max_batch_bytes = 16 < row_len) sent alone, never split.
let sink = RecordingSink::new();
let mut writer = IlpShardedWriter::new(
vec![sink.clone()],
IlpWriterOptions {
max_batch_bytes: 16,
max_batch_rows: 100,
},
)
.unwrap();
writer.write_bar_1m(&row, known_at).unwrap();
writer.write_bar_1m(&row, known_at).unwrap();
let stats = writer.finish().unwrap();
let writes = sink.captured_writes();
assert_eq!(writes.len(), 2);
assert_eq!(stats.flushes, 2);
assert_eq!(writes[0], one_line);
assert_eq!(writes[1], one_line);
}
#[test]
fn writer_validates_options_handles_zero_rows_and_poisons_on_io_error() {
assert!(matches!(
IlpShardedWriter::<Vec<u8>>::new(Vec::new(), IlpWriterOptions::default()),
Err(IlpWriterError::EmptySinks)
));
assert!(matches!(
IlpShardedWriter::new(
vec![Vec::new()],
IlpWriterOptions {
max_batch_bytes: 0,
max_batch_rows: 10,
}
),
Err(IlpWriterError::ZeroMaxBatchBytes)
));
assert!(matches!(
IlpShardedWriter::new(
vec![Vec::new()],
IlpWriterOptions {
max_batch_bytes: 1024,
max_batch_rows: 0,
}
),
Err(IlpWriterError::ZeroMaxBatchRows)
));
// Zero rows written -> clean stats and sink flush still called.
let s0 = RecordingSink::new();
let s1 = RecordingSink::new();
let writer = IlpShardedWriter::new(vec![s0.clone(), s1.clone()], IlpWriterOptions::default())
.unwrap();
let stats = writer.finish().unwrap();
assert_eq!(stats.rows, 0);
assert_eq!(stats.bytes, 0);
assert_eq!(stats.flushes, 0);
assert_eq!(stats.per_shard_rows, vec![0, 0]);
assert_eq!(s0.captured_flushes(), 1);
assert_eq!(s1.captured_flushes(), 1);
// Find a listing_id that routes to shard 2 out of 4.
let target_listing = (1..1000)
.find(|&id| shard_for_listing_id(id, 4) == 2)
.expect("listing for shard 2");
// Failing write_all on shard 2 after 1 successful batch: returns Io { shard: 2 } and poisons.
let failing_sink = RecordingSink::failing_on_write(1);
let mut writer = IlpShardedWriter::new(
vec![
RecordingSink::new(),
RecordingSink::new(),
failing_sink.clone(),
RecordingSink::new(),
],
IlpWriterOptions {
max_batch_bytes: 100_000,
max_batch_rows: 1,
},
)
.unwrap();
let row = sample_bar(target_listing, 1_700_000_000_000_000);
writer.write_bar_1m(&row, 1_700_000_060_000_000).unwrap();
let err = writer
.write_bar_1m(&row, 1_700_000_120_000_000)
.unwrap_err();
assert!(matches!(err, IlpWriterError::Io { shard: 2, .. }));
// Subsequent writes and finish fail with Poisoned { failed_shard: 2 }.
let err2 = writer
.write_bar_1m(&row, 1_700_000_180_000_000)
.unwrap_err();
assert!(matches!(err2, IlpWriterError::Poisoned { failed_shard: 2 }));
let err3 = writer.write_fx_1m(&sample_fx("USD.CAD", 100)).unwrap_err();
assert!(matches!(err3, IlpWriterError::Poisoned { failed_shard: 2 }));
let err4 = writer.finish().unwrap_err();
assert!(matches!(err4, IlpWriterError::Poisoned { failed_shard: 2 }));
assert_eq!(failing_sink.captured_writes().len(), 1);
// Failing flush() during finish() reports shard index.
let mut writer = IlpShardedWriter::new(
vec![RecordingSink::new(), RecordingSink::failing_on_flush()],
IlpWriterOptions::default(),
)
.unwrap();
writer.write_bar_1m(&row, 1_700_000_060_000_000).unwrap();
let flush_err = writer.finish().unwrap_err();
assert!(matches!(flush_err, IlpWriterError::Io { shard: 1, .. }));
// Encode error does not poison the writer.
let mut sinks = [Vec::new(), Vec::new()];
let stats = {
let refs: Vec<&mut Vec<u8>> = sinks.iter_mut().collect();
let mut writer = IlpShardedWriter::new(refs, IlpWriterOptions::default()).unwrap();
let mut bad = sample_bar(42, 100);
bad.close = f64::NAN;
assert!(matches!(
writer.write_bar_1m(&bad, 200),
Err(IlpWriterError::Encode(IlpEncodeError::NonFiniteDouble {
field: "close",
..
}))
));
writer
.write_bar_1m(&sample_bar(42, 100), 200)
.expect("writer still healthy after encode error");
writer.finish().unwrap()
};
assert_eq!(stats.rows, 1);
// Sanity check FNV-1a 64-bit known test vector ("foobar" -> 0x85944171f73967e8).
assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8);
}
#[test]
fn partial_write_failure_poisons_writer_and_freezes_sink_bytes() {
let target_listing = (1..1000)
.find(|&id| shard_for_listing_id(id, 4) == 2)
.expect("listing for shard 2");
let other_listing = (1..1000)
.find(|&id| shard_for_listing_id(id, 4) == 0)
.expect("listing for shard 0");
let row1 = sample_bar(target_listing, 1_700_000_000_000_000);
let row2 = sample_bar(target_listing, 1_700_000_060_000_000);
let other_row = sample_bar(other_listing, 1_700_000_000_000_000);
let known_at = 1_700_000_120_000_000;
let mut expected_row1 = Vec::new();
encode_bar_1m(&mut expected_row1, &row1, known_at).unwrap();
let mut expected_row2 = Vec::new();
encode_bar_1m(&mut expected_row2, &row2, known_at).unwrap();
let partial_prefix_len = 32;
assert!(partial_prefix_len < expected_row2.len());
let healthy_sink = RecordingSink::new();
let failing_sink = RecordingSink::failing_after_partial_write(1, partial_prefix_len);
let mut writer = IlpShardedWriter::new(
vec![
healthy_sink.clone(),
RecordingSink::new(),
failing_sink.clone(),
RecordingSink::new(),
],
IlpWriterOptions {
max_batch_bytes: 100_000,
max_batch_rows: 1,
},
)
.unwrap();
// First batch on shard 2 succeeds completely.
writer.write_bar_1m(&row1, known_at).unwrap();
// Second batch on shard 2 writes a partial prefix, then hits BrokenPipe.
let err = writer.write_bar_1m(&row2, known_at).unwrap_err();
assert!(matches!(err, IlpWriterError::Io { shard: 2, .. }));
let mut expected_captured = expected_row1.clone();
expected_captured.extend_from_slice(&expected_row2[..partial_prefix_len]);
assert_eq!(failing_sink.captured_bytes(), expected_captured);
// Subsequent writes (both on the failed shard and on another shard) and finish() are rejected,
// leaving all sink bytes frozen without replaying or appending anything.
assert!(matches!(
writer.write_bar_1m(&row2, known_at),
Err(IlpWriterError::Poisoned { failed_shard: 2 })
));
assert!(matches!(
writer.write_bar_1m(&other_row, known_at),
Err(IlpWriterError::Poisoned { failed_shard: 2 })
));
assert!(matches!(
writer.write_fx_1m(&sample_fx("USD.CAD", 100)),
Err(IlpWriterError::Poisoned { failed_shard: 2 })
));
assert!(matches!(
writer.finish(),
Err(IlpWriterError::Poisoned { failed_shard: 2 })
));
assert_eq!(failing_sink.captured_bytes(), expected_captured);
assert!(healthy_sink.captured_bytes().is_empty());
}
#[test]
fn golden_bytes_literal_ieee754_little_endian_without_to_le_bytes() {
let row = Bar1mRow {
key: 7,
ts: 1_700_000_000_000_000,
session_date: 20_000,
open: 1.0,
high: 2.0,
low: 0.5,
close: 1.5,
volume: 0.0,
session: IntradaySession::Rth,
source: BARS_1M_SOURCE_EOD,
};
let mut actual = Vec::new();
encode_bar_1m(&mut actual, &row, 1_700_000_060_000_000).unwrap();
// Hand-written little-endian IEEE-754 bytes (no f64::to_le_bytes):
// 1.0 -> 00 00 00 00 00 00 f0 3f
// 2.0 -> 00 00 00 00 00 00 00 40
// 0.5 -> 00 00 00 00 00 00 e0 3f
// 1.5 -> 00 00 00 00 00 00 f8 3f
// 0.0 -> 00 00 00 00 00 00 00 00
let mut expected: Vec<u8> = Vec::new();
expected.extend_from_slice(b"bars_1m,listing_id=7,session=RTH,source=eod_unadj ");
expected.extend_from_slice(b"open==\x10\x00\x00\x00\x00\x00\x00\xf0\x3f");
expected.extend_from_slice(b",high==\x10\x00\x00\x00\x00\x00\x00\x00\x40");
expected.extend_from_slice(b",low==\x10\x00\x00\x00\x00\x00\x00\xe0\x3f");
expected.extend_from_slice(b",close==\x10\x00\x00\x00\x00\x00\x00\xf8\x3f");
expected.extend_from_slice(b",volume==\x10\x00\x00\x00\x00\x00\x00\x00\x00");
expected.extend_from_slice(b",known_at=1700000060000000t 1700000000000000t\n");
assert_eq!(actual, expected);
}

View file

@ -5,6 +5,7 @@ pub mod bars;
pub mod bars_1m;
pub mod bench;
pub mod bson_ceo_shorts;
pub mod bson_eod_intraday;
pub mod bson_eod_prices;
pub mod bson_qm_actions;
pub mod bson_qm_events;
@ -16,6 +17,7 @@ pub mod corporate_actions;
pub mod events;
pub mod fundamentals;
pub mod fx;
pub mod ilp;
pub mod mongo_safety;
pub mod mongo_stream;
pub mod parquet_adj;
@ -25,6 +27,7 @@ pub mod parquet_events;
pub mod parquet_fx;
mod parquet_publish;
pub mod parquet_shorts;
pub mod posts;
pub mod provider_mapping;
pub mod session_close;
pub mod shorts;
@ -49,6 +52,10 @@ pub use bson_ceo_shorts::{
BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD,
DEFAULT_REPORT_DATE_FIELD,
};
pub use bson_eod_intraday::{
decode_eod_intraday_buffer, decode_eod_intraday_bytes, decode_eod_intraday_doc,
BsonEodIntradayDecodeStats, BsonEodIntradayError, RawEodIntradayBar,
};
pub use bson_eod_prices::{
decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs,
BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar,
@ -72,8 +79,8 @@ pub use bson_qm_prices::{
BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME,
};
pub use bson_stream::{
decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_price_chunks,
decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream,
decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_intraday_chunks,
decode_eod_intraday_stream, decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream,
decode_qm_earnings_chunks, decode_qm_earnings_stream, decode_qm_filings_chunks,
decode_qm_filings_stream, decode_qm_price_chunks, decode_qm_price_stream,
decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks,
@ -116,6 +123,12 @@ pub use fx::{
build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource,
FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD,
};
pub use ilp::{
encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Fx1mRow,
IlpEncodeError, IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions,
DEFAULT_ILP_MAX_BATCH_BYTES, DEFAULT_ILP_MAX_BATCH_ROWS, FNV1A_64_OFFSET_BASIS,
FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M,
};
pub use mongo_safety::{
assert_read_only_mongo_uri, is_qa_mongo_target, parse_mongo_target, LocalHosts,
MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy,
@ -155,6 +168,9 @@ pub use parquet_shorts::{
shorts_parquet_schema, write_shorts_dataset, ParquetShortsError, ShortsParquetRow,
ShortsWriteOptions, ShortsWriteStats,
};
pub use posts::{
build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO,
};
pub use provider_mapping::{
MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow,
ProviderMappingTable,
@ -268,5 +284,7 @@ pub use run_mongo::{
CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError,
};
#[cfg(test)]
mod posts_tests;
#[cfg(test)]
mod tsv_fixture_tests;

View file

@ -11,7 +11,8 @@ use curate_etl::bench::{
run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark,
run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark,
run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark,
run_fundamentals_benchmark, run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark,
run_fundamentals_benchmark, run_fx_benchmark, run_ilp_bars_1m_benchmark,
run_mongo_stream_benchmark, run_parquet_adj_benchmark,
run_parquet_bars_benchmark,
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
@ -378,6 +379,33 @@ fn main() -> ExitCode {
);
ExitCode::SUCCESS
}
Ok(CliAction::BenchIlpBars1m(rows)) => {
let report = match run_ilp_bars_1m_benchmark(rows) {
Ok(report) => report,
Err(err) => {
eprintln!("error: ilp bars_1m benchmark failed: {err}");
return ExitCode::FAILURE;
}
};
println!("curate-etl bench-ilp-bars-1m");
println!(
" input: rows={} keys={} shards={}",
report.rows, report.key_count, report.shards
);
println!(
" output: rows_encoded={} bytes={} flushes={} per_shard_rows={:?}",
report.rows_encoded, report.bytes, report.flushes, report.per_shard_rows
);
println!(
" perf: elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row size={:.2} bytes/row write={:.2} MB/s",
report.elapsed_ms,
report.rows_per_sec,
report.ns_per_row,
report.bytes_per_row,
report.mb_per_sec
);
ExitCode::SUCCESS
}
Ok(CliAction::BenchFx(rows)) => {
let report = run_fx_benchmark(rows);
println!("curate-etl bench-fx");

View file

@ -0,0 +1,248 @@
//! Pure, in-memory `posts` builder for `ceoPosts` (`bot == "1"` newswire vs. retail split,
//! `edited` text point-in-time `known_at` guard, and deterministic global `spielId` deduplication).
//!
//! Aligned with `design/DATA-CONTRACTS.md` §1 (`ceoSymbols`, `ceoPosts`, `ceoShorts` row):
//! - Separates `bot == "1"` newswire posts (e.g. `@thenewswire`) from retail posts so wire
//! releases are never pooled with crowd chat.
//! - Computes text availability as `known_at = COALESCE(edited, timestamp)` in UTC microseconds,
//! clamped so `known_at >= posted_at` always holds.
//! - **Point-in-time rule:** any text-based feature or sentiment model MUST join on `known_at`,
//! never `posted_at`. In `ceoPosts`, an edit overwrites `spiel` in place without version
//! history, so the builder retains one supplied version per `spiel_id` and cannot recover
//! earlier pre-edit text.
use std::error::Error;
use std::fmt;
/// Canonical provenance label written to [`PostRow::source`].
pub const POSTS_SOURCE_CEO: &str = "ceo_posts";
/// Typed errors returned by [`build_posts`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PostsError {
/// Converting a millisecond timestamp (`timestamp_ms` or `edited_ms`) to UTC microseconds
/// overflowed `i64`.
TimestampOverflow {
spiel_id: String,
field: &'static str,
timestamp_ms: i64,
},
}
impl fmt::Display for PostsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TimestampOverflow {
spiel_id,
field,
timestamp_ms,
} => write!(
f,
"timestamp overflow converting {field}={timestamp_ms} ms to UTC microseconds for spiel_id '{spiel_id}'"
),
}
}
}
impl Error for PostsError {}
/// A single already-decoded `ceoPosts` input row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CeoPost<K = String> {
/// Channel / `ceoId` (or resolved listing key).
pub key: K,
/// Provider post identifier (`spielId`, MongoDB upsert key).
pub spiel_id: String,
/// Provider post creation time in epoch milliseconds (`timestamp`).
pub timestamp_ms: i64,
/// Optional provider last-edit time in epoch milliseconds (`edited`).
pub edited_ms: Option<i64>,
/// Raw provider bot flag (`bot`; only `"1"` after trim classifies as newswire).
pub bot: Option<String>,
/// Optional provider author identifier (`userId`).
pub user_id: Option<String>,
/// Post text (`spiel`).
pub text: String,
}
/// A single curated `ceoPosts` output row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PostRow<K = String> {
pub key: K,
pub spiel_id: String,
/// Post creation timestamp in UTC microseconds (`timestamp_ms * 1_000`).
pub posted_at: i64,
/// Point-in-time text availability timestamp in UTC microseconds (`max(posted_at, edited_at)`).
/// Downstream text features MUST join on `known_at`, never `posted_at`.
pub known_at: i64,
pub is_bot: bool,
pub is_edited: bool,
pub user_id: Option<String>,
pub text: String,
pub source: &'static str,
}
/// Summary accounting counters produced alongside [`PostsBuild::newswire`] and
/// [`PostsBuild::retail`].
///
/// Conservation invariant:
/// `input == newswire + retail + duplicates_dropped + rejected_invalid`
///
/// Accounting note: `edited` and `edited_before_posted` are counted on valid input rows before
/// `spiel_id` deduplication (so they include valid duplicates and exclude `rejected_invalid`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PostsStats {
pub input: usize,
pub newswire: usize,
pub retail: usize,
pub edited: usize,
pub edited_before_posted: usize,
pub duplicates_dropped: usize,
pub rejected_invalid: usize,
}
/// Output of [`build_posts`]: disjoint, deterministically sorted `newswire` and `retail` streams
/// plus exact accounting stats.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PostsBuild<K = String> {
pub newswire: Vec<PostRow<K>>,
pub retail: Vec<PostRow<K>>,
pub stats: PostsStats,
}
/// Builds disjoint, deterministically sorted `newswire` and `retail` post streams from raw
/// `ceoPosts` inputs.
///
/// Rules:
/// - Rejects (counts in [`PostsStats::rejected_invalid`] without aborting) rows with an empty
/// `spiel_id` or `timestamp_ms <= 0` before timestamp conversion.
/// - Classifies `is_bot` as `true` iff `bot` is `"1"` after trimming whitespace; all other values
/// (`None`, `"0"`, `""`, etc.) route to `retail`.
/// - Sets `is_edited = edited_ms.is_some()`, counts valid edited rows in [`PostsStats::edited`],
/// and guards against look-ahead / clock-skew edits earlier than posting (`edited_ms <
/// timestamp_ms`) by clamping `known_at` to `posted_at` and incrementing
/// [`PostsStats::edited_before_posted`]. Both edit counters are recorded on valid rows prior to
/// deduplication.
/// - Converts `timestamp_ms` and the selected `known_at` millisecond value to UTC microseconds via
/// `checked_mul(1_000)`, returning [`PostsError::TimestampOverflow`] on overflow.
/// - Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail` (keeping
/// one supplied version per `spiel_id`; earlier pre-edit versions cannot be recovered). Within a
/// `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties
/// deterministically by the maximum lexicographic tuple
/// `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero
/// dependence on input order. All other `group_len - 1` rows are counted in
/// [`PostsStats::duplicates_dropped`].
/// - Sorts both `newswire` and `retail` strictly ascending by `(key, known_at, spiel_id)`.
/// - Any permutation of `rows` produces identical `newswire`, `retail`, and `stats`.
pub fn build_posts<K, I>(rows: I) -> Result<PostsBuild<K>, PostsError>
where
K: Ord + Clone,
I: IntoIterator<Item = CeoPost<K>>,
{
let iter = rows.into_iter();
let (lower, _) = iter.size_hint();
let mut stats = PostsStats::default();
let mut normalized: Vec<PostRow<K>> = Vec::with_capacity(lower);
for row in iter {
stats.input += 1;
if row.spiel_id.is_empty() || row.timestamp_ms <= 0 {
stats.rejected_invalid += 1;
continue;
}
let is_bot = row.bot.as_deref().map(str::trim) == Some("1");
let is_edited = row.edited_ms.is_some();
let known_at_ms = match row.edited_ms {
Some(edited_ms) => {
stats.edited += 1;
if edited_ms < row.timestamp_ms {
stats.edited_before_posted += 1;
row.timestamp_ms
} else {
edited_ms
}
}
None => row.timestamp_ms,
};
let posted_at =
row.timestamp_ms
.checked_mul(1_000)
.ok_or_else(|| PostsError::TimestampOverflow {
spiel_id: row.spiel_id.clone(),
field: "timestamp_ms",
timestamp_ms: row.timestamp_ms,
})?;
let known_at = if known_at_ms == row.timestamp_ms {
posted_at
} else {
known_at_ms
.checked_mul(1_000)
.ok_or_else(|| PostsError::TimestampOverflow {
spiel_id: row.spiel_id.clone(),
field: "edited_ms",
timestamp_ms: known_at_ms,
})?
};
normalized.push(PostRow {
key: row.key,
spiel_id: row.spiel_id,
posted_at,
known_at,
is_bot,
is_edited,
user_id: row.user_id,
text: row.text,
source: POSTS_SOURCE_CEO,
});
}
normalized.sort_unstable_by(|a, b| {
a.spiel_id
.cmp(&b.spiel_id)
.then_with(|| b.known_at.cmp(&a.known_at))
.then_with(|| b.posted_at.cmp(&a.posted_at))
.then_with(|| b.is_edited.cmp(&a.is_edited))
.then_with(|| b.is_bot.cmp(&a.is_bot))
.then_with(|| b.key.cmp(&a.key))
.then_with(|| b.user_id.cmp(&a.user_id))
.then_with(|| b.text.cmp(&a.text))
});
let before_dedup = normalized.len();
normalized.dedup_by(|a, b| a.spiel_id == b.spiel_id);
stats.duplicates_dropped = before_dedup - normalized.len();
let mut newswire: Vec<PostRow<K>> = Vec::new();
let mut retail: Vec<PostRow<K>> = Vec::new();
for row in normalized {
if row.is_bot {
newswire.push(row);
} else {
retail.push(row);
}
}
let output_order = |a: &PostRow<K>, b: &PostRow<K>| {
a.key
.cmp(&b.key)
.then_with(|| a.known_at.cmp(&b.known_at))
.then_with(|| a.spiel_id.cmp(&b.spiel_id))
};
newswire.sort_unstable_by(output_order);
retail.sort_unstable_by(output_order);
stats.newswire = newswire.len();
stats.retail = retail.len();
Ok(PostsBuild {
newswire,
retail,
stats,
})
}

View file

@ -0,0 +1,988 @@
use std::collections::HashSet;
use crate::posts::{
build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO,
};
fn post(
key: &str,
spiel_id: &str,
timestamp_ms: i64,
edited_ms: Option<i64>,
bot: Option<&str>,
user_id: Option<&str>,
text: &str,
) -> CeoPost<String> {
CeoPost {
key: key.to_string(),
spiel_id: spiel_id.to_string(),
timestamp_ms,
edited_ms,
bot: bot.map(str::to_string),
user_id: user_id.map(str::to_string),
text: text.to_string(),
}
}
fn assert_invariants<K: Ord + std::fmt::Debug>(build: &PostsBuild<K>) {
let s = &build.stats;
assert_eq!(
s.input,
s.newswire + s.retail + s.duplicates_dropped + s.rejected_invalid,
"accounting invariant failed: {s:?}"
);
assert_eq!(s.newswire, build.newswire.len());
assert_eq!(s.retail, build.retail.len());
assert!(s.edited_before_posted <= s.edited);
let mut seen_ids = HashSet::with_capacity(s.newswire + s.retail);
for (stream_name, rows, expected_bot) in [
("newswire", &build.newswire, true),
("retail", &build.retail, false),
] {
for pair in rows.windows(2) {
assert!(
(&pair[0].key, pair[0].known_at, &pair[0].spiel_id)
< (&pair[1].key, pair[1].known_at, &pair[1].spiel_id),
"{stream_name} must be strictly sorted by (key, known_at, spiel_id)"
);
}
for row in rows {
assert_eq!(row.is_bot, expected_bot);
assert_eq!(row.source, POSTS_SOURCE_CEO);
assert!(
row.known_at >= row.posted_at,
"look-ahead violation in {stream_name}: known_at {} < posted_at {}",
row.known_at,
row.posted_at
);
assert!(
seen_ids.insert(row.spiel_id.as_str()),
"spiel_id '{}' appeared more than once across streams",
row.spiel_id
);
}
}
}
/// Deterministic SplitMix64 PRNG for fixture generation and shuffles.
struct SplitMix64(u64);
impl SplitMix64 {
fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
fn shuffle<T>(&mut self, slice: &mut [T]) {
for i in (1..slice.len()).rev() {
let j = (self.next_u64() as usize) % (i + 1);
slice.swap(i, j);
}
}
}
/// Generates all permutations of `items` via Heap's algorithm.
fn all_permutations<T: Clone>(items: &[T]) -> Vec<Vec<T>> {
let mut out = Vec::new();
let mut arr = items.to_vec();
let n = arr.len();
let mut c = vec![0usize; n];
out.push(arr.clone());
let mut i = 0;
while i < n {
if c[i] < i {
if i % 2 == 0 {
arr.swap(0, i);
} else {
arr.swap(c[i], i);
}
out.push(arr.clone());
c[i] += 1;
i = 0;
} else {
c[i] = 0;
i += 1;
}
}
out
}
#[test]
fn bot_split_routes_only_trimmed_one_to_newswire_and_preserves_fields() {
let input = vec![
post(
"chan_a",
"sp_bot_exact",
1_700_000_000_000,
None,
Some("1"),
Some("wire_user"),
"News release headline",
),
post(
"chan_b",
"sp_bot_trimmed",
1_700_000_001_000,
None,
Some(" 1 "),
None,
"Trimmed bot flag release",
),
post(
"chan_a",
"sp_retail_zero",
1_700_000_002_000,
None,
Some("0"),
Some("u1"),
"Retail zero flag",
),
post(
"chan_a",
"sp_retail_empty",
1_700_000_003_000,
None,
Some(""),
Some("u2"),
"Retail empty flag",
),
post(
"chan_b",
"sp_retail_none",
1_700_000_004_000,
None,
None,
None,
"Retail missing flag",
),
post(
"chan_b",
"sp_retail_other",
1_700_000_005_000,
None,
Some("true"),
Some("u3"),
"Non-1 string is retail",
),
];
let built = build_posts(input).expect("valid posts should build");
assert_invariants(&built);
assert_eq!(
built.stats,
PostsStats {
input: 6,
newswire: 2,
retail: 4,
edited: 0,
edited_before_posted: 0,
duplicates_dropped: 0,
rejected_invalid: 0,
}
);
assert_eq!(
built.newswire,
vec![
PostRow {
key: "chan_a".to_string(),
spiel_id: "sp_bot_exact".to_string(),
posted_at: 1_700_000_000_000_000,
known_at: 1_700_000_000_000_000,
is_bot: true,
is_edited: false,
user_id: Some("wire_user".to_string()),
text: "News release headline".to_string(),
source: POSTS_SOURCE_CEO,
},
PostRow {
key: "chan_b".to_string(),
spiel_id: "sp_bot_trimmed".to_string(),
posted_at: 1_700_000_001_000_000,
known_at: 1_700_000_001_000_000,
is_bot: true,
is_edited: false,
user_id: None,
text: "Trimmed bot flag release".to_string(),
source: POSTS_SOURCE_CEO,
},
]
);
let retail_ids: Vec<&str> = built.retail.iter().map(|r| r.spiel_id.as_str()).collect();
assert_eq!(
retail_ids,
vec![
"sp_retail_zero",
"sp_retail_empty",
"sp_retail_none",
"sp_retail_other"
]
);
assert_eq!(built.retail[0].user_id.as_deref(), Some("u1"));
assert_eq!(built.retail[0].text, "Retail zero flag");
assert_eq!(built.retail[2].user_id, None);
assert_eq!(built.retail[2].source, POSTS_SOURCE_CEO);
}
#[test]
fn edited_timestamps_guard_known_at_and_availability_cutoff() {
let t_post = 1_710_000_000_000_i64;
let t_edit_later = t_post + 720_000; // +12 minutes
let t_edit_earlier = t_post - 5_000; // -5 seconds (clock skew)
let input = vec![
post(
"TSX:ABC",
"sp_unedited",
t_post,
None,
None,
Some("u1"),
"Unedited baseline",
),
post(
"TSX:ABC",
"sp_edited_equal",
t_post,
Some(t_post),
None,
Some("u2"),
"Edited at exact post ms",
),
post(
"TSX:ABC",
"sp_edited_later",
t_post,
Some(t_edit_later),
None,
Some("u3"),
"Rewritten after move",
),
post(
"TSX:ABC",
"sp_edited_earlier",
t_post,
Some(t_edit_earlier),
None,
Some("u4"),
"Skewed edit timestamp",
),
];
let built = build_posts(input).expect("valid posts should build");
assert_invariants(&built);
assert_eq!(built.stats.edited, 3);
assert_eq!(built.stats.edited_before_posted, 1);
let by_id = |id: &str| {
built
.retail
.iter()
.find(|r| r.spiel_id == id)
.expect("expected row in retail")
};
let unedited = by_id("sp_unedited");
assert_eq!(unedited.posted_at, t_post * 1_000);
assert_eq!(unedited.known_at, t_post * 1_000);
assert!(!unedited.is_edited);
let equal = by_id("sp_edited_equal");
assert_eq!(equal.posted_at, t_post * 1_000);
assert_eq!(equal.known_at, t_post * 1_000);
assert!(equal.is_edited);
let later = by_id("sp_edited_later");
assert_eq!(later.posted_at, t_post * 1_000);
assert_eq!(later.known_at, t_edit_later * 1_000);
assert!(later.is_edited);
// Point-in-time availability check: at a cutoff strictly between posted_at and edited_at,
// the unedited post is visible (known_at < cutoff) while the edited post is NOT yet visible.
let cutoff = (t_post + 300_000) * 1_000; // +5 minutes after post
assert!(unedited.known_at < cutoff);
assert!(later.posted_at < cutoff);
assert!(later.known_at > cutoff);
let earlier = by_id("sp_edited_earlier");
assert_eq!(earlier.posted_at, t_post * 1_000);
assert_eq!(earlier.known_at, t_post * 1_000);
assert!(earlier.is_edited);
}
#[test]
fn generated_fixture_preserves_known_at_ge_posted_at_and_edit_accounting() {
let mut rng = SplitMix64(0x5eed_cafe_1234_5678);
let mut input = Vec::with_capacity(220);
let mut expected_edited = 0usize;
let mut expected_edited_before_posted = 0usize;
let mut expected_rejected = 0usize;
// 200 valid rows (including intentional duplicate spiel_ids across 120 buckets).
for i in 0..200usize {
let key = format!("CH_{:02}", rng.next_u64() % 10);
let spiel_id = format!("sp_{:03}", rng.next_u64() % 120);
let timestamp_ms = 1_700_000_000_000 + (rng.next_u64() % 10_000_000) as i64;
let edit_mode = rng.next_u64() % 4;
let edited_ms = match edit_mode {
0 => None,
1 => {
expected_edited += 1;
Some(timestamp_ms + (rng.next_u64() % 900_000) as i64 + 1)
}
2 => {
expected_edited += 1;
expected_edited_before_posted += 1;
Some(timestamp_ms - (rng.next_u64() % 60_000) as i64 - 1)
}
_ => {
expected_edited += 1;
Some(timestamp_ms)
}
};
let bot = match rng.next_u64() % 5 {
0 => Some("1"),
1 => Some(" 1 "),
2 => Some("0"),
3 => Some(""),
_ => None,
};
input.push(post(
&key,
&spiel_id,
timestamp_ms,
edited_ms,
bot,
Some(&format!("u{}", i % 17)),
&format!("generated post {i}"),
));
}
// 20 rejected rows (some carrying edited_ms that must NOT count toward edited stats).
for i in 0..20usize {
expected_rejected += 1;
if i % 2 == 0 {
input.push(post(
"CH_BAD",
"",
1_700_000_000_000,
Some(1_699_999_999_000),
Some("1"),
None,
"empty id",
));
} else {
input.push(post(
"CH_BAD",
&format!("bad_ts_{i}"),
-(i as i64),
Some(-(i as i64) - 100),
None,
None,
"non-positive ts",
));
}
}
let built = build_posts(input).expect("generated fixture should build");
assert_invariants(&built);
assert_eq!(built.stats.input, 220);
assert_eq!(built.stats.rejected_invalid, expected_rejected);
assert_eq!(built.stats.edited, expected_edited);
assert_eq!(
built.stats.edited_before_posted,
expected_edited_before_posted
);
assert!(built.stats.duplicates_dropped > 0);
}
#[test]
fn dedup_keeps_greatest_known_at_globally_across_channels_and_streams() {
let base_ms = 1_720_000_000_000_i64;
let input = vec![
post(
"chan_a",
"shared_id",
base_ms,
None,
Some("1"),
Some("wire"),
"v1 newswire",
),
post(
"chan_b",
"shared_id",
base_ms,
Some(base_ms + 120_000),
Some("0"),
Some("retail_u"),
"v2 edited later in another channel/stream",
),
post(
"chan_c",
"shared_id",
base_ms + 60_000,
None,
Some("1"),
Some("wire"),
"v1.5 intermediate known_at",
),
];
let built = build_posts(input).expect("valid posts should build");
assert_invariants(&built);
assert_eq!(built.stats.input, 3);
assert_eq!(built.stats.newswire, 0);
assert_eq!(built.stats.retail, 1);
assert_eq!(built.stats.duplicates_dropped, 2);
assert_eq!(built.retail[0].key, "chan_b");
assert_eq!(built.retail[0].known_at, (base_ms + 120_000) * 1_000);
assert_eq!(
built.retail[0].text,
"v2 edited later in another channel/stream"
);
}
fn conflicting_tie_group() -> Vec<CeoPost<String>> {
let t = 1_725_000_000_000_i64;
vec![
// Same spiel_id & same known_at = t * 1_000, differing in text and bot flag.
post(
"chan_m",
"tie_spiel",
t,
None,
Some("0"),
Some("u_b"),
"alpha text",
),
post(
"chan_m",
"tie_spiel",
t,
None,
Some("0"),
Some("u_b"),
"zeta text",
),
// is_bot = true beats is_bot = false on same (known_at, posted_at, is_edited).
post(
"chan_m",
"tie_spiel",
t,
None,
Some("1"),
Some("u_a"),
"bot winner text",
),
// is_edited = true beats is_edited = false on same (known_at, posted_at), even with bot="0".
post(
"chan_a",
"tie_spiel",
t,
Some(t),
Some("0"),
None,
"edited winner text",
),
]
}
#[test]
fn dedup_conflicting_known_at_ties_pick_exact_tuple_winner_across_all_permutations() {
let group = conflicting_tie_group();
let expected_drops = group.len() - 1;
let perms = all_permutations(&group);
assert_eq!(perms.len(), 24);
let baseline = build_posts(group).expect("tie group should build");
assert_invariants(&baseline);
assert_eq!(baseline.stats.duplicates_dropped, expected_drops);
assert_eq!(baseline.newswire.len(), 0);
assert_eq!(baseline.retail.len(), 1);
assert_eq!(baseline.retail[0].text, "edited winner text");
assert!(baseline.retail[0].is_edited);
assert!(!baseline.retail[0].is_bot);
for perm in perms {
let built = build_posts(perm).expect("permutation should build");
assert_eq!(built, baseline);
}
// Also verify each individual tie-break field in exact precedence order:
// (posted_at, is_edited, is_bot, key, user_id [None < Some], text).
let t = 1_725_000_100_000_i64;
// 1. posted_at beats is_edited
let b1 = build_posts(vec![
post(
"z",
"tb1",
t - 1_000,
Some(t),
Some("1"),
Some("z"),
"earlier post edited to t",
),
post(
"a",
"tb1",
t,
None,
Some("0"),
None,
"later posted_at wins",
),
])
.unwrap();
assert_eq!(b1.retail[0].text, "later posted_at wins");
// 2. is_bot beats key
let b2 = build_posts(vec![
post("zzz", "tb2", t, None, Some("0"), Some("z"), "retail"),
post("aaa", "tb2", t, None, Some("1"), None, "bot wins"),
])
.unwrap();
assert_eq!(b2.newswire[0].text, "bot wins");
// 3. key beats user_id
let b3 = build_posts(vec![
post("chan_a", "tb3", t, None, Some("0"), Some("zzz"), "low key"),
post("chan_z", "tb3", t, None, Some("0"), None, "high key wins"),
])
.unwrap();
assert_eq!(b3.retail[0].text, "high key wins");
// 4. user_id (None < Some) beats text
let b4 = build_posts(vec![
post("chan_a", "tb4", t, None, Some("0"), None, "zzz text"),
post(
"chan_a",
"tb4",
t,
None,
Some("0"),
Some("a"),
"some user_id wins",
),
])
.unwrap();
assert_eq!(b4.retail[0].text, "some user_id wins");
// 5. text breaks final tie
let b5 = build_posts(vec![
post("chan_a", "tb5", t, None, Some("0"), Some("u1"), "alpha"),
post("chan_a", "tb5", t, None, Some("0"), Some("u1"), "omega"),
])
.unwrap();
assert_eq!(b5.retail[0].text, "omega");
}
#[test]
fn shuffle_invariance_with_conflicting_ties_and_sort_order() {
let mut fixture = conflicting_tie_group();
fixture.extend([
post(
"chan_b",
"sp_10",
1_725_000_010_000,
None,
Some("1"),
Some("wire"),
"wire 10",
),
post(
"chan_a",
"sp_02",
1_725_000_020_000,
None,
Some("1"),
Some("wire"),
"wire 02",
),
post(
"chan_a",
"sp_01",
1_725_000_020_000,
None,
Some("1"),
Some("wire"),
"wire 01 same known_at",
),
post(
"chan_b",
"sp_20",
1_725_000_005_000,
Some(1_725_000_030_000),
None,
Some("u20"),
"retail edited later",
),
post(
"chan_b",
"sp_20",
1_725_000_005_000,
None,
None,
Some("u20"),
"retail older version",
),
post(
"chan_a",
"sp_03",
1_725_000_001_000,
Some(1_725_000_000_000),
Some("0"),
Some("u03"),
"retail edited before posted",
),
post(
"chan_a",
"",
1_725_000_001_000,
None,
Some("1"),
None,
"invalid empty id",
),
post(
"chan_a",
"sp_bad_ts",
0,
None,
None,
None,
"invalid zero ts",
),
]);
let baseline = build_posts(fixture.clone()).expect("fixture should build");
assert_invariants(&baseline);
// Reversed order.
let mut reversed = fixture.clone();
reversed.reverse();
assert_eq!(build_posts(reversed).unwrap(), baseline);
// Multiple deterministic shuffles.
let mut rng = SplitMix64(0x1234_5678_9abc_def0);
for _ in 0..16 {
let mut shuffled = fixture.clone();
rng.shuffle(&mut shuffled);
let built = build_posts(shuffled).expect("shuffled fixture should build");
assert_eq!(built, baseline);
}
// Verify generic non-String key (e.g., listing_id: i32) works identically.
let int_keyed = build_posts(vec![
CeoPost {
key: 200_i32,
spiel_id: "s2".to_string(),
timestamp_ms: 1_700_000_000_000,
edited_ms: None,
bot: None,
user_id: None,
text: "listing 200".to_string(),
},
CeoPost {
key: 100_i32,
spiel_id: "s1".to_string(),
timestamp_ms: 1_700_000_000_000,
edited_ms: None,
bot: Some("1".to_string()),
user_id: None,
text: "listing 100".to_string(),
},
])
.expect("i32 keys should build");
assert_invariants(&int_keyed);
assert_eq!(int_keyed.newswire[0].key, 100);
assert_eq!(int_keyed.retail[0].key, 200);
}
#[test]
fn empty_invalid_and_timestamp_overflow_boundaries() {
// Empty input.
let empty = build_posts(Vec::<CeoPost<String>>::new()).expect("empty input should succeed");
assert!(empty.newswire.is_empty());
assert!(empty.retail.is_empty());
assert_eq!(empty.stats, PostsStats::default());
// Empty spiel_id, zero timestamp_ms, negative timestamp_ms (including i64::MIN).
let invalid = build_posts(vec![
post("c", "", 1_700_000_000_000, None, Some("1"), None, "empty id"),
post("c", "sp_zero", 0, None, None, None, "zero ts"),
post("c", "sp_neg", -1, None, None, None, "negative ts"),
post("c", "sp_min", i64::MIN, None, None, None, "i64 min ts"),
])
.expect("invalid rows should be rejected, not error");
assert_invariants(&invalid);
assert_eq!(invalid.stats.input, 4);
assert_eq!(invalid.stats.rejected_invalid, 4);
assert_eq!(invalid.stats.newswire, 0);
assert_eq!(invalid.stats.retail, 0);
// Greatest convertible millisecond value succeeds for both timestamp_ms and edited_ms.
let max_ms = i64::MAX / 1_000;
let boundary_ok = build_posts(vec![
post("c", "sp_max_post", max_ms, None, None, None, "max posted"),
post(
"c",
"sp_max_edit",
max_ms - 1,
Some(max_ms),
None,
None,
"max edited",
),
// Clamped earlier edited_ms = i64::MIN must not overflow when rejected in favor of timestamp_ms.
post(
"c",
"sp_clamped_min_edit",
1_000,
Some(i64::MIN),
None,
None,
"clamped min edit",
),
])
.expect("max convertible ms should succeed");
assert_invariants(&boundary_ok);
assert_eq!(boundary_ok.stats.retail, 3);
assert_eq!(boundary_ok.stats.edited, 2);
assert_eq!(boundary_ok.stats.edited_before_posted, 1);
// Overflow on timestamp_ms returns typed PostsError::TimestampOverflow.
let err_post = build_posts(vec![post(
"c",
"sp_overflow_post",
max_ms + 1,
None,
None,
None,
"overflow post",
)])
.expect_err("timestamp_ms overflow should error");
assert_eq!(
err_post,
PostsError::TimestampOverflow {
spiel_id: "sp_overflow_post".to_string(),
field: "timestamp_ms",
timestamp_ms: max_ms + 1,
}
);
assert!(err_post.to_string().contains("timestamp_ms"));
assert!(err_post.to_string().contains("sp_overflow_post"));
// Overflow on selected edited_ms returns typed PostsError::TimestampOverflow.
let err_edit = build_posts(vec![post(
"c",
"sp_overflow_edit",
1_700_000_000_000,
Some(max_ms + 1),
None,
None,
"overflow edit",
)])
.expect_err("edited_ms overflow should error");
assert_eq!(
err_edit,
PostsError::TimestampOverflow {
spiel_id: "sp_overflow_edit".to_string(),
field: "edited_ms",
timestamp_ms: max_ms + 1,
}
);
assert!(err_edit.to_string().contains("edited_ms"));
assert!(err_edit.to_string().contains("sp_overflow_edit"));
}
#[test]
fn bot_flag_whitespace_and_near_miss_values() {
let base = 1_730_000_000_000_i64;
let input = vec![
post("c", "b_exact", base, None, Some("1"), None, "exact"),
post("c", "b_tabs", base + 1, None, Some("\t1\r\n"), None, "tabs"),
post("c", "r_leading_zero", base + 2, None, Some("01"), None, "01"),
post("c", "r_decimal", base + 3, None, Some("1.0"), None, "1.0"),
post("c", "r_plus", base + 4, None, Some("+1"), None, "+1"),
post("c", "r_ten", base + 5, None, Some("10"), None, "10"),
post("c", "r_two_ones", base + 6, None, Some("1 1"), None, "1 1"),
post("c", "r_spaces", base + 7, None, Some(" "), None, "spaces"),
];
let built = build_posts(input).expect("valid posts should build");
assert_invariants(&built);
let wire_ids: Vec<&str> = built.newswire.iter().map(|r| r.spiel_id.as_str()).collect();
let retail_ids: Vec<&str> = built.retail.iter().map(|r| r.spiel_id.as_str()).collect();
assert_eq!(wire_ids, vec!["b_exact", "b_tabs"]);
assert_eq!(
retail_ids,
vec![
"r_leading_zero",
"r_decimal",
"r_plus",
"r_ten",
"r_two_ones",
"r_spaces",
]
);
}
#[test]
fn exact_duplicate_rows_collapse_and_preserve_pre_dedup_edit_counts() {
let t = 1_730_100_000_000_i64;
let edited_dup = post(
"TSXV:XYZ",
"dup_edited",
t,
Some(t + 60_000),
Some("0"),
Some("u1"),
"exact same edited text",
);
let skewed_dup = post(
"TSXV:XYZ",
"dup_skewed",
t + 1_000,
Some(t),
Some("1"),
Some("wire"),
"exact same skewed wire",
);
let input = vec![
edited_dup.clone(),
edited_dup.clone(),
edited_dup,
skewed_dup.clone(),
skewed_dup,
];
let built = build_posts(input).expect("exact duplicates should build");
assert_invariants(&built);
assert_eq!(
built.stats,
PostsStats {
input: 5,
newswire: 1,
retail: 1,
edited: 5,
edited_before_posted: 2,
duplicates_dropped: 3,
rejected_invalid: 0,
}
);
assert_eq!(built.retail[0].spiel_id, "dup_edited");
assert_eq!(built.newswire[0].spiel_id, "dup_skewed");
}
#[test]
fn dedup_alternating_stream_winners_and_losers_across_shuffles() {
let t = 1_730_200_000_000_i64;
let fixture = vec![
// Group 1: newswire wins over retail via higher known_at.
post("c1", "sp_01", t, None, Some("0"), Some("r1"), "retail v1"),
post("c1", "sp_01", t, Some(t + 5_000), Some("1"), Some("w1"), "wire v2"),
// Group 2: retail wins over newswire via higher known_at.
post("c1", "sp_02", t, None, Some("1"), Some("w2"), "wire v1"),
post("c1", "sp_02", t, Some(t + 5_000), Some("0"), Some("r2"), "retail v2"),
// Group 3: newswire wins over retail via tie-break (is_bot = true > false).
post("c1", "sp_03", t, None, Some("0"), Some("r3"), "retail tie"),
post("c1", "sp_03", t, None, Some("1"), Some("w3"), "wire tie"),
// Group 4: retail wins over newswire via tie-break (is_edited = true > false).
post("c1", "sp_04", t, None, Some("1"), Some("w4"), "wire unedited"),
post("c1", "sp_04", t, Some(t), Some("0"), Some("r4"), "retail edited"),
];
let baseline = build_posts(fixture.clone()).expect("alternating fixture should build");
assert_invariants(&baseline);
assert_eq!(baseline.stats.newswire, 2);
assert_eq!(baseline.stats.retail, 2);
assert_eq!(baseline.stats.duplicates_dropped, 4);
let wire_ids: Vec<&str> = baseline
.newswire
.iter()
.map(|r| r.spiel_id.as_str())
.collect();
let retail_ids: Vec<&str> = baseline
.retail
.iter()
.map(|r| r.spiel_id.as_str())
.collect();
assert_eq!(wire_ids, vec!["sp_03", "sp_01"]);
assert_eq!(retail_ids, vec!["sp_04", "sp_02"]);
let mut rng = SplitMix64(0xdead_beef_cafe_babe);
for _ in 0..32 {
let mut shuffled = fixture.clone();
rng.shuffle(&mut shuffled);
let built = build_posts(shuffled).expect("shuffled alternating fixture should build");
assert_eq!(built, baseline);
}
}
#[test]
fn cutoff_filter_on_known_at_hides_post_edited_after_cutoff() {
// Mirrors the worked example: cutoff at 15:45, six retail posts (one posted at 15:40 and
// rewritten at 15:52 after the stock drops), plus three unedited wire releases.
let t_1530 = 1_730_300_000_000_i64;
let t_1540 = t_1530 + 10 * 60_000;
let t_1545_cutoff_us = (t_1530 + 15 * 60_000) * 1_000;
let t_1552 = t_1530 + 22 * 60_000;
let input = vec![
post("TSXV:EX", "r1", t_1530, None, None, Some("u1"), "+1"),
post("TSXV:EX", "r2", t_1530 + 60_000, None, None, Some("u2"), "+1"),
post("TSXV:EX", "r3", t_1530 + 120_000, None, None, Some("u3"), "0"),
post("TSXV:EX", "r4", t_1530 + 180_000, None, None, Some("u4"), "-1"),
post("TSXV:EX", "r5", t_1530 + 240_000, None, None, Some("u5"), "0"),
post(
"TSXV:EX",
"r6_edited_after_cutoff",
t_1540,
Some(t_1552),
None,
Some("u6"),
"-1 rewritten after drop",
),
post("TSXV:EX", "w1", t_1530 + 30_000, None, Some("1"), Some("wire"), "+1"),
post("TSXV:EX", "w2", t_1530 + 90_000, None, Some("1"), Some("wire"), "+1"),
post("TSXV:EX", "w3", t_1530 + 150_000, None, Some("1"), Some("wire"), "+1"),
];
let built = build_posts(input).expect("worked example should build");
assert_invariants(&built);
assert_eq!(built.retail.len(), 6);
assert_eq!(built.newswire.len(), 3);
// Filtering retail on known_at < cutoff excludes the post edited at 15:52.
let visible_by_known_at: Vec<&str> = built
.retail
.iter()
.filter(|r| r.known_at < t_1545_cutoff_us)
.map(|r| r.spiel_id.as_str())
.collect();
assert_eq!(visible_by_known_at.len(), 5);
assert!(!visible_by_known_at.contains(&"r6_edited_after_cutoff"));
// Filtering on posted_at < cutoff would leak the post edited at 15:52.
let leaked_by_posted_at: Vec<&str> = built
.retail
.iter()
.filter(|r| r.posted_at < t_1545_cutoff_us)
.map(|r| r.spiel_id.as_str())
.collect();
assert_eq!(leaked_by_posted_at.len(), 6);
assert!(leaked_by_posted_at.contains(&"r6_edited_after_cutoff"));
}

View file

@ -0,0 +1,438 @@
//! QA contract tests for the public `eodIntraday1M` raw BSON decoder (T-141 / M2.3d).
//!
//! Covers gaps left by the in-crate `bson_eod_intraday_tests.rs`, using only the public API:
//! - field-order independence, case-sensitive keys, nested look-alike keys ignored;
//! - error precedence: corrupt skipped payload beats an earlier semantic error, and the first
//! semantic error in document order wins over later ones;
//! - timestamp edge values (`i32::MAX`, subnormal / half-second / huge doubles);
//! - `Display` names the offending field; empty buffer; `i32::MAX` declared length;
//! - seeded byte-mutation fuzz: never panics, conservation always holds, every buffer row equals
//! the single-document decode of the same frame, and the stream decode reproduces the buffer
//! rows, per-document errors, and terminal framing offset;
//! - stream: empty input, `max_doc_bytes` overflow, and invalid options;
//! - UTC bar-start micros map to the right `build_bars_1m` session date across the UTC midnight.
use std::io::{self, Cursor, Read};
use bson::raw::{cstr, RawBsonRef, RawDocumentBuf};
use curate_etl::{
build_bars_1m, decode_eod_intraday_buffer, decode_eod_intraday_bytes,
decode_eod_intraday_doc, decode_eod_intraday_stream, iter_raw_bson_docs, ymd_to_epoch_days,
BsonEodIntradayDecodeStats, BsonEodIntradayError, BsonStreamError, BsonStreamOptions,
RawEodIntradayBar, SplitTable,
};
const TS: i64 = 1_717_767_000;
struct SplitMix64(u64);
impl SplitMix64 {
fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
}
/// Reader returning seeded pseudo-random short reads of 1..=61 bytes.
struct JitterReader<'a> {
data: &'a [u8],
pos: usize,
rng: SplitMix64,
}
impl Read for JitterReader<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let remaining = self.data.len() - self.pos;
if remaining == 0 {
return Ok(0);
}
let step = (self.rng.next_u64() % 61) as usize + 1;
let take = remaining.min(step).min(buf.len());
buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]);
self.pos += take;
Ok(take)
}
}
fn valid_doc(code: &str, ts: i64, close: f64, volume: f64) -> RawDocumentBuf {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "X");
doc.append(cstr!("eodSearchCode"), code);
doc.append(cstr!("datetime"), "2024-06-07 13:30:00");
doc.append(cstr!("timestamp"), ts);
doc.append(cstr!("gmtoffset"), 0_i32);
doc.append(cstr!("open"), close - 0.25);
doc.append(cstr!("high"), close + 0.5);
doc.append(cstr!("low"), close - 0.5);
doc.append(cstr!("close"), close);
doc.append(cstr!("volume"), volume);
doc
}
fn with_timestamp(ts: RawBsonRef<'_>) -> RawDocumentBuf {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), "NVDA.US");
doc.append(cstr!("timestamp"), ts);
doc.append(cstr!("open"), 10.0_f64);
doc.append(cstr!("high"), 11.0_f64);
doc.append(cstr!("low"), 9.0_f64);
doc.append(cstr!("close"), 10.5_f64);
doc.append(cstr!("volume"), 1.0_f64);
doc
}
type Row = (String, i64, [u64; 5]);
fn row(b: RawEodIntradayBar<'_>) -> Row {
(
b.eod_search_code.to_owned(),
b.ts,
[
b.open.to_bits(),
b.high.to_bits(),
b.low.to_bits(),
b.close.to_bits(),
b.volume.to_bits(),
],
)
}
#[test]
fn field_order_does_not_change_the_decoded_bar() {
let forward = valid_doc("NVDA.US", TS, 120.5, 1_000.0);
let mut reversed = RawDocumentBuf::new();
reversed.append(cstr!("volume"), 1_000.0_f64);
reversed.append(cstr!("close"), 120.5_f64);
reversed.append(cstr!("low"), 120.0_f64);
reversed.append(cstr!("high"), 121.0_f64);
reversed.append(cstr!("open"), 120.25_f64);
reversed.append(cstr!("timestamp"), TS);
reversed.append(cstr!("eodSearchCode"), "NVDA.US");
assert_eq!(
decode_eod_intraday_doc(&forward).unwrap(),
decode_eod_intraday_doc(&reversed).unwrap()
);
}
#[test]
fn keys_are_case_sensitive_and_nested_look_alikes_are_ignored() {
// `Timestamp` (capital T) is not `timestamp`; a nested `timestamp` must not satisfy it either.
let mut nested = RawDocumentBuf::new();
nested.append(cstr!("timestamp"), TS);
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), "NVDA.US");
doc.append(cstr!("Timestamp"), TS);
doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
doc.append(cstr!("open"), 10.0_f64);
doc.append(cstr!("high"), 11.0_f64);
doc.append(cstr!("low"), 9.0_f64);
doc.append(cstr!("close"), 10.5_f64);
doc.append(cstr!("volume"), 1.0_f64);
assert_eq!(
decode_eod_intraday_doc(&doc),
Err(BsonEodIntradayError::MissingField { field: "timestamp" })
);
}
#[test]
fn eod_search_code_is_borrowed_verbatim_without_trimming() {
let doc = valid_doc(" NVDA.US ", TS, 10.0, 1.0);
let bar = decode_eod_intraday_bytes(doc.as_bytes()).unwrap();
assert_eq!(bar.eod_search_code, " NVDA.US ");
}
#[test]
fn first_semantic_error_in_document_order_wins() {
// close is invalid before eodSearchCode is blank: close error must be reported.
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("close"), -1.0_f64);
doc.append(cstr!("eodSearchCode"), "");
doc.append(cstr!("timestamp"), -5_i64);
doc.append(cstr!("open"), 10.0_f64);
doc.append(cstr!("high"), 11.0_f64);
doc.append(cstr!("low"), 9.0_f64);
doc.append(cstr!("volume"), 1.0_f64);
match decode_eod_intraday_doc(&doc) {
Err(BsonEodIntradayError::InvalidNumber { field: "close", value }) => {
assert_eq!(value, -1.0)
}
other => panic!("expected InvalidNumber(close), got {other:?}"),
}
// A semantic error plus a missing field: the semantic error wins over MissingField.
let mut doc2 = RawDocumentBuf::new();
doc2.append(cstr!("eodSearchCode"), "NVDA.US");
doc2.append(cstr!("timestamp"), RawBsonRef::Null);
assert!(matches!(
decode_eod_intraday_doc(&doc2),
Err(BsonEodIntradayError::WrongType { field: "timestamp", .. })
));
}
#[test]
fn corrupt_skipped_payload_after_semantic_error_is_reported_as_corrupt_bson() {
// Blank key (semantic) first, then a later `datetime` string with invalid UTF-8.
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), " ");
doc.append(cstr!("timestamp"), TS);
doc.append(cstr!("open"), 10.0_f64);
doc.append(cstr!("high"), 11.0_f64);
doc.append(cstr!("low"), 9.0_f64);
doc.append(cstr!("close"), 10.5_f64);
doc.append(cstr!("volume"), 1.0_f64);
doc.append(cstr!("datetime"), "ZZZZ");
let mut bytes = doc.into_bytes();
let pos = bytes.windows(4).position(|w| w == b"ZZZZ").unwrap();
bytes[pos + 1] = 0xFF;
let mut stats = BsonEodIntradayDecodeStats::default();
let mut errs = Vec::new();
let s = decode_eod_intraday_buffer(&bytes, |_| panic!("no row"), |o, e| errs.push((o, e)));
stats.merge(&s);
assert_eq!(errs.len(), 1);
assert!(matches!(errs[0], (0, BsonEodIntradayError::CorruptBson { offset: 0, .. })));
assert_eq!(stats.rejected_corrupt_document, 1);
assert_eq!(stats.rejected_empty_field, 0);
assert_eq!(stats.rejected_total(), 1);
}
#[test]
fn timestamp_edge_values_are_accepted_or_rejected_exactly() {
// i32::MAX seconds (2038-01-19) is valid in Int32 form.
let bar_doc = with_timestamp(RawBsonRef::Int32(i32::MAX));
let bar = decode_eod_intraday_doc(&bar_doc).unwrap();
assert_eq!(bar.ts, i64::from(i32::MAX) * 1_000_000);
let max_secs = i64::MAX / 1_000_000;
for bad in [
RawBsonRef::Double(f64::MIN_POSITIVE),
RawBsonRef::Double(5e-324),
RawBsonRef::Double(max_secs as f64 + 0.5),
RawBsonRef::Double(1e300),
RawBsonRef::Double(f64::MAX),
RawBsonRef::Int32(i32::MIN),
RawBsonRef::Int64(i64::MIN),
] {
let doc = with_timestamp(bad);
assert_eq!(
decode_eod_intraday_doc(&doc),
Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }),
"timestamp {bad:?}"
);
}
}
#[test]
fn display_messages_name_the_offending_field_and_offset() {
let cases = [
(BsonEodIntradayError::MissingField { field: "eodSearchCode" }, "eodSearchCode"),
(BsonEodIntradayError::EmptyField { field: "eodSearchCode" }, "eodSearchCode"),
(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }, "timestamp"),
(BsonEodIntradayError::InvalidNumber { field: "volume", value: -1.0 }, ">= 0"),
(BsonEodIntradayError::InvalidNumber { field: "close", value: 0.0 }, "> 0"),
(
BsonEodIntradayError::CorruptBson { offset: 77, detail: "x".into() },
"77",
),
];
for (err, needle) in cases {
let msg = err.to_string();
assert!(msg.contains(needle), "{msg:?} should contain {needle:?}");
}
}
#[test]
fn empty_buffer_and_huge_declared_length_never_panic() {
let stats = decode_eod_intraday_buffer(&[], |_| panic!(), |_, _| panic!());
assert_eq!(stats, BsonEodIntradayDecodeStats::default());
let mut bytes = valid_doc("NVDA.US", TS, 10.0, 1.0).into_bytes();
let first_len = bytes.len();
bytes.extend_from_slice(&i32::MAX.to_le_bytes());
bytes.extend_from_slice(&[0u8; 8]);
let mut rows = 0usize;
let mut errs = Vec::new();
let stats = decode_eod_intraday_buffer(&bytes, |_| rows += 1, |o, e| errs.push((o, e)));
assert_eq!(rows, 1);
assert_eq!(stats.docs_seen, 2);
assert_eq!(stats.rejected_corrupt_document, 1);
assert_eq!(errs.len(), 1);
assert_eq!(errs[0].0, first_len);
assert!(matches!(
errs[0].1,
BsonEodIntradayError::TruncatedDocument { declared_len: Some(i32::MAX), .. }
));
}
fn is_framing(e: &BsonEodIntradayError) -> bool {
matches!(
e,
BsonEodIntradayError::TruncatedDocument { .. }
| BsonEodIntradayError::CorruptDocumentLength { .. }
)
}
#[test]
fn seeded_mutation_fuzz_buffer_and_stream_agree_and_conserve_counts() {
let mut clean = Vec::new();
for i in 0..20i64 {
let doc = valid_doc(&format!("S{i:02}.US"), TS + 60 * i, 10.0 + i as f64, 100.0 * i as f64);
clean.extend_from_slice(doc.as_bytes());
}
let mut rng = SplitMix64(0x7141_B50E);
let (mut framing_cases, mut ok_cases, mut rows_seen) = (0usize, 0usize, 0usize);
for case in 0..400u64 {
let mut bytes = clean.clone();
for _ in 0..1 + (rng.next_u64() % 4) as usize {
let idx = (rng.next_u64() as usize) % bytes.len();
bytes[idx] = rng.next_u64() as u8;
}
if rng.next_u64() % 5 == 0 {
let cut = (rng.next_u64() as usize) % bytes.len();
bytes.truncate(cut);
}
// Buffer decode: every row must equal the single-frame decode of the same bytes.
let mut frames = Vec::new();
let mut it = iter_raw_bson_docs(&bytes);
while let Some(item) = it.next_with_offset() {
if let Ok((off, doc)) = item {
frames.push((off, doc.as_bytes().len()));
}
}
let mut exp_rows = Vec::new();
let mut exp_errs = Vec::new();
let stats = decode_eod_intraday_buffer(
&bytes,
|b| {
let start = b.eod_search_code.as_ptr() as usize - bytes.as_ptr() as usize;
let &(off, len) = frames
.iter()
.find(|(o, l)| start >= *o && start < o + l)
.expect("row borrows from a framed doc");
assert_eq!(decode_eod_intraday_bytes(&bytes[off..off + len]).unwrap(), b);
exp_rows.push(row(b));
},
|o, e| exp_errs.push((o as u64, e)),
);
assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total(), "case={case}");
assert_eq!(stats.rows_decoded, exp_rows.len());
assert_eq!(stats.rejected_total(), exp_errs.len());
rows_seen += exp_rows.len();
let exp_framing = match exp_errs.last() {
Some((off, e)) if is_framing(e) => {
let off = *off;
exp_errs.pop();
Some(off)
}
_ => None,
};
let cap = [1usize, 5, 41, 300, 4096][(case % 5) as usize];
let mut rows = Vec::new();
let mut errs = Vec::new();
let result = decode_eod_intraday_stream(
JitterReader { data: &bytes, pos: 0, rng: SplitMix64(case) },
BsonStreamOptions { chunk_capacity_bytes: cap, max_doc_bytes: 1 << 20 },
|b| rows.push(row(b)),
|o, e| errs.push((o, e)),
);
assert_eq!(rows, exp_rows, "case={case} cap={cap}");
assert_eq!(errs, exp_errs, "case={case} cap={cap}");
match (exp_framing, result) {
(None, Ok(s)) => {
ok_cases += 1;
assert_eq!(s, stats, "case={case}");
}
(Some(off), Err(BsonStreamError::CorruptDocumentLength { offset, .. }))
| (Some(off), Err(BsonStreamError::TruncatedDocument { offset, .. })) => {
framing_cases += 1;
assert_eq!(offset, off, "case={case} cap={cap}");
}
(exp, got) => panic!("case={case}: expected framing={exp:?}, got {got:?}"),
}
}
assert!(framing_cases >= 20, "framing_cases={framing_cases}");
assert!(ok_cases >= 20, "ok_cases={ok_cases}");
assert!(rows_seen > 1000, "rows_seen={rows_seen}");
}
#[test]
fn stream_handles_empty_input_oversized_docs_and_invalid_options() {
let stats = decode_eod_intraday_stream(
Cursor::new(Vec::<u8>::new()),
BsonStreamOptions::default(),
|_| panic!(),
|_, _| panic!(),
)
.unwrap();
assert_eq!(stats, BsonEodIntradayDecodeStats::default());
let first = valid_doc("NVDA.US", TS, 10.0, 1.0).into_bytes();
let mut big = valid_doc("BIG.US", TS, 10.0, 1.0);
big.append(cstr!("pad"), "p".repeat(256).as_str());
let mut input = first.clone();
input.extend_from_slice(big.as_bytes());
let mut rows = Vec::new();
let err = decode_eod_intraday_stream(
Cursor::new(&input),
BsonStreamOptions { chunk_capacity_bytes: 16, max_doc_bytes: 200 },
|b| rows.push(row(b)),
|_, e| panic!("unexpected per-doc error {e:?}"),
)
.unwrap_err();
assert_eq!(rows.len(), 1);
assert!(matches!(
err,
BsonStreamError::CorruptDocumentLength { offset, max_doc_bytes: 200, .. }
if offset == first.len() as u64
));
for (opts, want_cap) in [
(BsonStreamOptions { chunk_capacity_bytes: 0, max_doc_bytes: 4096 }, true),
(BsonStreamOptions { chunk_capacity_bytes: 16, max_doc_bytes: 4 }, false),
] {
let err = decode_eod_intraday_stream(Cursor::new(&input), opts, |_| {}, |_, _| {})
.unwrap_err();
if want_cap {
assert!(matches!(err, BsonStreamError::InvalidChunkCapacity));
} else {
assert!(matches!(err, BsonStreamError::InvalidMaxDocBytes));
}
}
}
#[test]
fn utc_bar_start_micros_assign_late_et_bars_to_the_correct_session_date() {
// 2024-06-07 19:59 EDT = 2024-06-07 23:59 UTC (same UTC date) and
// 2024-06-07 20:00 EDT = 2024-06-08 00:00 UTC (next UTC date) both belong to the 06-07
// US session; a seconds/micros unit slip would push them to 1970 or far future dates.
let late = 1_717_804_740_i64; // 2024-06-07T23:59:00Z
let after_midnight = 1_717_804_800_i64; // 2024-06-08T00:00:00Z
let mut buf = Vec::new();
buf.extend_from_slice(valid_doc("NVDA.US", late, 120.0, 10.0).as_bytes());
buf.extend_from_slice(valid_doc("NVDA.US", after_midnight, 120.1, 10.0).as_bytes());
let mut bars = Vec::new();
decode_eod_intraday_buffer(
&buf,
|b| bars.push(b.into_eod_intraday_bar(|c, _| c.to_owned())),
|_, e| panic!("{e:?}"),
);
let built = build_bars_1m(bars, &SplitTable::<String>::default());
let june7 = ymd_to_epoch_days(2024, 6, 7).unwrap();
let dates: Vec<i32> = built.rows.iter().map(|r| r.session_date).collect();
assert_eq!(built.rows.len(), 2);
assert_eq!(dates, vec![june7, june7]);
assert_eq!(built.rows[0].ts, late * 1_000_000);
assert_eq!(built.rows[1].ts, after_midnight * 1_000_000);
}

View file

@ -46,6 +46,7 @@ fn no_args_and_help_print_usage_and_succeed() {
"{args:?}: {text}"
);
assert!(text.contains("bench-split"), "{args:?}: {text}");
assert!(text.contains("bench-ilp-bars-1m"), "{args:?}: {text}");
assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}");
assert!(text.contains("bench-fx"), "{args:?}: {text}");
assert!(text.contains("bench-events"), "{args:?}: {text}");
@ -90,6 +91,10 @@ fn invalid_invocations_exit_nonzero_with_usage_on_stderr() {
&["bench-curate-fx", "0"][..],
&["bench-curate-fx", "-5"][..],
&["bench-curate-fx", "10", "20"][..],
&["bench-ilp-bars-1m", "abc"][..],
&["bench-ilp-bars-1m", "0"][..],
&["bench-ilp-bars-1m", "-5"][..],
&["bench-ilp-bars-1m", "10", "20"][..],
&["--unknown"][..],
&["export"][..],
] {
@ -260,6 +265,33 @@ fn bench_curate_fx_small_run_is_headless_deterministic_and_reports_rates() {
assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes="));
}
#[test]
fn bench_ilp_bars_1m_small_run_is_headless_deterministic_and_reports_rates() {
let a = run(&["bench-ilp-bars-1m", "2000"]);
let b = run(&["bench-ilp-bars-1m", "2000"]);
assert!(a.status.success(), "{}", stderr(&a));
assert!(b.status.success(), "{}", stderr(&b));
assert!(stderr(&a).is_empty(), "unexpected stderr: {}", stderr(&a));
assert!(stderr(&b).is_empty(), "unexpected stderr: {}", stderr(&b));
let text_a = stdout(&a);
let text_b = stdout(&b);
assert!(text_a.contains("curate-etl bench-ilp-bars-1m"), "{text_a}");
assert!(text_a.contains("rows=2000 "), "{text_a}");
assert!(text_a.contains("rows_encoded=2000 "), "{text_a}");
assert!(text_a.contains("rows/s"), "{text_a}");
assert!(text_a.contains("bytes/row"), "{text_a}");
assert!(text_a.contains("MB/s"), "{text_a}");
let field = |s: &str, prefix: &str| {
s.split_whitespace()
.find(|t| t.starts_with(prefix))
.map(str::to_owned)
};
assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes="));
assert_eq!(field(&text_a, "flushes="), field(&text_b, "flushes="));
}
static CLI_TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
struct CliTempDir {

View file

@ -0,0 +1,381 @@
//! QA contract tests for the QuestDB ILP v2 encoder and sharded writer (T-137 / M2.3c).
//!
//! Uses only the public crate API. Expected wire bytes are written out by hand (decimal
//! timestamps, hex IEEE-754 payloads) and shard routing is checked against an independently
//! written FNV-1a reference, so the encoder is not used as its own oracle.
use std::io::{self, Write};
use std::sync::{Arc, Mutex};
use curate_etl::{
encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Bar1mRow,
Fx1mRow, IlpEncodeError, IlpShardedWriter, IlpWriterError, IlpWriterOptions,
IntradaySession, BARS_1M_SOURCE_EOD, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M,
};
fn bar(key: i32, ts: i64) -> Bar1mRow<i32> {
Bar1mRow {
key,
ts,
session_date: 20_000,
open: 1.0,
high: 2.0,
low: 0.5,
close: 1.5,
volume: 0.0,
session: IntradaySession::Rth,
source: BARS_1M_SOURCE_EOD,
}
}
fn fx(pair: &'static str, ts: i64) -> Fx1mRow<'static> {
Fx1mRow {
pair,
ts,
open: 1.0,
high: 2.0,
low: 0.5,
close: 1.5,
source: "eod",
}
}
type BarSetter = fn(&mut Bar1mRow<i32>, f64);
type FxSetter = fn(&mut Fx1mRow<'static>, f64);
fn encoded_bar(row: &Bar1mRow<i32>, known_at: i64) -> Vec<u8> {
let mut v = Vec::new();
encode_bar_1m(&mut v, row, known_at).unwrap();
v
}
/// Independent FNV-1a 64 reference (spec constants written inline).
fn ref_fnv1a(bytes: &[u8]) -> u64 {
bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, &b| {
(h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
})
}
/// Sink that records every `write` call and flush, optionally failing a numbered write.
#[derive(Clone, Default)]
struct Rec {
writes: Arc<Mutex<Vec<Vec<u8>>>>,
flushes: Arc<Mutex<usize>>,
fail_write_call: Option<usize>,
}
impl Rec {
fn writes(&self) -> Vec<Vec<u8>> {
self.writes.lock().unwrap().clone()
}
fn bytes(&self) -> Vec<u8> {
self.writes().concat()
}
fn flushes(&self) -> usize {
*self.flushes.lock().unwrap()
}
}
impl Write for Rec {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut w = self.writes.lock().unwrap();
if self.fail_write_call == Some(w.len()) {
return Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected"));
}
w.push(buf.to_vec());
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
*self.flushes.lock().unwrap() += 1;
Ok(())
}
}
#[test]
fn table_names_and_double_marker_match_contract() {
assert_eq!(TABLE_BARS_1M, "bars_1m");
assert_eq!(TABLE_FX_1M, "fx_1m");
assert_eq!(ILP_V2_DOUBLE_TYPE, 16);
}
#[test]
fn fx_1m_golden_bytes_use_hand_written_little_endian_payloads() {
let row = Fx1mRow {
pair: "USD.CAD",
ts: 1_700_000_000_000_000,
open: 1.0,
high: 2.0,
low: 0.5,
close: -1.5,
source: "eod",
};
let mut actual = Vec::new();
encode_fx_1m(&mut actual, &row).unwrap();
let mut expected = b"fx_1m,pair=USD.CAD,source=eod ".to_vec();
expected.extend_from_slice(b"open==\x10\x00\x00\x00\x00\x00\x00\xf0\x3f");
expected.extend_from_slice(b",high==\x10\x00\x00\x00\x00\x00\x00\x00\x40");
expected.extend_from_slice(b",low==\x10\x00\x00\x00\x00\x00\x00\xe0\x3f");
expected.extend_from_slice(b",close==\x10\x00\x00\x00\x00\x00\x00\xf8\xbf");
expected.extend_from_slice(b" 1700000000000000t\n");
assert_eq!(actual, expected);
}
#[test]
fn encoder_appends_to_existing_buffer_without_clearing_it() {
let mut buf = b"prior-line\n".to_vec();
encode_bar_1m(&mut buf, &bar(1, 10), 20).unwrap();
encode_fx_1m(&mut buf, &fx("EUR.USD", 30)).unwrap();
let mut expected = b"prior-line\n".to_vec();
expected.extend(encoded_bar(&bar(1, 10), 20));
let mut fx_line = Vec::new();
encode_fx_1m(&mut fx_line, &fx("EUR.USD", 30)).unwrap();
expected.extend(fx_line);
assert_eq!(buf, expected);
}
#[test]
fn integer_extremes_encode_as_exact_decimal_without_overflow() {
// i32::MIN listing id, i64::MIN known_at, i64::MAX designated ts.
let row = bar(i32::MIN, i64::MAX);
let line = encoded_bar(&row, i64::MIN);
assert!(line.starts_with(b"bars_1m,listing_id=-2147483648,session=RTH,source=eod_unadj "));
assert!(line.ends_with(b",known_at=-9223372036854775808t 9223372036854775807t\n"));
// Zero designated ts and zero known_at are valid boundaries.
let zero = encoded_bar(&bar(0, 0), 0);
assert!(zero.starts_with(b"bars_1m,listing_id=0,"));
assert!(zero.ends_with(b",known_at=0t 0t\n"));
let mut buf = Vec::new();
encode_fx_1m(&mut buf, &fx("X", i64::MAX)).unwrap();
assert!(buf.ends_with(b" 9223372036854775807t\n"));
}
#[test]
fn extreme_finite_doubles_round_trip_bit_exactly() {
for v in [
-0.0_f64,
f64::MIN_POSITIVE,
f64::from_bits(1), // smallest subnormal
f64::MAX,
f64::MIN,
f64::EPSILON,
] {
let mut row = bar(5, 1);
row.low = v;
let line = encoded_bar(&row, 2);
let prefix = b",low==\x10";
let pos = line.windows(prefix.len()).position(|w| w == prefix).unwrap() + prefix.len();
let raw: [u8; 8] = line[pos..pos + 8].try_into().unwrap();
assert_eq!(f64::from_le_bytes(raw).to_bits(), v.to_bits(), "value {v:e}");
}
}
#[test]
fn every_double_field_rejects_each_non_finite_value_atomically() {
let sentinel = b"keep".to_vec();
let bar_fields: [(&str, BarSetter); 5] = [
("open", |r, v| r.open = v),
("high", |r, v| r.high = v),
("low", |r, v| r.low = v),
("close", |r, v| r.close = v),
("volume", |r, v| r.volume = v),
];
let fx_fields: [(&str, FxSetter); 4] = [
("open", |r, v| r.open = v),
("high", |r, v| r.high = v),
("low", |r, v| r.low = v),
("close", |r, v| r.close = v),
];
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
for (name, set) in bar_fields {
let mut row = bar(1, 1);
set(&mut row, bad);
let mut buf = sentinel.clone();
match encode_bar_1m(&mut buf, &row, 1) {
Err(IlpEncodeError::NonFiniteDouble { field, .. }) => assert_eq!(field, name),
other => panic!("bars_1m {name}={bad}: unexpected {other:?}"),
}
assert_eq!(buf, sentinel);
}
for (name, set) in fx_fields {
let mut row = fx("USD.CAD", 1);
set(&mut row, bad);
let mut buf = sentinel.clone();
match encode_fx_1m(&mut buf, &row) {
Err(IlpEncodeError::NonFiniteDouble { field, .. }) => assert_eq!(field, name),
other => panic!("fx_1m {name}={bad}: unexpected {other:?}"),
}
assert_eq!(buf, sentinel);
}
}
let mut buf = sentinel.clone();
assert_eq!(
encode_fx_1m(&mut buf, &Fx1mRow { source: "", ..fx("USD.CAD", 1) }),
Err(IlpEncodeError::EmptySymbol { field: "source" })
);
assert_eq!(buf, sentinel);
}
#[test]
fn routing_matches_independent_fnv1a_reference_and_published_vectors() {
// Published FNV-1a 64 test vectors.
assert_eq!(fnv1a_64(b""), 0xcbf2_9ce4_8422_2325);
assert_eq!(fnv1a_64(b"a"), 0xaf63_dc4c_8601_ec8c);
assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8);
for shards in [1usize, 2, 3, 4, 7, 16] {
for id in [-1_000_000, -1, 0, 1, 42, 65_535, i32::MAX, i32::MIN] {
let expected = (ref_fnv1a(&id.to_le_bytes()) % shards as u64) as usize;
assert_eq!(shard_for_listing_id(id, shards), expected, "id {id} shards {shards}");
}
for pair in ["USD.CAD", "EUR.USD", "a b", "caf\u{e9}"] {
let expected = (ref_fnv1a(pair.as_bytes()) % shards as u64) as usize;
assert_eq!(shard_for_fx_pair(pair, shards), expected);
}
}
}
#[test]
fn fx_routing_hashes_raw_pair_not_escaped_wire_form() {
// A pair that needs escaping must route by its raw bytes.
let pair = "US D";
let shards = 8;
let sinks: Vec<Rec> = (0..shards).map(|_| Rec::default()).collect();
let mut w = IlpShardedWriter::new(sinks.clone(), IlpWriterOptions::default()).unwrap();
w.write_fx_1m(&fx(pair, 1)).unwrap();
let stats = w.finish().unwrap();
let target = (ref_fnv1a(pair.as_bytes()) % shards as u64) as usize;
assert_eq!(stats.per_shard_rows[target], 1);
assert!(sinks[target].bytes().starts_with(b"fx_1m,pair=US\\ D,source=eod "));
}
#[test]
fn single_shard_writer_preserves_global_input_order() {
let sink = Rec::default();
let mut w = IlpShardedWriter::new(
vec![sink.clone()],
IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 7 },
)
.unwrap();
let mut expected = Vec::new();
for i in 0..50i64 {
let row = bar((i % 9) as i32 - 4, 1_000 + i);
expected.extend(encoded_bar(&row, 2_000 + i));
w.write_bar_1m(&row, 2_000 + i).unwrap();
}
let stats = w.finish().unwrap();
assert_eq!(sink.bytes(), expected);
assert_eq!(stats.rows, 50);
assert_eq!(stats.per_shard_rows, vec![50]);
assert_eq!(stats.flushes, 8); // 7 full batches of 7 + one remainder of 1
assert_eq!(stats.bytes, expected.len());
}
#[test]
fn row_and_byte_limits_hit_on_same_row_produce_one_flush() {
let row = bar(3, 100);
let len = encoded_bar(&row, 200).len();
let sink = Rec::default();
let mut w = IlpShardedWriter::new(
vec![sink.clone()],
IlpWriterOptions { max_batch_bytes: 2 * len, max_batch_rows: 2 },
)
.unwrap();
for _ in 0..4 {
w.write_bar_1m(&row, 200).unwrap();
}
let stats = w.finish().unwrap();
let writes = sink.writes();
assert_eq!(writes.len(), 2);
assert!(writes.iter().all(|b| b.len() == 2 * len));
assert_eq!(stats.flushes, 2);
assert_eq!(sink.flushes(), 1);
}
#[test]
fn bytes_and_rows_are_counted_only_after_a_successful_batch() {
// Interleave two shards; shard holding the failing sink fails on its 2nd batch.
let a = (1..1000).find(|&id| shard_for_listing_id(id, 2) == 0).unwrap();
let b = (1..1000).find(|&id| shard_for_listing_id(id, 2) == 1).unwrap();
let ok = Rec::default();
let bad = Rec { fail_write_call: Some(1), ..Rec::default() };
let mut w = IlpShardedWriter::new(
vec![ok.clone(), bad.clone()],
IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 2 },
)
.unwrap();
for i in 0..3 {
w.write_bar_1m(&bar(a, i), i).unwrap();
}
w.write_bar_1m(&bar(b, 1), 1).unwrap();
w.write_bar_1m(&bar(b, 2), 2).unwrap(); // first batch on shard 1 succeeds
w.write_bar_1m(&bar(b, 3), 3).unwrap();
let err = w.write_bar_1m(&bar(b, 4), 4).unwrap_err();
assert!(matches!(err, IlpWriterError::Io { shard: 1, .. }));
assert!(err.to_string().contains("shard 1"), "{err}");
assert!(std::error::Error::source(&err).is_some());
// Healthy shard got exactly its one full batch; buffered remainder is never sent.
assert_eq!(ok.writes().len(), 1);
assert_eq!(bad.writes().len(), 1);
assert!(matches!(w.finish(), Err(IlpWriterError::Poisoned { failed_shard: 1 })));
assert_eq!(ok.writes().len(), 1);
assert_eq!(ok.flushes(), 0);
}
#[test]
fn encode_error_inside_writer_leaves_pending_batch_and_stats_intact() {
let sink = Rec::default();
let mut w = IlpShardedWriter::new(
vec![sink.clone()],
IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 3 },
)
.unwrap();
let good1 = bar(9, 1);
let good2 = bar(9, 2);
let good3 = bar(9, 3);
w.write_bar_1m(&good1, 10).unwrap();
let mut bad = bar(9, -5);
bad.close = 3.0;
assert!(matches!(
w.write_bar_1m(&bad, 10),
Err(IlpWriterError::Encode(IlpEncodeError::NegativeTimestamp { field: "ts", value: -5 }))
));
w.write_bar_1m(&good2, 10).unwrap();
w.write_bar_1m(&good3, 10).unwrap(); // third valid row hits the row limit
let writes = sink.writes();
assert_eq!(writes.len(), 1);
let mut expected = encoded_bar(&good1, 10);
expected.extend(encoded_bar(&good2, 10));
expected.extend(encoded_bar(&good3, 10));
assert_eq!(writes[0], expected);
let stats = w.finish().unwrap();
assert_eq!(stats.rows, 3);
assert_eq!(stats.bytes, expected.len());
}
#[test]
fn bars_and_fx_rows_can_share_a_writer_with_independent_routing() {
let shards = 4;
let sinks: Vec<Rec> = (0..shards).map(|_| Rec::default()).collect();
let mut w = IlpShardedWriter::new(sinks.clone(), IlpWriterOptions::default()).unwrap();
w.write_bar_1m(&bar(42, 1), 2).unwrap();
w.write_fx_1m(&fx("USD.CAD", 3)).unwrap();
let stats = w.finish().unwrap();
assert_eq!(stats.rows, 2);
let bar_shard = shard_for_listing_id(42, shards);
let fx_shard = shard_for_fx_pair("USD.CAD", shards);
let total: usize = sinks.iter().map(|s| s.bytes().len()).sum();
assert_eq!(stats.bytes, total);
let bar_bytes = sinks[bar_shard].bytes();
let fx_bytes = sinks[fx_shard].bytes();
assert!(bar_bytes.windows(8).any(|w| w == b"bars_1m,"));
assert!(fx_bytes.windows(6).any(|w| w == b"fx_1m,"));
}

View file

@ -0,0 +1,332 @@
//! QA contract tests for the public `posts` builder (T-140 / M2.2b).
//!
//! Covers gaps left by the in-crate `posts_tests.rs`, checking against independent references
//! rather than the builder's own logic:
//! - seeded differential test against a naive reference (group by `spiel_id`, `max_by` winner
//! tuple, route, sort) on high-collision fixtures that force `known_at` ties;
//! - truncation test: every row visible at a cutoff in the full build is reproduced unchanged by a
//! build over only the inputs available before that cutoff;
//! - poison test: absurd future edits to existing posts never change what is visible before the
//! cutoff, except that the poisoned posts stop being visible (latest-only text, no recovery);
//! - an overflow row anywhere in the batch fails the whole build for every input order.
use std::collections::{BTreeMap, BTreeSet};
use curate_etl::{build_posts, CeoPost, PostRow, PostsBuild, PostsError, POSTS_SOURCE_CEO};
/// Deterministic SplitMix64 PRNG (seeded; no wall clock).
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
fn shuffle<T>(&mut self, v: &mut [T]) {
for i in (1..v.len()).rev() {
let j = self.below(i as u64 + 1) as usize;
v.swap(i, j);
}
}
}
const BASE_MS: i64 = 1_735_000_000_000;
/// High-collision fixture: few ids, few channels, coarse timestamps, so ties on `known_at` and on
/// several tie-break fields are frequent. Includes invalid rows.
fn collision_fixture(seed: u64, n: usize, ids: u64) -> Vec<CeoPost<String>> {
let mut rng = Rng(seed);
let bots = [
Some("1"),
Some(" 1"),
Some("0"),
Some(""),
None,
Some("yes"),
];
let users = [None, Some("u_a"), Some("u_b")];
let texts = ["a", "b", "c"];
(0..n)
.map(|_| {
let spiel_id = match rng.below(25) {
0 => String::new(),
_ => format!("sp_{}", rng.below(ids)),
};
let timestamp_ms = match rng.below(20) {
0 => 0,
1 => -5,
_ => BASE_MS + 1_000 * rng.below(4) as i64,
};
let edited_ms = match rng.below(4) {
0 => None,
1 => Some(timestamp_ms),
2 => Some(timestamp_ms - 1_000),
_ => Some(BASE_MS + 1_000 * rng.below(6) as i64),
};
CeoPost {
key: format!("ch_{}", rng.below(3)),
spiel_id,
timestamp_ms,
edited_ms,
bot: bots[rng.below(bots.len() as u64) as usize].map(str::to_string),
user_id: users[rng.below(users.len() as u64) as usize].map(str::to_string),
text: texts[rng.below(texts.len() as u64) as usize].to_string(),
}
})
.collect()
}
/// Independent reference written from the task's rules, not from `posts.rs`.
fn reference(rows: &[CeoPost<String>]) -> (Vec<PostRow>, Vec<PostRow>, usize, usize) {
let mut rejected = 0usize;
let mut groups: BTreeMap<String, Vec<PostRow>> = BTreeMap::new();
for r in rows {
if r.spiel_id.is_empty() || r.timestamp_ms <= 0 {
rejected += 1;
continue;
}
let posted_at = r.timestamp_ms * 1_000;
let known_at = r
.edited_ms
.map_or(r.timestamp_ms, |e| e.max(r.timestamp_ms))
* 1_000;
groups.entry(r.spiel_id.clone()).or_default().push(PostRow {
key: r.key.clone(),
spiel_id: r.spiel_id.clone(),
posted_at,
known_at,
is_bot: r.bot.as_deref().map(str::trim) == Some("1"),
is_edited: r.edited_ms.is_some(),
user_id: r.user_id.clone(),
text: r.text.clone(),
source: POSTS_SOURCE_CEO,
});
}
let mut dropped = 0usize;
let (mut wire, mut retail) = (Vec::new(), Vec::new());
for (_, group) in groups {
dropped += group.len() - 1;
let winner = group
.into_iter()
.max_by(|a, b| {
(
a.known_at,
a.posted_at,
a.is_edited,
a.is_bot,
&a.key,
&a.user_id,
&a.text,
)
.cmp(&(
b.known_at,
b.posted_at,
b.is_edited,
b.is_bot,
&b.key,
&b.user_id,
&b.text,
))
})
.unwrap();
if winner.is_bot {
wire.push(winner);
} else {
retail.push(winner);
}
}
let order = |r: &PostRow| (r.key.clone(), r.known_at, r.spiel_id.clone());
wire.sort_by_key(order);
retail.sort_by_key(order);
(wire, retail, dropped, rejected)
}
#[test]
fn seeded_differential_matches_naive_reference_on_high_collision_fixtures() {
for seed in 0..40u64 {
let input = collision_fixture(0xC0FF_EE00 + seed, 120, 8);
let built = build_posts(input.clone()).expect("fixture has no overflow");
let (wire, retail, dropped, rejected) = reference(&input);
assert_eq!(built.newswire, wire, "seed {seed}: newswire mismatch");
assert_eq!(built.retail, retail, "seed {seed}: retail mismatch");
assert_eq!(built.stats.duplicates_dropped, dropped, "seed {seed}");
assert_eq!(built.stats.rejected_invalid, rejected, "seed {seed}");
assert_eq!(built.stats.input, input.len());
assert_eq!(
built.stats.input,
built.stats.newswire
+ built.stats.retail
+ built.stats.duplicates_dropped
+ built.stats.rejected_invalid
);
let valid = input
.iter()
.filter(|r| !r.spiel_id.is_empty() && r.timestamp_ms > 0);
assert_eq!(
built.stats.edited,
valid.clone().filter(|r| r.edited_ms.is_some()).count()
);
assert_eq!(
built.stats.edited_before_posted,
valid
.filter(|r| r.edited_ms.is_some_and(|e| e < r.timestamp_ms))
.count()
);
}
}
/// Ordered projection of a `PostRow` (which is not `Ord`) for set comparisons.
type RowKey = (String, String, i64, i64, bool, bool, Option<String>, String);
fn row_key(r: &PostRow) -> RowKey {
(
r.spiel_id.clone(),
r.key.clone(),
r.posted_at,
r.known_at,
r.is_bot,
r.is_edited,
r.user_id.clone(),
r.text.clone(),
)
}
fn visible(build: &PostsBuild<String>, cutoff_us: i64) -> BTreeSet<RowKey> {
build
.newswire
.iter()
.chain(build.retail.iter())
.filter(|r| r.known_at < cutoff_us)
.map(row_key)
.collect()
}
fn known_at_us(r: &CeoPost<String>) -> i64 {
r.edited_ms
.map_or(r.timestamp_ms, |e| e.max(r.timestamp_ms))
* 1_000
}
#[test]
fn truncation_rows_visible_at_cutoff_are_reproduced_from_pre_cutoff_inputs_only() {
for seed in 0..20u64 {
let input = collision_fixture(0x7A0C_0000 + seed, 150, 60);
let full = build_posts(input.clone()).unwrap();
assert!(!visible(&full, (BASE_MS + 2_000) * 1_000).is_empty());
for step in 0..=6i64 {
let cutoff_us = (BASE_MS + 1_000 * step) * 1_000;
let truncated_input: Vec<_> = input
.iter()
.filter(|r| r.timestamp_ms > 0 && known_at_us(r) < cutoff_us)
.cloned()
.collect();
let truncated = build_posts(truncated_input).unwrap();
let full_visible = visible(&full, cutoff_us);
let trunc_visible = visible(&truncated, cutoff_us);
// Every row the full build exposes before the cutoff must be derivable from data
// available before the cutoff (no future-dependent winner selection).
assert!(
full_visible.is_subset(&trunc_visible),
"seed {seed} cutoff step {step}: full build exposes rows not reproducible pre-cutoff: {:?}",
full_visible.difference(&trunc_visible).collect::<Vec<_>>()
);
// Truncated build never exposes anything at/after the cutoff.
assert!(truncated
.newswire
.iter()
.chain(truncated.retail.iter())
.all(|r| r.known_at < cutoff_us));
}
}
}
#[test]
fn poison_future_edits_never_change_pre_cutoff_view_except_hiding_poisoned_ids() {
let cutoff_us = (BASE_MS + 3_000) * 1_000;
let far_future_ms = BASE_MS + 10 * 365 * 86_400_000;
for seed in 0..20u64 {
let input = collision_fixture(0x9015_0000 + seed, 120, 60);
let base = build_posts(input.clone()).unwrap();
let base_visible = visible(&base, cutoff_us);
// Poison half of the ids that are visible before the cutoff with an absurd future edit
// flagged as a wire release in a different channel.
let poisoned: BTreeSet<String> = base_visible
.iter()
.map(|r| r.0.clone())
.enumerate()
.filter(|(i, _)| i % 2 == 0)
.map(|(_, id)| id)
.collect();
assert!(
!poisoned.is_empty(),
"seed {seed}: fixture must expose pre-cutoff rows"
);
let mut poisoned_input = input.clone();
for id in &poisoned {
poisoned_input.push(CeoPost {
key: "ch_poison".to_string(),
spiel_id: id.clone(),
timestamp_ms: BASE_MS,
edited_ms: Some(far_future_ms),
bot: Some("1".to_string()),
user_id: Some("poison".to_string()),
text: "POISON: future restatement".to_string(),
});
}
let mut rng = Rng(seed);
rng.shuffle(&mut poisoned_input);
let after = build_posts(poisoned_input).unwrap();
let after_visible = visible(&after, cutoff_us);
let expected: BTreeSet<_> = base_visible
.iter()
.filter(|r| !poisoned.contains(&r.0))
.cloned()
.collect();
assert_eq!(after_visible, expected, "seed {seed}");
assert!(after_visible.iter().all(|r| !r.7.starts_with("POISON")));
assert_eq!(
after.stats.duplicates_dropped,
base.stats.duplicates_dropped + poisoned.len()
);
}
}
#[test]
fn overflow_row_anywhere_fails_build_for_every_input_order() {
let mut input = collision_fixture(0x0F10_0001, 40, 8);
input.push(CeoPost {
key: "ch_x".to_string(),
spiel_id: "sp_overflow".to_string(),
timestamp_ms: BASE_MS,
edited_ms: Some(i64::MAX / 1_000 + 1),
bot: None,
user_id: None,
text: "overflow".to_string(),
});
let mut rng = Rng(7);
for _ in 0..16 {
let mut shuffled = input.clone();
rng.shuffle(&mut shuffled);
let err = build_posts(shuffled).expect_err("overflow must fail the build");
assert_eq!(
err,
PostsError::TimestampOverflow {
spiel_id: "sp_overflow".to_string(),
field: "edited_ms",
timestamp_ms: i64::MAX / 1_000 + 1,
}
);
}
}