Compare commits

..

No commits in common. "dev" and "master" have entirely different histories.
dev ... master

315 changed files with 635 additions and 209925 deletions

7
.gitignore vendored
View file

@ -121,10 +121,3 @@ docs/configuration-standardization.md
# Rust
target/
# Python
__pycache__/
*.py[cod]
*.egg-info/
.pytest_cache/
.venv/

1287
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -206,128 +206,3 @@ All four files are deterministic and byte-identical for identical inputs (no wal
- `conflicts.csv` — Unified deterministic conflict export across Stage A, Stage B, Pass 4, and Pass 6.
- `override-template.sql` — Commented SQL template for director-reviewed `override` entries.
- `run-stats.json` — Canonical ASCII-key-sorted JSON summary of exchange, reader, security-type, bar-span, composer, and report stats (`pass4Wired: false`).
## Read-Only Source Field-Shape Probe (`source-field-shapes.ts`)
`apps/stock/data-pipeline/src/security-master/source-field-shapes.ts` and its CLI `probe-source-field-shapes.ts` sample raw MongoDB collections read-only to report exact field names, BSON/JS value types (`string`, `int`, `double`, `bool`, `date`, `null`, `objectId`, `array`, `object`, `other`), one-level nested `parent.child` keys, string pattern classes (`ymd`, `isoDatetime`, `numeric`, `emptyOrWhitespace`, `other`), and bounded sanitized examples (never emitted for `_id` / `_id.*`).
- **Bounded read-only contract:** Initializes config with `mongoReadOnly: true`, connects via `MONGODB_READ_URI` (`studio_stock_bot_read@stock`), refuses non-read-only readers before issuing any query, and runs strictly `find({}, { limit, promoteValues: false, promoteLongs: false })` (default `limit = 1,000`, max `10,000`) over allowlisted collections (`ceoShorts`, `qmSplits`, `qmDividends`, `qmFilings`, `qmEarnings`, `qmPrices`, `eodPrices`, `teMarketData`) — no aggregations, no `$sample`, no writes, and no index operations.
- **Host live-run command (read-only QA MongoDB):**
```bash
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts \
--out ./tmp/source-field-shapes.md \
--limit 1000
```
- **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 80,000-doc streaming benchmark (`8` collections × `10,000` limit) with:
```bash
bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts
```
- **Recorded baselines (`2026-11-28`, local sandbox, in-memory async cursor fake reader):**
- Workload: `80,000` synthetic docs (`8` collections × `10,000` limit) with mixed BSON/JS types, one-level nested objects, and all five string pattern classes, including `renderFieldShapesMarkdown`.
- Initial implementation: `442,496 docs/s` (`180.8 ms` elapsed, `28.50 MiB` heap delta).
- After path-segment escaping, exact defensive sample cap, and GFM/HTML-safe cell formatting: `365,756 docs/s` (`218.7 ms` elapsed, `27.66 MiB` heap delta).
## Read-Only Curate-ETL TSV Exporter (`export-curate-inputs.ts`)
`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts` and its CLI `run-export-curate-inputs.ts` read the PostgreSQL security-master tables strictly read-only inside a `REPEATABLE READ READ ONLY` transaction (bounded chunks `<= 5,000`, using a server-side `NO SCROLL` cursor for `provider_mapping`) and atomically publish each complete three-file set as an immutable generation under `<out-dir>/generations/<generationId>` through a single atomic `<out-dir>/current` symlink commit point (`--chunk-size` is optional; default `5000`, max `5000`):
```bash
NODE_ENV=development \
POSTGRES_HOST=localhost \
POSTGRES_PORT=5433 \
POSTGRES_DATABASE=trading_bot_dev \
bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts \
--out-dir ./tmp/curate-inputs \
--chunk-size 5000
```
- **Immutable snapshot layout & consumer pinning:**
- Each export writes all three TSVs into `<out-dir>/generations/<generationId>/` and serializes top-level link setup, commit (`<out-dir>/current -> generations/<generationId>`), and rollback behind `<out-dir>/.publish.lock`. Top-level symlinks (`<out-dir>/provider_mapping.tsv`, `<out-dir>/listing_currencies.tsv`, `<out-dir>/delistings.tsv`) point through `current/<file>`.
- Multi-TSV Rust commands pin the active generation once before opening any TSV via `--curate-inputs <out-dir>` (e.g. `curate-etl curate-corporate-actions --qm-splits qmSplits.bson --qm-dividends qmDividends.bson --curate-inputs ./tmp/curate-inputs --out ./out` and `curate-etl curate-bars-1d --eod-prices eodPrices.bson --qm-splits qmSplits.bson --curate-inputs ./tmp/curate-inputs --out ./out`), and TypeScript consumers can pin via `pinCurateInputSnapshot(outDir)` so concurrent refreshes never mix files from different PostgreSQL snapshots.
- **Output files:**
- `provider_mapping.tsv` — `source \t source_id \t valid_from \t valid_to(or empty) \t listing_id`, sorted in `COLLATE "C"` ASCII order, preserving non-blank values verbatim and failing closed on `\t`/`\n`/`\r`, duplicates, or overlapping inclusive ranges.
- `listing_currencies.tsv` — `listing_id \t currency`, sorted by ascending `listing_id`.
- `delistings.tsv` — Pass 6 delistings (`source_id \t delist_date \t from_listing_id \t successor_source_id(or empty) \t terminal_return(or empty)`), resolved against `qm` mappings (`valid_from <= effective_date` for outgoing OTC transfers, valid on `effective_date` for OTC successors, valid on `listed_to` for terminal delistings) and indexed by `from_listing_id` so OTC successors (e.g. `SIVBQ`) still emit their own terminal delisting.
- **Skip-reason accounting (`rowsIn === rowsOut + skippedTotal`):**
- `active`: active listings (no delisting row emitted; fails closed if an `active` listing has a continuity or `terminal_return`).
- `noOutcome`: non-active listings with neither an outgoing `otc_delist_transfer` nor a `terminal_return`.
- `missingListedTo`: terminal-return listings with `listed_to IS NULL`.
- `missingOutgoingQmMapping`: delisting/OTC candidates without a qualifying outgoing `qm` mapping.
- `missingSuccessorQmMapping`: OTC transfers whose successor listing has no `qm` mapping valid on `effective_date`.
- `nonOtcContinuity`: non-`otc_delist_transfer` continuities skipped in the pure `buildDelistingExportRows` builder.
- **Local synthetic benchmark (zero PostgreSQL):** Run the fixed-seed 500,000-mapping / 100,000-listing streaming benchmark with:
```bash
bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts
```
- **Recorded baseline (`2026-11-29`, local sandbox, in-memory cursor/keyset queryable, `chunkSize = 5000`):**
- Workload: `500,000` `provider_mapping` rows, `100,000` `listing` rows, `2,000` OTC continuities, terminal delistings, and skipped rows (`606,680` exported rows, `17,203,861` bytes written across all three TSVs).
- Observed throughput: `1,506,181 rows/s` (`402.8 ms` elapsed, `277.01 MiB` peak RSS).
## Read-Only Raw-BSON Exporter (`export-raw-bson.ts`)
`apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` and its CLI `run-export-raw-bson.ts` stream M1 allowlisted MongoDB collections directly to `<out-dir>/<collection>.bson` as untouched length-prefixed raw BSON bytes (`find(filter, { raw: true, batchSize })` — zero per-document JS decoding), validating every frame (`byteLength >= 5`, `<= 16 MiB + 16 KiB`, 4-byte LE length prefix `=== byteLength`, trailing `0x00`), coalescing writes through a fixed-size 8 MiB buffer with strict backpressure, computing an incremental SHA-256 digest, and publishing atomically via a same-directory temp file (`open('wx')` -> `write` -> `sync` -> `close` -> `rename`).
- **Allowlisted collections (`RAW_BSON_EXPORT_COLLECTIONS`):** `eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`. Any other collection (including M2 collections such as `eodIntraday1M`, `qmIntraday`, `qmFinancials`, `ceoPosts`) is rejected before any MongoDB call.
- **Flags:**
- `--out-dir <dir>` *(required)* — destination directory for `<collection>.bson` files.
- `--collections <c1,c2,...>` *(optional)* — comma-separated subset of allowlisted collections (defaults to all 8).
- `--eod-symbol <code>` *(optional)* — exact `{ eodSearchCode: <code> }` filter; only permitted when `--collections` is strictly `eodPrices` (for example `CAD.FOREX` for `curate-fx-1d`). Use a **separate `--out-dir`** so a filtered slice never overwrites the full `eodPrices.bson`.
- `--te-symbol <sym>` *(optional)* — exact `{ teSymbol: <sym> }` filter; only permitted when `--collections` is strictly `teMarketData` (for example `USDCAD`).
- `--limit <n>` *(optional)* — positive integer document cap per collection for smoke runs.
- `--batch-size <n>` *(optional)* — MongoDB cursor `batchSize` (`1..100000`, default `4096`).
- `--help` — print usage and exit with zero config/Mongo/fs I/O.
- **Read-only safety:** Initializes config via `initializeStockConfig('dataPipeline', { mongoReadOnly: true })`, enforces `assertEnvironmentSafety()` via `assertExportRawBsonSafety()`, connects through `resolveReadOnlyMongoClientConfig()`, issues strictly `find(..., { raw: true })`, and always closes the MongoDB client in `finally`. Running against live QA MongoDB is a **separate manual host step** (never executed by automated tests or benchmarks).
### Full M1 Step 2 Chain Order (Manual Host Run)
1. **Export PostgreSQL security-master TSVs (`run-export-curate-inputs.ts`):**
```bash
NODE_ENV=development \
POSTGRES_HOST=localhost \
POSTGRES_PORT=5433 \
POSTGRES_DATABASE=trading_bot_dev \
bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts \
--out-dir ./tmp/curate-inputs
```
2. **Export raw BSON collections from read-only QA MongoDB (`run-export-raw-bson.ts`):**
```bash
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \
--out-dir ./tmp/raw-bson \
--collections eodPrices,qmSplits,qmDividends,qmPrices,ceoShorts,qmFilings,qmEarnings
# Export filtered FX inputs to a separate directory so full eodPrices.bson is not overwritten:
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \
--out-dir ./tmp/raw-bson-fx \
--collections eodPrices \
--eod-symbol CAD.FOREX
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \
--out-dir ./tmp/raw-bson-fx \
--collections teMarketData \
--te-symbol USDCAD
```
3. **Run `tools/curate-etl` commands (`curate-bars-1d` first, then the remaining datasets):**
- `curate-etl curate-bars-1d` (`--eod-prices ./tmp/raw-bson/eodPrices.bson`, `--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-prices ./tmp/raw-bson/qmPrices.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated` — writes `./tmp/curated/bars_1d/year=YYYY/part.parquet` and prints read-only `qmPrices.sharevolume` cross-check stats)
- `curate-etl curate-adj-factors` (`--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-dividends ./tmp/raw-bson/qmDividends.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--bars-1d ./tmp/curated/bars_1d`, `--out ./tmp/curated`)
- `curate-etl curate-corporate-actions` (`--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-dividends ./tmp/raw-bson/qmDividends.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated`)
- `curate-etl curate-fx-1d` (`--eod-prices ./tmp/raw-bson-fx/eodPrices.bson`, `--te-market-data ./tmp/raw-bson-fx/teMarketData.bson`, `--out ./tmp/curated`)
- `curate-etl curate-shorts` (`--ceo-shorts ./tmp/raw-bson/ceoShorts.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--out ./tmp/curated`, plus required `--shares-short-field <name>`)
- `curate-etl curate-events` (`--qm-filings ./tmp/raw-bson/qmFilings.bson`, `--qm-earnings ./tmp/raw-bson/qmEarnings.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--out ./tmp/curated`, plus required `--filings-form-type-field <name>`)
- **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 1,000,000-doc streaming benchmark with:
```bash
bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts
```
- **Recorded baseline (`2026-11-29`, local sandbox, in-memory async cursor fake source, `writeBufferBytes = 8 MiB`):**
- Workload: `1,000,000` synthetic `eodPrices` raw BSON frames (`123.9 B` avg, `123,863,264` bytes written, deterministic `sha256=67f035eba7060d6312f3d5faecc9e6a6fa14f6239c0c4dc1859794b4cd895886`).
- Run 1 (`1,000,000` docs): `3,574,267 docs/s`, `422.21 MiB/s` (`279.8 ms` elapsed, `rss_before=97.00 MiB`, `rss_after=149.91 MiB`, `peak_rss=150.19 MiB`).
- Run 2 (`1,000,000` docs): `3,692,715 docs/s`, `436.20 MiB/s` (`270.8 ms` elapsed, `peak_rss=151.03 MiB`, identical `sha256`).
- Scaling check (`2,000,000` docs, `247,726,576` bytes): `3,833,075 docs/s`, `452.78 MiB/s` (`521.8 ms` elapsed, `peak_rss=146.88 MiB` — confirms peak RSS stays bounded independent of document count).

View file

@ -1,292 +0,0 @@
/**
* Reproducible headless benchmark for `exportCurateInputs`.
* Streams 500,000 `provider_mapping` rows + 100,000 `listing` rows + 2,000 OTC continuities +
* terminal delistings + skipped rows through an in-memory keyset-paginated
* `SecurityMasterQueryable` into a temporary directory (cleaned up in `finally`), with zero
* database or network dependencies.
*
* Usage:
* bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts
*/
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
DEFAULT_EXPORT_CHUNK_SIZE,
exportCurateInputs,
type SecurityMasterQueryable,
type SecurityMasterQueryResult,
} from '../src/security-master/export-curate-inputs';
const LISTING_COUNT = 100_000;
const PROVIDER_MAPPING_COUNT = 500_000;
const OTC_CONTINUITY_COUNT = 2_000;
interface BenchContinuityRow {
from_listing_id: number;
to_listing_id: number;
effective_date: string;
kind: string;
}
interface BenchListingRow {
listing_id: number;
currency: string;
listed_to: string | null;
delist_reason: string | null;
terminal_return: string | null;
}
interface BenchMappingRow {
source: string;
source_id: string;
valid_from: string;
valid_to: string | null;
listing_id: number;
}
/**
* Generates deterministic sorted synthetic rows (matching PostgreSQL ORDER BY):
* - 100,000 listings:
* - 1..2000: OTC outgoing listings (moved_to_otc -> successor listing_id + 2000)
* - 2001..4000: OTC successor listings (half bankruptcy_cancelled -1.0, half active)
* - 4001..8000: terminal delistings (-0.3; every 20th has listed_to = null -> missingListedTo)
* - 8001..10000: delisted with null outcome (noOutcome)
* - 10001..100000: active US/CA listings
* - 500,000 provider_mapping rows in strict ASCII COLLATE "C" order across 5 sources:
* ceo (100k), eod (100k), ib (100k), qm (100k), te (100k).
* For a small deterministic subset of listings, omit the `qm` mapping (assign to listing 10001)
* so missingOutgoingQmMapping and missingSuccessorQmMapping are exercised too.
*/
function buildSyntheticTables(): {
continuities: BenchContinuityRow[];
listings: BenchListingRow[];
mappings: BenchMappingRow[];
} {
const continuities = new Array<BenchContinuityRow>(OTC_CONTINUITY_COUNT);
for (let i = 0; i < OTC_CONTINUITY_COUNT; i++) {
const fromId = i + 1;
continuities[i] = {
from_listing_id: fromId,
to_listing_id: fromId + OTC_CONTINUITY_COUNT,
effective_date: '2023-03-28',
kind: 'otc_delist_transfer',
};
}
const listings = new Array<BenchListingRow>(LISTING_COUNT);
for (let i = 0; i < LISTING_COUNT; i++) {
const id = i + 1;
const currency = id % 5 === 0 ? 'CAD' : 'USD';
if (id <= OTC_CONTINUITY_COUNT) {
listings[i] = {
listing_id: id,
currency,
listed_to: '2023-03-10',
delist_reason: 'moved_to_otc',
terminal_return: null,
};
} else if (id <= OTC_CONTINUITY_COUNT * 2) {
if (id % 2 === 0) {
listings[i] = {
listing_id: id,
currency,
listed_to: '2024-11-07',
delist_reason: 'bankruptcy_cancelled',
terminal_return: '-1.000000',
};
} else {
listings[i] = {
listing_id: id,
currency,
listed_to: null,
delist_reason: 'active',
terminal_return: null,
};
}
} else if (id <= 8_000) {
const missingDate = id % 20 === 0;
listings[i] = {
listing_id: id,
currency,
listed_to: missingDate ? null : '2023-06-15',
delist_reason: 'unknown_involuntary',
terminal_return: '-0.300000',
};
} else if (id <= 10_000) {
listings[i] = {
listing_id: id,
currency,
listed_to: '2022-12-30',
delist_reason: null,
terminal_return: null,
};
} else {
listings[i] = {
listing_id: id,
currency,
listed_to: null,
delist_reason: 'active',
terminal_return: null,
};
}
}
// 5 sources in strict ASCII order: ceo, eod, ib, qm, te (100,000 rows each = 500,000 total).
const sources = ['ceo', 'eod', 'ib', 'qm', 'te'] as const;
const mappings = new Array<BenchMappingRow>(PROVIDER_MAPPING_COUNT);
let idx = 0;
for (const source of sources) {
for (let i = 0; i < LISTING_COUNT; i++) {
const naturalListingId = i + 1;
const padded = String(naturalListingId).padStart(6, '0');
let listingId = naturalListingId;
let validFrom = '2015-01-02';
let validTo: string | null = null;
if (naturalListingId <= OTC_CONTINUITY_COUNT) {
validTo = '2023-03-10';
// Drop QM mapping for every 40th outgoing OTC listing (redirect to active listing 10001).
if (source === 'qm' && naturalListingId % 40 === 0) {
listingId = 10_001;
}
} else if (naturalListingId <= OTC_CONTINUITY_COUNT * 2) {
validFrom = '2023-03-28';
validTo = naturalListingId % 2 === 0 ? '2024-11-07' : null;
// Drop QM mapping for every 50th successor OTC listing.
if (source === 'qm' && naturalListingId % 50 === 0) {
listingId = 10_002;
}
} else if (naturalListingId <= 8_000) {
validTo = '2023-06-15';
}
mappings[idx++] = {
source,
source_id: `SYM${padded}`,
valid_from: validFrom,
valid_to: validTo,
listing_id: listingId,
};
}
}
return { continuities, listings, mappings };
}
function createFastPaginatedQueryable(tables: {
continuities: BenchContinuityRow[];
listings: BenchListingRow[];
mappings: BenchMappingRow[];
}): SecurityMasterQueryable {
let contOffset = 0;
let listingOffset = 0;
let mappingOffset = 0;
return {
async query<Row = Record<string, unknown>>(
text: string,
values?: readonly unknown[]
): Promise<SecurityMasterQueryResult<Row>> {
const normalized = text.replace(/\s+/g, ' ').trim();
if (normalized.startsWith('BEGIN')) {
contOffset = 0;
listingOffset = 0;
mappingOffset = 0;
return { rows: [] };
}
if (normalized === 'COMMIT' || normalized === 'ROLLBACK') {
return { rows: [] };
}
if (normalized.startsWith('DECLARE ') && normalized.includes('FROM provider_mapping')) {
mappingOffset = 0;
return { rows: [] };
}
const fetchMatch = /^FETCH FORWARD (\d+) FROM \S+$/i.exec(normalized);
if (fetchMatch) {
const fetchLimit = Number(fetchMatch[1]);
const slice = tables.mappings.slice(mappingOffset, mappingOffset + fetchLimit);
mappingOffset += slice.length;
return { rows: slice as unknown as Row[] };
}
if (/^CLOSE \S+$/i.test(normalized)) {
return { rows: [] };
}
const limit = values ? (values[values.length - 1] as number) : DEFAULT_EXPORT_CHUNK_SIZE;
if (normalized.includes('FROM corporate_action_continuity')) {
const slice = tables.continuities.slice(contOffset, contOffset + limit);
contOffset += slice.length;
return { rows: slice as unknown as Row[] };
}
if (normalized.includes('FROM listing')) {
const slice = tables.listings.slice(listingOffset, listingOffset + limit);
listingOffset += slice.length;
return { rows: slice as unknown as Row[] };
}
if (normalized.includes('FROM provider_mapping')) {
const slice = tables.mappings.slice(mappingOffset, mappingOffset + limit);
mappingOffset += slice.length;
return { rows: slice as unknown as Row[] };
}
throw new Error(`Unexpected SQL in benchmark queryable: ${normalized}`);
},
release: () => {},
};
}
async function main(): Promise<void> {
const tables = buildSyntheticTables();
const queryable = createFastPaginatedQueryable(tables);
const outDir = await mkdtemp(join(tmpdir(), 'curate-inputs-bench-'));
try {
const startNs = Bun.nanoseconds();
const result = await exportCurateInputs(queryable, {
outDir,
chunkSize: DEFAULT_EXPORT_CHUNK_SIZE,
});
const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6;
const d = result.delistings.stats;
const skipSum =
d.skipped.active +
d.skipped.noOutcome +
d.skipped.missingListedTo +
d.skipped.missingOutgoingQmMapping +
d.skipped.missingSuccessorQmMapping +
d.skipped.nonOtcContinuity;
if (d.skippedTotal !== skipSum || d.rowsIn !== d.rowsOut + d.skippedTotal) {
throw new Error(
`Delisting stats reconciliation failed: rowsIn=${d.rowsIn} rowsOut=${d.rowsOut} skippedTotal=${d.skippedTotal} skipSum=${skipSum}`
);
}
const totalRowsExported =
result.providerMapping.rowsOut + result.listingCurrencies.rowsOut + result.delistings.rowsOut;
const rowsPerSec = totalRowsExported / (elapsedMs / 1000);
// process.resourceUsage().maxRSS is reported in KiB on Linux.
const peakRssMiB = process.resourceUsage().maxRSS / 1024;
process.stdout.write('exportCurateInputs benchmark complete\n');
process.stdout.write(
` inputs: provider_mapping=${PROVIDER_MAPPING_COUNT} listings=${LISTING_COUNT} otc_continuities=${OTC_CONTINUITY_COUNT}\n`
);
process.stdout.write(
` exported: provider_mapping=${result.providerMapping.rowsOut} listing_currencies=${result.listingCurrencies.rowsOut} delistings=${result.delistings.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut} skipped=${d.skippedTotal})\n`
);
process.stdout.write(
` total_rows_out=${totalRowsExported} bytes_written=${result.totalBytesWritten} elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(rowsPerSec)} rows/s peak_rss=${peakRssMiB.toFixed(2)} MiB\n`
);
} finally {
await rm(outDir, { recursive: true, force: true });
}
}
main().catch(error => {
process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
process.exit(1);
});

View file

@ -1,140 +0,0 @@
/**
* Reproducible headless benchmark for `exportRawBsonCollection`.
* Streams >= 1,000,000 fixed-seed synthetic ~100 B raw BSON `eodPrices` frames through
* `exportRawBsonCollection` into a temporary directory (cleaned up in `finally`), with zero
* MongoDB or network dependencies.
*
* Usage:
* bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts [docCount]
*/
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { BSON } from 'mongodb';
import {
DEFAULT_WRITE_BUFFER_BYTES,
exportRawBsonCollection,
type ReadOnlyRawBsonSource,
} from '../src/security-master/export-raw-bson';
const DEFAULT_DOC_COUNT = 1_000_000;
const POOL_SIZE = 1_024;
function parseDocCount(): number {
const raw = process.argv[2];
if (raw === undefined) {
return DEFAULT_DOC_COUNT;
}
if (!/^\d+$/.test(raw)) {
throw new Error(`Invalid docCount "${raw}": expected a positive integer`);
}
const parsed = Number(raw);
if (!Number.isSafeInteger(parsed) || parsed < 1) {
throw new Error(`Invalid docCount "${raw}": expected a positive integer`);
}
return parsed;
}
/**
* Deterministic PRNG (Mulberry32) so the synthetic BSON pool is identical across runs.
*/
function createSeededRng(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function buildSyntheticBsonPool(): Uint8Array[] {
const rng = createSeededRng(0x5eed117);
const pool = new Array<Uint8Array>(POOL_SIZE);
for (let i = 0; i < POOL_SIZE; i++) {
const base = 10 + Math.round(rng() * 20000) / 100;
const high = Math.round((base + rng() * 3) * 100) / 100;
const low = Math.max(0.01, Math.round((base - rng() * 3) * 100) / 100);
const close = Math.round((low + rng() * (high - low)) * 100) / 100;
const volume = Math.floor(1_000 + rng() * 5_000_000);
const month = String((i % 12) + 1).padStart(2, '0');
const day = String((i % 28) + 1).padStart(2, '0');
const doc = {
eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`,
date: `2025-${month}-${day}`,
open: base,
high,
low,
close,
volume,
};
pool[i] = Uint8Array.from(BSON.serialize(doc));
}
return pool;
}
function createSyntheticRawSource(pool: readonly Uint8Array[], totalDocs: number): ReadOnlyRawBsonSource {
const poolLen = pool.length;
return {
isReadOnly: () => true,
find() {
return {
async *[Symbol.asyncIterator]() {
for (let i = 0; i < totalDocs; i++) {
const frame = pool[i % poolLen];
if (frame !== undefined) {
yield frame;
}
}
},
};
},
};
}
async function main(): Promise<void> {
const docCount = parseDocCount();
const pool = buildSyntheticBsonPool();
const avgDocBytes =
pool.reduce((acc, frame) => acc + frame.byteLength, 0) / pool.length;
const source = createSyntheticRawSource(pool, docCount);
const outDir = await mkdtemp(join(tmpdir(), 'export-raw-bson-bench-'));
try {
const rssBeforeMiB = process.memoryUsage().rss / (1024 * 1024);
const startNs = Bun.nanoseconds();
const result = await exportRawBsonCollection(source, {
collection: 'eodPrices',
outDir,
writeBufferBytes: DEFAULT_WRITE_BUFFER_BYTES,
});
const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6;
const rssAfterMiB = process.memoryUsage().rss / (1024 * 1024);
// process.resourceUsage().maxRSS is reported in KiB on Linux.
const peakRssMiB = process.resourceUsage().maxRSS / 1024;
const elapsedSec = elapsedMs / 1000;
const docsPerSec = result.docsWritten / elapsedSec;
const mibPerSec = result.bytesWritten / (1024 * 1024) / elapsedSec;
process.stdout.write('exportRawBsonCollection benchmark complete\n');
process.stdout.write(
` docs=${result.docsWritten} avg_doc_bytes=${avgDocBytes.toFixed(1)} bytes_written=${result.bytesWritten} write_buffer_bytes=${DEFAULT_WRITE_BUFFER_BYTES}\n`
);
process.stdout.write(
` elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(docsPerSec)} docs/s rate=${mibPerSec.toFixed(2)} MiB/s\n`
);
process.stdout.write(
` rss_before=${rssBeforeMiB.toFixed(2)} MiB rss_after=${rssAfterMiB.toFixed(2)} MiB peak_rss=${peakRssMiB.toFixed(2)} MiB\n`
);
process.stdout.write(` sha256=${result.sha256}\n`);
} finally {
await rm(outDir, { recursive: true, force: true });
}
}
main().catch(error => {
process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
process.exit(1);
});

View file

@ -1,167 +0,0 @@
/**
* Reproducible headless benchmark for `readFieldShapes` + `renderFieldShapesMarkdown`.
* Streams 80,000 fixed-seed synthetic documents (8 allowlisted collections × 10,000 limit)
* with mixed BSON/JS types, one-level nested objects, and all 5 string pattern classes
* through an in-memory async-generator fake reader with zero MongoDB or network dependencies.
*
* Usage:
* bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts
*/
import {
FIELD_SHAPE_PROBE_COLLECTIONS,
FIELD_VALUE_TYPES,
MAX_FIELD_SHAPE_LIMIT,
readFieldShapes,
renderFieldShapesMarkdown,
STRING_PATTERN_CLASSES,
type ReadOnlySourceSymbolCursor,
type ReadOnlySourceSymbolReader,
type SourceSymbolFindOptions,
} from '../src/security-master';
const DOCS_PER_COLLECTION = MAX_FIELD_SHAPE_LIMIT;
function mulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function makeSyntheticDoc(collectionIndex: number, docIndex: number, rng: () => number): Record<string, unknown> {
const r = rng();
const day = String((docIndex % 28) + 1).padStart(2, '0');
const month = String(((docIndex + collectionIndex) % 12) + 1).padStart(2, '0');
const dateStr = `2025-${month}-${day}`;
const isoStr = `${dateStr}T14:30:00Z`;
const doc: Record<string, unknown> = {
_id: {
_bsontype: 'ObjectId',
toString: () =>
`${String(collectionIndex).padStart(2, '0')}${String(docIndex).padStart(22, '0')}`,
},
symbol: `SYM${String(docIndex % 2000).padStart(4, '0')}`,
date: r < 0.85 ? dateStr : r < 0.95 ? isoStr : '',
value:
r < 0.5
? { _bsontype: 'Double', toString: () => (10 + (docIndex % 500) * 0.25).toFixed(2) }
: r < 0.8
? { _bsontype: 'Int32', toString: () => String(docIndex % 10000) }
: r < 0.92
? String((docIndex % 1000) / 10)
: null,
active: docIndex % 5 !== 0,
updatedAt: new Date(1735689600000 + (docIndex % 365) * 86_400_000),
meta: {
exchange: docIndex % 2 === 0 ? 'NYSE' : 'TSX',
version: { _bsontype: 'Int32', toString: () => '2' },
},
};
if (docIndex % 7 === 0) {
doc.tags = ['equity', 'na'];
}
return doc;
}
function createSyntheticBenchmarkReader(): ReadOnlySourceSymbolReader {
return {
isReadOnly(): boolean {
return true;
},
find<T extends Record<string, unknown> = Record<string, unknown>>(
collectionName: string,
_filter?: Record<string, unknown>,
options?: SourceSymbolFindOptions
): ReadOnlySourceSymbolCursor<T> {
const colIdx = FIELD_SHAPE_PROBE_COLLECTIONS.indexOf(
collectionName as (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number]
);
const count = Math.min(DOCS_PER_COLLECTION, options?.limit ?? DOCS_PER_COLLECTION);
const rng = mulberry32(0x5eed108 + (colIdx + 1) * 7919);
return {
async *[Symbol.asyncIterator](): AsyncIterator<T> {
for (let i = 0; i < count; i++) {
yield makeSyntheticDoc(colIdx, i, rng) as T;
}
},
async close(): Promise<void> {
// No-op for in-memory benchmark cursor.
},
};
},
};
}
async function main(): Promise<void> {
const reader = createSyntheticBenchmarkReader();
if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') {
Bun.gc(true);
}
const heapBefore = process.memoryUsage().heapUsed;
const startedAt = performance.now();
const result = await readFieldShapes(reader, {
limit: DOCS_PER_COLLECTION,
batchSize: 2_000,
});
const markdown = renderFieldShapesMarkdown(result);
const elapsedMs = performance.now() - startedAt;
const heapAfter = process.memoryUsage().heapUsed;
const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024);
const expectedTotal = FIELD_SHAPE_PROBE_COLLECTIONS.length * DOCS_PER_COLLECTION;
if (result.totalDocsSampled !== expectedTotal) {
throw new Error(
`Unexpected totalDocsSampled=${result.totalDocsSampled} (expected ${expectedTotal})`
);
}
for (const col of result.collections) {
for (const field of col.fields) {
if (field.presentCount + field.missingCount !== col.docCount) {
throw new Error(`Presence mismatch on ${col.collection}.${field.field}`);
}
let typeSum = 0;
for (const typeName of FIELD_VALUE_TYPES) {
typeSum += field.typeCounts[typeName];
}
if (typeSum !== field.presentCount) {
throw new Error(`Type sum mismatch on ${col.collection}.${field.field}`);
}
if (field.stringStats !== null) {
let patternSum = 0;
for (const p of STRING_PATTERN_CLASSES) {
patternSum += field.stringStats.patterns[p];
}
if (patternSum !== field.typeCounts.string) {
throw new Error(`Pattern sum mismatch on ${col.collection}.${field.field}`);
}
}
if ((field.field === '_id' || field.field.startsWith('_id.')) && field.examples.length > 0) {
throw new Error(`_id example leaked on ${col.collection}.${field.field}`);
}
}
}
const docsPerSec = Math.round(result.totalDocsSampled / (elapsedMs / 1000));
const lines = [
'Source field-shapes probe benchmark (in-memory async cursor, zero MongoDB)',
` Workload: ${result.totalDocsSampled.toLocaleString('en-US')} docs (${FIELD_SHAPE_PROBE_COLLECTIONS.length} collections x ${DOCS_PER_COLLECTION.toLocaleString('en-US')} limit)`,
` Markdown: ${markdown.length.toLocaleString('en-US')} chars`,
` Elapsed: ${elapsedMs.toFixed(1)} ms`,
` Throughput: ${docsPerSec.toLocaleString('en-US')} docs/s`,
` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`,
];
process.stdout.write(`${lines.join('\n')}\n`);
}
await main();

View file

@ -175,49 +175,6 @@ function parseExactIsoDateToUtcDay(value: unknown): number | null {
return era * 146097 + dayOfEra - 719468;
}
function formatUtcDayToIsoDate(daysSinceEpoch: number): string {
const shifted = daysSinceEpoch + 719468;
const era = Math.floor(shifted / 146097);
const doe = shifted - era * 146097;
const yoe = Math.floor(
(doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365
);
const y = yoe + era * 400;
const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
const mp = Math.floor((5 * doy + 2) / 153);
const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
const month = mp + (mp < 10 ? 3 : -9);
const year = y + (month <= 2 ? 1 : 0);
const yStr = String(year).padStart(4, '0');
const mStr = month < 10 ? `0${String(month)}` : String(month);
const dStr = day < 10 ? `0${String(day)}` : String(day);
return `${yStr}-${mStr}-${dStr}`;
}
function isBackfilledOtcContinuation(
primary: EndedPrimaryRow,
otc: EligibleOtcRow,
overlapToleranceDays: number
): boolean {
// Provider backfills (notably EODHD on SIVB -> SIVBQ) copy the primary listing's entire
// pre-delist bar history onto the OTC ticker, so otc.listedFrom matches primary.listedFrom
// rather than starting near primary.listedTo. Require that OTC trading continued strictly
// past primary.listedTo and either shares the primary's IPO/start date or carries the
// canonical bankruptcy `<primaryTicker>Q` suffix.
if (otc.listedFromDay >= primary.listedToDay - overlapToleranceDays) {
return false;
}
if (otc.listedToDay !== null && otc.listedToDay <= primary.listedToDay) {
return false;
}
const sameBackfilledStart =
primary.listedFromDay !== null &&
otc.listedFromDay <= primary.listedFromDay + overlapToleranceDays;
const isBankruptcyQSuffix =
otc.key.tickerRoot.toUpperCase() === `${primary.key.tickerRoot.toUpperCase()}Q`;
return sameBackfilledStart || isBankruptcyQSuffix;
}
function cloneListingKey(key: ListingNaturalKey): ListingNaturalKey {
return {
primaryIsin: key.primaryIsin,
@ -736,24 +693,13 @@ export function linkDelistingChains(
otc.listedToDay === null || otc.listedToDay > maxWindowDay
? maxWindowDay
: otc.listedToDay;
if (lowDay <= highDay) {
const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay);
const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay);
if (startIdx < endExclusive) {
intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx });
continue;
}
if (lowDay > highDay) {
continue;
}
// Fallback for EODHD-style backfilled OTC history (e.g. SIVB -> SIVBQ) where the OTC
// ticker carries pre-delist bars back to the primary listing's original start date.
for (let pIdx = 0; pIdx < primaries.length; pIdx++) {
const primary = primaries[pIdx];
if (
primary !== undefined &&
isBackfilledOtcContinuation(primary, otc, overlapToleranceDays)
) {
intervals.push({ startIdx: pIdx, endIdx: pIdx, otcIdx: oIdx });
}
const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay);
const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay);
if (startIdx < endExclusive) {
intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx });
}
}
@ -784,16 +730,13 @@ export function linkDelistingChains(
const otc = oIdx !== undefined ? otcs[oIdx] : undefined;
if (primary !== undefined && otc !== undefined) {
linkedPrimaryIndices.add(primary.index);
// effectiveDate uses the OTC listing's first observed date (listedFrom) for clean
// transfers, or the day after primary.listedTo when the OTC ticker's pre-delist history
// was backfilled (so downstream curation never back-dates the transfer to the IPO date).
const effectiveDate = isBackfilledOtcContinuation(primary, otc, overlapToleranceDays)
? formatUtcDayToIsoDate(primary.listedToDay + 1)
: otc.listedFrom;
// effectiveDate uses the OTC listing's first observed date (listedFrom) so
// downstream backtests and curation never back-date OTC availability before
// OTC trading/quoting actually began.
continuities.push({
fromListingKey: cloneListingKey(primary.key),
toListingKey: cloneListingKey(otc.key),
effectiveDate,
effectiveDate: otc.listedFrom,
kind: CONTINUITY_KIND_OTC_DELIST_TRANSFER,
});
}

View file

@ -71,7 +71,6 @@ export interface ExchangeClassificationResult {
export interface ClassifySourceExchangesOptions {
knownExchanges?: readonly ExchangeSeedRow[];
reviewedRows?: readonly ExchangeSourceMapRow[];
}
const VALID_EXCHANGE_SOURCE_SET: ReadonlySet<string> = new Set(EXCHANGE_SOURCES);
@ -294,15 +293,9 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
{ source: 'eod' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSE ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSE MKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSE NAT', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSEARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSEMKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTC', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCCE', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCGREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCMKTS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCMTKS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCQB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
@ -312,63 +305,19 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
{ source: 'ib' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'BOX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'BYX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CBOE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CBOE2', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CBOT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CDE', role: 'ats_routing' as const, mic: null, countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'CFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CFETAS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CHX', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CME', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'COMEX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'EMERALD', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'FORECASTX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'FUNDSERV', role: 'excluded_fund' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'GEMINI', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBCMDTY', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBDESK', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBFX', role: 'forex' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBKRAM', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBKRATS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBUSCFD', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ICEUS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IDEALPRO', role: 'forex' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ISE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ISLAND', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'LTSE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'MERCURY', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'MIAX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NASDAQBX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NASDAQOM', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'NYBOT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYMEX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSEFLOOR', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSELIFFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSENAT', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'OVERNIGHT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PEARL', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PHLX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PSE', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PURE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'SGXCME', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'SMFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'TRADEWEB', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'VALUE', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'VENTURE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'ZEROHASH', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
// QuoteMedia US + CA venues (qmExchanges has 0% OperatingMIC)
{ source: 'qm' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'AMX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'AQL', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'AQLL', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'ARC', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'ASE', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
@ -383,23 +332,16 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
{ source: 'qm' as const, sourceCode: 'CNX', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CSE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CVE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CVEM', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EDGA', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EXPM', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'GREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'IEX', role: 'primary_venue' as const, mic: 'IEXG', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'MOE', role: 'ats_routing' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NCM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NDD', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'NEOE', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'NGM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NGS', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NMF', role: 'excluded_fund' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NSC', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NSD', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NSQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NYE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
@ -415,7 +357,6 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
{ source: 'qm' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PCX', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PINL', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PNK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'QB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'QX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
@ -423,9 +364,7 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
{ source: 'qm' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSX', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSXC', role: 'composite' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSXV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSXVC', role: 'composite' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'VNX', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
].map(rule => ({
...rule,
@ -484,12 +423,6 @@ export function classifySourceExchanges(
const knownByMic = new Map<string, ExchangeSeedRow>(
knownExchanges.map(exchange => [exchange.mic.trim().toUpperCase(), exchange])
);
const reviewedByKey = new Map<string, ExchangeSourceMapRow>();
if (options.reviewedRows) {
for (const row of options.reviewedRows) {
reviewedByKey.set(makeRuleKey(row.source, row.sourceCode.trim().toUpperCase()), row);
}
}
const grouped = new Map<string, { source: ExchangeSource; sourceCode: string; records: SourceExchangeRecord[] }>();
const unresolved: UnresolvedExchangeRecord[] = [];
@ -562,20 +495,6 @@ export function classifySourceExchanges(
continue;
}
const reviewedRow = reviewedByKey.get(makeRuleKey(group.source, group.sourceCode));
if (reviewedRow) {
mapped.push({
source: reviewedRow.source,
sourceCode: reviewedRow.sourceCode.trim().toUpperCase(),
role: reviewedRow.role,
mic: reviewedRow.mic,
countryIso: reviewedRow.countryIso,
method: reviewedRow.method,
reviewedBy: reviewedRow.reviewedBy ?? null,
});
continue;
}
// Sort group deterministically so duplicate collapse is independent of input order.
const sortedRecords = [...group.records].sort(compareSourceRecordsDeterministically);
const representative = sortedRecords[0];

View file

@ -1,670 +0,0 @@
import { createHash, randomUUID } from 'node:crypto';
import { mkdir, open, rename, unlink } from 'node:fs/promises';
import { join } from 'node:path';
import type { MongoDBClient } from '@stock-bot/mongodb';
/**
* M1 allowlisted MongoDB collections whose concatenated raw BSON documents are consumed by
* `tools/curate-etl` (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`,
* `curate-fx-1d`, `curate-shorts`, `curate-events`).
*/
export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([
'eodPrices',
'qmSplits',
'qmDividends',
'qmPrices',
'teMarketData',
'ceoShorts',
'qmFilings',
'qmEarnings',
] as const);
export type RawBsonExportCollection = (typeof RAW_BSON_EXPORT_COLLECTIONS)[number];
const RAW_BSON_EXPORT_COLLECTION_SET: ReadonlySet<string> = new Set(RAW_BSON_EXPORT_COLLECTIONS);
export const MIN_RAW_BSON_DOC_BYTES = 5;
/** Matches `tools/curate-etl` `bson_stream` ceiling (16 MiB BSON max + 16 KiB wire headroom). */
export const DEFAULT_MAX_RAW_BSON_DOC_BYTES = 16 * 1024 * 1024 + 16 * 1024;
export const DEFAULT_WRITE_BUFFER_BYTES = 8 * 1024 * 1024;
export const MIN_WRITE_BUFFER_BYTES = 64;
export const MAX_WRITE_BUFFER_BYTES = 64 * 1024 * 1024;
export const DEFAULT_RAW_BSON_BATCH_SIZE = 4_096;
export const MAX_RAW_BSON_BATCH_SIZE = 100_000;
export function isRawBsonExportCollection(value: string): value is RawBsonExportCollection {
return RAW_BSON_EXPORT_COLLECTION_SET.has(value);
}
export type RawBsonExportErrorCode =
| 'DISALLOWED_COLLECTION'
| 'INVALID_OPTION'
| 'INVALID_SOURCE'
| 'INVALID_BSON_FRAME';
export interface RawBsonExportErrorOptions {
readonly code: RawBsonExportErrorCode;
readonly collection: string;
readonly docOrdinal?: number;
readonly detail: string;
readonly cause?: unknown;
}
export class RawBsonExportError extends Error {
readonly code: RawBsonExportErrorCode;
readonly collection: string;
readonly docOrdinal?: number;
constructor(options: RawBsonExportErrorOptions) {
const ordinalPart = options.docOrdinal !== undefined ? ` doc#${options.docOrdinal}` : '';
super(
`[${options.code}] ${options.collection}${ordinalPart}: ${options.detail}`,
options.cause !== undefined ? { cause: options.cause } : undefined
);
this.name = 'RawBsonExportError';
this.code = options.code;
this.collection = options.collection;
if (options.docOrdinal !== undefined) {
this.docOrdinal = options.docOrdinal;
}
}
}
export interface RawBsonFindOptions {
readonly raw: true;
readonly batchSize?: number;
readonly limit?: number;
}
export interface ReadOnlyRawBsonCursor extends AsyncIterable<unknown> {
close?(): Promise<unknown>;
}
export interface ReadOnlyRawBsonCollection {
find(filter: Record<string, unknown>, options: RawBsonFindOptions): ReadOnlyRawBsonCursor;
}
export interface ReadOnlyMongoRawBsonClient {
isReadOnly(): boolean;
getCollection(name: string): ReadOnlyRawBsonCollection;
}
export interface ReadOnlyRawBsonSource {
isReadOnly(): boolean;
find(
collectionName: string,
filter: Record<string, unknown>,
options: RawBsonFindOptions
): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
}
// Compile-time structural compatibility check (type-only, erased at runtime):
// verifies the real `MongoDBClient` satisfies `ReadOnlyMongoRawBsonClient`.
type AssertAssignable<Target, _Candidate extends Target> = true;
export type MongoDBClientRawBsonSourceCheck = AssertAssignable<
ReadOnlyMongoRawBsonClient,
MongoDBClient
>;
export interface ExportRawBsonFileHandle {
write(
buffer: Uint8Array,
offset?: number | null,
length?: number | null,
position?: number | null
): Promise<{ bytesWritten: number }>;
sync(): Promise<void>;
close(): Promise<void>;
}
export interface ExportRawBsonFsHooks {
readonly mkdir?: typeof mkdir;
readonly open?: (path: string, flags: string) => Promise<ExportRawBsonFileHandle>;
readonly rename?: typeof rename;
readonly unlink?: typeof unlink;
}
export interface ExportRawBsonCollectionOptions {
readonly collection: string;
readonly outDir: string;
readonly eodSymbol?: string;
readonly teSymbol?: string;
readonly limit?: number;
readonly batchSize?: number;
readonly writeBufferBytes?: number;
readonly maxDocBytes?: number;
readonly fs?: ExportRawBsonFsHooks;
}
export interface ExportRawBsonCollectionResult {
readonly collection: RawBsonExportCollection;
readonly outPath: string;
readonly docsWritten: number;
readonly bytesWritten: number;
readonly elapsedMs: number;
readonly sha256: string;
readonly filter: Readonly<Record<string, string>>;
}
function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
return false;
}
return typeof (value as Partial<Record<symbol, unknown>>)[Symbol.asyncIterator] === 'function';
}
/**
* Adapts a read-only `MongoDBClient` into a streaming `ReadOnlyRawBsonSource`.
* Rejects non-read-only clients and buffered/non-AsyncIterable cursor results, and
* guarantees `cursor.close()` runs in `finally` on completion, early break, or error.
*/
export function createReadOnlyMongoRawBsonSource(
client: ReadOnlyMongoRawBsonClient
): ReadOnlyRawBsonSource {
if (!client || typeof client.isReadOnly !== 'function' || client.isReadOnly() !== true) {
throw new RawBsonExportError({
code: 'INVALID_SOURCE',
collection: '*',
detail: 'MongoDB client must be configured in read-only mode (isReadOnly() === true)',
});
}
return {
isReadOnly(): boolean {
return client.isReadOnly() === true;
},
find(
collectionName: string,
filter: Record<string, unknown>,
options: RawBsonFindOptions
): AsyncIterable<unknown> {
if (client.isReadOnly() !== true) {
throw new RawBsonExportError({
code: 'INVALID_SOURCE',
collection: collectionName,
detail: 'MongoDB client must remain in read-only mode (isReadOnly() === true)',
});
}
if (!options || options.raw !== true) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: 'Raw BSON export requires find option { raw: true }',
});
}
const cursor = client.getCollection(collectionName).find(filter, options);
if (!isAsyncIterable(cursor)) {
throw new RawBsonExportError({
code: 'INVALID_SOURCE',
collection: collectionName,
detail:
'Collection find() must return a streaming AsyncIterable cursor (buffered arrays are not allowed)',
});
}
return {
async *[Symbol.asyncIterator]() {
let hasPrimaryError = false;
try {
for await (const doc of cursor) {
yield doc;
}
} catch (error) {
hasPrimaryError = true;
throw error;
} finally {
if (typeof cursor.close === 'function') {
if (hasPrimaryError) {
try {
await cursor.close();
} catch {
// Preserve primary iteration error when close also fails.
}
} else {
await cursor.close();
}
}
}
},
};
},
};
}
/**
* Validates that a single raw BSON document frame is a `Uint8Array` of length in
* `[5, maxDocBytes]` whose leading signed 32-bit little-endian length prefix equals
* `byteLength` and whose final byte is `0x00`.
*/
export function validateRawBsonFrame(
bytes: unknown,
collection: string,
docOrdinal: number,
maxDocBytes: number = DEFAULT_MAX_RAW_BSON_DOC_BYTES
): Uint8Array {
if (!(bytes instanceof Uint8Array)) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `expected Uint8Array raw BSON frame, got ${bytes === null ? 'null' : typeof bytes}`,
});
}
const byteLength = bytes.byteLength;
if (byteLength < MIN_RAW_BSON_DOC_BYTES) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `frame length ${byteLength} is below minimum BSON document size (${MIN_RAW_BSON_DOC_BYTES})`,
});
}
if (byteLength > maxDocBytes) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `frame length ${byteLength} exceeds maxDocBytes (${maxDocBytes})`,
});
}
const b0 = bytes[0] ?? 0;
const b1 = bytes[1] ?? 0;
const b2 = bytes[2] ?? 0;
const b3 = bytes[3] ?? 0;
const declaredLen = (b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)) | 0;
if (declaredLen !== byteLength) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `4-byte LE length prefix (${declaredLen}) disagrees with frame byteLength (${byteLength})`,
});
}
const lastByte = bytes[byteLength - 1];
if (lastByte !== 0x00) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `missing trailing 0x00 terminator (got 0x${(lastByte ?? 0).toString(16).padStart(2, '0')})`,
});
}
return bytes;
}
/**
* Walks concatenated length-prefixed raw BSON documents using the exact framing rules
* implemented by `tools/curate-etl/src/bson_eod_prices.rs::iter_raw_bson_docs`
* (signed 32-bit LE length prefix `>= 5`, `<= maxDocBytes`, exact buffer bounds, trailing `0x00`).
*/
export function walkRawBsonFrames(
bytes: Uint8Array,
maxDocBytes: number = DEFAULT_MAX_RAW_BSON_DOC_BYTES,
collection: string = '<buffer>'
): Uint8Array[] {
const frames: Uint8Array[] = [];
let offset = 0;
let docOrdinal = 0;
while (offset < bytes.byteLength) {
const remaining = bytes.byteLength - offset;
if (remaining < 4) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `truncated BSON length prefix at byte offset ${offset} (${remaining} bytes remaining)`,
});
}
const b0 = bytes[offset] ?? 0;
const b1 = bytes[offset + 1] ?? 0;
const b2 = bytes[offset + 2] ?? 0;
const b3 = bytes[offset + 3] ?? 0;
const declaredLen = (b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)) | 0;
if (declaredLen < MIN_RAW_BSON_DOC_BYTES) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `corrupt BSON document length ${declaredLen} at byte offset ${offset}`,
});
}
if (declaredLen > maxDocBytes) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `BSON document length ${declaredLen} at byte offset ${offset} exceeds maxDocBytes (${maxDocBytes})`,
});
}
if (declaredLen > remaining) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `truncated BSON document at byte offset ${offset} (declared ${declaredLen}, remaining ${remaining})`,
});
}
const frame = bytes.subarray(offset, offset + declaredLen);
const lastByte = frame[declaredLen - 1];
if (lastByte !== 0x00) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `missing trailing 0x00 terminator at byte offset ${offset}`,
});
}
frames.push(frame);
offset += declaredLen;
docOrdinal += 1;
}
return frames;
}
interface ValidatedExportOptions {
readonly collection: RawBsonExportCollection;
readonly outDir: string;
readonly filter: Readonly<Record<string, string>>;
readonly limit?: number;
readonly batchSize: number;
readonly writeBufferBytes: number;
readonly maxDocBytes: number;
}
function validateExportOptions(options: ExportRawBsonCollectionOptions): ValidatedExportOptions {
const collectionName = typeof options?.collection === 'string' ? options.collection : '';
if (!isRawBsonExportCollection(collectionName)) {
throw new RawBsonExportError({
code: 'DISALLOWED_COLLECTION',
collection: collectionName || '<empty>',
detail: `collection "${collectionName}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`,
});
}
if (typeof options.outDir !== 'string' || options.outDir.trim().length === 0) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: 'outDir must be a non-empty string',
});
}
const writeBufferBytes = options.writeBufferBytes ?? DEFAULT_WRITE_BUFFER_BYTES;
if (
!Number.isSafeInteger(writeBufferBytes) ||
writeBufferBytes < MIN_WRITE_BUFFER_BYTES ||
writeBufferBytes > MAX_WRITE_BUFFER_BYTES
) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: `writeBufferBytes must be an integer in [${MIN_WRITE_BUFFER_BYTES}, ${MAX_WRITE_BUFFER_BYTES}] (got ${String(writeBufferBytes)})`,
});
}
const maxDocBytes = options.maxDocBytes ?? DEFAULT_MAX_RAW_BSON_DOC_BYTES;
if (
!Number.isSafeInteger(maxDocBytes) ||
maxDocBytes < MIN_RAW_BSON_DOC_BYTES ||
maxDocBytes > MAX_WRITE_BUFFER_BYTES
) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: `maxDocBytes must be an integer in [${MIN_RAW_BSON_DOC_BYTES}, ${MAX_WRITE_BUFFER_BYTES}] (got ${String(maxDocBytes)})`,
});
}
const batchSize = options.batchSize ?? DEFAULT_RAW_BSON_BATCH_SIZE;
if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > MAX_RAW_BSON_BATCH_SIZE) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: `batchSize must be an integer in [1, ${MAX_RAW_BSON_BATCH_SIZE}] (got ${String(batchSize)})`,
});
}
let limit: number | undefined;
if (options.limit !== undefined) {
if (!Number.isSafeInteger(options.limit) || options.limit < 1) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: `limit must be a positive safe integer (got ${String(options.limit)})`,
});
}
limit = options.limit;
}
let filter: Record<string, string> = {};
if (options.eodSymbol !== undefined) {
if (collectionName !== 'eodPrices') {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: '--eod-symbol filter is only permitted for collection "eodPrices"',
});
}
if (typeof options.eodSymbol !== 'string' || options.eodSymbol.trim().length === 0) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: 'eodSymbol must be a non-empty string',
});
}
filter = { eodSearchCode: options.eodSymbol };
}
if (options.teSymbol !== undefined) {
if (collectionName !== 'teMarketData') {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: '--te-symbol filter is only permitted for collection "teMarketData"',
});
}
if (typeof options.teSymbol !== 'string' || options.teSymbol.trim().length === 0) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: 'teSymbol must be a non-empty string',
});
}
filter = { teSymbol: options.teSymbol };
}
return {
collection: collectionName,
outDir: options.outDir.trim(),
filter: Object.freeze(filter),
...(limit !== undefined ? { limit } : {}),
batchSize,
writeBufferBytes,
maxDocBytes,
};
}
async function writeAll(
handle: ExportRawBsonFileHandle,
buffer: Uint8Array,
length: number,
collection: string,
tempPath: string
): Promise<void> {
let offset = 0;
while (offset < length) {
const remaining = length - offset;
const result = await handle.write(buffer, offset, remaining);
if (
!result ||
typeof result.bytesWritten !== 'number' ||
!Number.isInteger(result.bytesWritten) ||
result.bytesWritten <= 0
) {
throw new Error(
`Short write (bytesWritten=${String(result?.bytesWritten)}) while exporting "${collection}" to ${tempPath}`
);
}
if (result.bytesWritten > remaining) {
throw new Error(
`Write hook reported bytesWritten=${result.bytesWritten} exceeding requested length=${remaining} while exporting "${collection}" to ${tempPath}`
);
}
offset += result.bytesWritten;
}
}
/**
* Streams an allowlisted MongoDB collection as untouched raw BSON frames into
* `<outDir>/<collection>.bson` using a fixed-size write buffer, incremental SHA-256 hashing,
* and atomic same-directory temp-file publish (`open('wx')` -> `write` -> `sync` -> `close` -> `rename`).
*/
export async function exportRawBsonCollection(
source: ReadOnlyRawBsonSource,
options: ExportRawBsonCollectionOptions
): Promise<ExportRawBsonCollectionResult> {
const validated = validateExportOptions(options);
if (
!source ||
typeof source.isReadOnly !== 'function' ||
source.isReadOnly() !== true ||
typeof source.find !== 'function'
) {
throw new RawBsonExportError({
code: 'INVALID_SOURCE',
collection: validated.collection,
detail: 'Raw BSON exporter requires a read-only source (isReadOnly() === true)',
});
}
const mkdirFn = options.fs?.mkdir ?? mkdir;
const openFn: (path: string, flags: string) => Promise<ExportRawBsonFileHandle> =
options.fs?.open ?? ((filePath: string, flags: string) => open(filePath, flags));
const renameFn = options.fs?.rename ?? rename;
const unlinkFn = options.fs?.unlink ?? unlink;
const startMs = performance.now();
await mkdirFn(validated.outDir, { recursive: true });
const outPath = join(validated.outDir, `${validated.collection}.bson`);
const tempPath = join(
validated.outDir,
`.${validated.collection}.bson.${process.pid}.${randomUUID()}.tmp`
);
const handle = await openFn(tempPath, 'wx');
let handleClosed = false;
let renamed = false;
const writeBuffer = new Uint8Array(validated.writeBufferBytes);
let buffered = 0;
const hash = createHash('sha256');
let docsWritten = 0;
let bytesWritten = 0;
const flushBuffer = async (): Promise<void> => {
if (buffered > 0) {
await writeAll(handle, writeBuffer, buffered, validated.collection, tempPath);
buffered = 0;
}
};
try {
const findOptions: RawBsonFindOptions = {
raw: true,
batchSize: validated.batchSize,
...(validated.limit !== undefined ? { limit: validated.limit } : {}),
};
const iterable = await source.find(
validated.collection,
{ ...validated.filter },
findOptions
);
if (!isAsyncIterable(iterable)) {
throw new RawBsonExportError({
code: 'INVALID_SOURCE',
collection: validated.collection,
detail:
'Source find() must return a streaming AsyncIterable (buffered arrays are not allowed)',
});
}
for await (const rawDoc of iterable) {
if (validated.limit !== undefined && docsWritten >= validated.limit) {
break;
}
const frame = validateRawBsonFrame(
rawDoc,
validated.collection,
docsWritten,
validated.maxDocBytes
);
const frameLen = frame.byteLength;
hash.update(frame);
if (frameLen > validated.writeBufferBytes) {
await flushBuffer();
await writeAll(handle, frame, frameLen, validated.collection, tempPath);
} else {
if (buffered + frameLen > validated.writeBufferBytes) {
await flushBuffer();
}
writeBuffer.set(frame, buffered);
buffered += frameLen;
}
docsWritten += 1;
bytesWritten += frameLen;
if (validated.limit !== undefined && docsWritten >= validated.limit) {
break;
}
}
await flushBuffer();
await handle.sync();
await handle.close();
handleClosed = true;
await renameFn(tempPath, outPath);
renamed = true;
} catch (error) {
if (!handleClosed) {
await handle.close().catch(() => {});
}
if (!renamed) {
await unlinkFn(tempPath).catch(() => {});
}
throw error;
}
const elapsedMs = Math.max(0, performance.now() - startMs);
return {
collection: validated.collection,
outPath,
docsWritten,
bytesWritten,
elapsedMs,
sha256: hash.digest('hex'),
filter: validated.filter,
};
}

View file

@ -47,100 +47,6 @@ export {
type UnresolvedExchangeRecord,
} from './exchange-pass1';
export {
buildDelistingExportRows,
CURATE_INPUT_CURRENT_LINK,
CURATE_INPUT_FILES,
CURATE_INPUT_GENERATIONS_DIR,
CURATE_INPUT_PUBLISH_LOCK,
CurateInputExportError,
DEFAULT_DELISTING_MAPPING_SOURCE,
DEFAULT_EXPORT_CHUNK_SIZE,
DEFAULT_PUBLISH_LOCK_TIMEOUT_MS,
exportCurateInputs,
formatDelistingsTsv,
formatListingCurrenciesTsv,
formatPlainDecimal,
formatProviderMappingTsv,
isValidStrictYmd,
MAX_EXPORT_CHUNK_SIZE,
pinCurateInputSnapshot,
type BuildDelistingExportRowsOptions,
type BuildDelistingExportRowsResult,
type ContinuityExportSourceRow,
type CurateInputExportErrorCode,
type CurateInputExportErrorOptions,
type DelistingExportRow,
type DelistingExportSkippedByReason,
type DelistingExportStats,
type ExportCurateInputsFileStats,
type ExportCurateInputsFsHooks,
type ExportCurateInputsOptions,
type ExportCurateInputsResult,
type ListingCurrencyExportRow,
type ListingDelistingSourceRow,
type PinnedCurateInputSnapshot,
type ProviderMappingExportRow,
} from './export-curate-inputs';
export {
assertExportCurateInputsSafety,
EXPORT_CURATE_INPUTS_USAGE,
formatExportCurateInputsSummary,
parseExportCurateInputsArgs,
runCli as runExportCurateInputsCli,
runExportCurateInputs,
type ParsedExportCurateInputsArgs,
type RunExportCurateInputsDeps,
type RunExportCurateInputsOptions,
type RunExportCurateInputsOutput,
} from './run-export-curate-inputs';
export {
createReadOnlyMongoRawBsonSource,
DEFAULT_MAX_RAW_BSON_DOC_BYTES,
DEFAULT_RAW_BSON_BATCH_SIZE,
DEFAULT_WRITE_BUFFER_BYTES,
exportRawBsonCollection,
isRawBsonExportCollection,
MAX_RAW_BSON_BATCH_SIZE,
MAX_WRITE_BUFFER_BYTES,
MIN_RAW_BSON_DOC_BYTES,
MIN_WRITE_BUFFER_BYTES,
RAW_BSON_EXPORT_COLLECTIONS,
RawBsonExportError,
validateRawBsonFrame,
walkRawBsonFrames,
type ExportRawBsonCollectionOptions,
type ExportRawBsonCollectionResult,
type ExportRawBsonFileHandle,
type ExportRawBsonFsHooks,
type MongoDBClientRawBsonSourceCheck,
type RawBsonExportCollection,
type RawBsonExportErrorCode,
type RawBsonExportErrorOptions,
type RawBsonFindOptions,
type ReadOnlyMongoRawBsonClient,
type ReadOnlyRawBsonCollection,
type ReadOnlyRawBsonCursor,
type ReadOnlyRawBsonSource,
} from './export-raw-bson';
export {
assertExportRawBsonSafety,
EXPORT_RAW_BSON_USAGE,
formatExportRawBsonSummary,
parseExportRawBsonArgs,
runCli as runExportRawBsonCli,
runExportRawBson,
type ParsedExportRawBsonArgs,
type RawBsonMongoHandle,
type RunExportRawBsonCliOverrides,
type RunExportRawBsonDeps,
type RunExportRawBsonOptions,
type RunExportRawBsonOutput,
} from './run-export-raw-bson';
export {
escapeSqlLiteral,
generateExchangeSeedSql,
@ -359,47 +265,6 @@ export {
type UnknownSecurityTypeCount,
} from './security-type';
export {
parseProbeSourceFieldShapesArgs,
PROBE_SOURCE_FIELD_SHAPES_USAGE,
runCli as runProbeSourceFieldShapesCli,
runSourceFieldShapesProbe,
type ParsedProbeSourceFieldShapesArgs,
type RunSourceFieldShapesProbeDeps,
type RunSourceFieldShapesProbeOptions,
type RunSourceFieldShapesProbeOutput,
} from './probe-source-field-shapes';
export {
DEFAULT_FIELD_SHAPE_LIMIT,
DEFAULT_MAX_EXAMPLE_LENGTH,
DEFAULT_MAX_EXAMPLES,
FIELD_SHAPE_PROBE_COLLECTIONS,
FIELD_VALUE_TYPES,
isFieldShapeProbeCollection,
MAX_EXAMPLE_LENGTH_CAP,
MAX_EXAMPLES_CAP,
MAX_FIELD_SHAPE_LIMIT,
normalizeProbeCollections,
readFieldShapes,
renderFieldShapesMarkdown,
STRING_PATTERN_CLASSES,
summarizeFieldShapes,
UnknownProbeCollectionError,
type CollectionFieldShapesProbeResult,
type CollectionFieldShapesSummary,
type FieldShapeProbeCollection,
type FieldShapeSummary,
type FieldStringStats,
type FieldValueType,
type FieldValueTypeCounts,
type ReadFieldShapesOptions,
type ReadFieldShapesResult,
type StringPatternClass,
type StringPatternCounts,
type SummarizeFieldShapesOptions,
} from './source-field-shapes';
export {
adaptCeoSymbolDoc,
adaptEodSymbolChangeDoc,

View file

@ -9,15 +9,9 @@ import { compareAscii } from './exchange-pass1';
export const STAGE_A_SOURCES = ['ib', 'eod'] as const;
export const SYNTHETIC_EOD_ISIN_PREFIX = 'SYN:EOD:' as const;
export function isSyntheticInstrumentKey(value: string): boolean {
return value.startsWith(SYNTHETIC_EOD_ISIN_PREFIX);
}
export type StageASource = (typeof STAGE_A_SOURCES)[number];
export type StageAMatchMethod = 'tier1_isin' | 'tier2_cusip' | 'tier3_ticker_span';
export type StageAMatchMethod = 'tier1_isin' | 'tier2_cusip';
export type StageAConflictKind = 'isin_cusip_mismatch' | 'duplicate_source_id';
@ -70,7 +64,6 @@ export interface StageASourceStats {
total: number;
tier1Isin: number;
tier2Cusip: number;
tier3Synthetic?: number;
unresolved: number;
conflict: number;
}
@ -83,7 +76,6 @@ export interface StageAStats {
export interface MatchInstrumentsStageAOptions {
readonly nameSourcePrecedence?: readonly StageASource[];
readonly allowIdentifierlessEod?: boolean;
}
export interface StageAMatchResult {
@ -101,7 +93,6 @@ interface BestSourceName {
interface InstrumentAccumulator {
members: StageAInstrumentMember[];
bestNameBySource: Record<StageASource, BestSourceName | null>;
fallbackCountry: string | null;
}
export function isStageASource(value: unknown): value is StageASource {
@ -239,45 +230,6 @@ export function matchInstrumentsStageA(
const resolved = resolveIsin(record);
if (resolved.isin === null) {
if (options.allowIdentifierlessEod === true && source === 'eod') {
const syntheticKey = `${SYNTHETIC_EOD_ISIN_PREFIX}${sourceId.trim().toUpperCase()}`;
const normalizedCountry = normalizeCode(record.country);
const fallbackCountry =
normalizedCountry !== null && /^[A-Z]{2}$/.test(normalizedCountry)
? normalizedCountry
: sourceId.endsWith('.TO') ||
sourceId.endsWith('.V') ||
sourceId.endsWith('.NEO') ||
sourceId.endsWith('.CN')
? 'CA'
: 'US';
const currency = normalizeCode(record.currency);
const name = normalizeName(record.name);
let acc = instrumentsByIsin.get(syntheticKey);
if (acc === undefined) {
acc = {
members: [],
bestNameBySource: { ib: null, eod: null },
fallbackCountry,
};
instrumentsByIsin.set(syntheticKey, acc);
}
acc.members.push({
source,
sourceId,
currency,
method: 'tier3_ticker_span',
});
if (name !== null) {
const existingBest = acc.bestNameBySource[source];
if (existingBest === null || compareAscii(sourceId, existingBest.sourceId) < 0) {
acc.bestNameBySource[source] = { sourceId, name };
}
}
sourceStats.tier3Synthetic = (sourceStats.tier3Synthetic ?? 0) + 1;
continue;
}
unresolved.push({
source,
sourceId,
@ -334,7 +286,6 @@ export function matchInstrumentsStageA(
ib: null,
eod: null,
},
fallbackCountry: null,
};
instrumentsByIsin.set(resolved.isin, acc);
}
@ -362,13 +313,10 @@ export function matchInstrumentsStageA(
const instruments: StageAInstrumentCandidate[] = [];
for (const [primaryIsin, acc] of instrumentsByIsin.entries()) {
const isSynthetic = isSyntheticInstrumentKey(primaryIsin);
const issuerCountry = isSynthetic ? (acc.fallbackCountry ?? 'US') : primaryIsin.slice(0, 2);
const embeddedCusip = isSynthetic ? '' : primaryIsin.slice(2, 11);
const issuerCountry = primaryIsin.slice(0, 2);
const embeddedCusip = primaryIsin.slice(2, 11);
const primaryCusip =
!isSynthetic && isNorthAmericaCountry(issuerCountry) && isValidCusip(embeddedCusip)
? embeddedCusip
: null;
isNorthAmericaCountry(issuerCountry) && isValidCusip(embeddedCusip) ? embeddedCusip : null;
let canonicalName: string | null = null;
for (const source of nameSourcePrecedence) {

View file

@ -6,11 +6,10 @@ import {
} from '../normalization/bar-spans';
import { parseTickerDetailed } from '../normalization/ticker';
import { compareAscii, type ExchangeRole } from './exchange-pass1';
import {
isSyntheticInstrumentKey,
type StageAInstrumentCandidate,
type StageAMatchMethod,
type StageASource,
import type {
StageAInstrumentCandidate,
StageAMatchMethod,
StageASource,
} from './instrument-stage-a';
export const MAX_TICKER_ROOT_LENGTH = 24;
@ -45,9 +44,6 @@ export interface StageBIbContractInput {
conid: number;
currency?: string | null;
primaryExchange: string | null;
ticker?: string | null;
name?: string | null;
exchangeId?: string | null;
}
export interface StageBTickerSourceInput {
@ -58,7 +54,6 @@ export interface StageBTickerSourceInput {
role: ExchangeRole | null;
currency?: string | null;
span: SpanDateRange | null;
name?: string | null;
}
export interface StageBSymbolChangeInput {
@ -82,8 +77,6 @@ export interface StageBInput {
export interface MatchListingsStageBOptions {
readonly spanOverlapToleranceDays?: number;
readonly enableIbTickerDisambiguation?: boolean;
readonly allowUniqueTickerFallbackForCrawlOnlyCeo?: boolean;
}
export interface StageBListingCandidate extends ListingNaturalKey {
@ -208,7 +201,7 @@ interface StagedIbCandidate {
currency: string;
conid: number;
primaryExchange: string | null;
method: StageBMatchMethod;
method: StageAMatchMethod;
}
const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/;
@ -223,15 +216,8 @@ function isStageASourceValue(value: unknown): value is StageASource {
return value === 'ib' || value === 'eod';
}
function isStageAMatchMethodValue(
value: unknown,
allowSyntheticTier3 = false
): value is StageAMatchMethod {
return (
value === 'tier1_isin' ||
value === 'tier2_cusip' ||
(allowSyntheticTier3 && value === 'tier3_ticker_span')
);
function isStageAMatchMethodValue(value: unknown): value is StageAMatchMethod {
return value === 'tier1_isin' || value === 'tier2_cusip';
}
function isStageBTickerSourceValue(value: unknown): value is StageBTickerSource {
@ -672,8 +658,7 @@ export function matchListingsStageB(
`Invalid empty or non-string sourceId at instruments[${i}].members[${j}]`
);
}
const isSyntheticInst = isSyntheticInstrumentKey(inst.primaryIsin);
if (!isStageAMatchMethodValue(member.method, isSyntheticInst)) {
if (!isStageAMatchMethodValue(member.method)) {
throw new Error(
`Unknown Stage A member method "${String(member.method)}" at instruments[${i}].members[${j}]`
);
@ -880,11 +865,7 @@ export function matchListingsStageB(
const listingsByNaturalKey = new Map<string, ListingAccumulator>();
const listingsByInstrumentCurrency = new Map<string, Map<string, ListingAccumulator[]>>();
const listingsByTickerKey = new Map<string, TickerLookupCandidate[]>();
const listingsByCurrencyTickerKey = new Map<string, ListingAccumulator[]>();
const listingByEodSourceId = new Map<string, ListingAccumulator>();
const enableIbTickerDisambiguation = options.enableIbTickerDisambiguation === true;
const allowUniqueTickerFallbackForCrawlOnlyCeo =
options.allowUniqueTickerFallbackForCrawlOnlyCeo === true;
const providerMappings: StageBProviderMappingCandidate[] = [];
const unresolved: StageBUnresolvedRecord[] = [];
@ -1025,14 +1006,6 @@ export function matchListingsStageB(
listingsByTickerKey.set(tickerKey, tickerList);
}
tickerList.push({ acc, aliasBounds: null });
const currTickerKey = `${currency}\u0000${ticker.tickerRoot}\u0000${ticker.classSuffix}`;
let currTickerList = listingsByCurrencyTickerKey.get(currTickerKey);
if (currTickerList === undefined) {
currTickerList = [];
listingsByCurrencyTickerKey.set(currTickerKey, currTickerList);
}
currTickerList.push(acc);
} else if (validSpan !== null) {
// Associative & commutative min/max widening ensures shuffle invariance.
if (acc.listedFrom === null || validSpan.firstBarDate < acc.listedFrom) {
@ -1170,84 +1143,7 @@ export function matchListingsStageB(
}
const primaryExchange = normalizeOptionalExchangeLabel(contract.primaryExchange);
let candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency);
let matchMethod: StageBMatchMethod = member.method;
const isActiveCandidate = (acc: ListingAccumulator): boolean =>
acc.listedTo === null || acc.listedTo >= '2025-01-01';
const narrowIbCandidates = (
pool: readonly ListingAccumulator[],
parsedTicker: { readonly tickerRoot: string; readonly classSuffix: string } | null
): ListingAccumulator[] => {
let current = [...pool];
if (current.length > 1 && parsedTicker !== null) {
const exactTicker = current.filter(
acc =>
acc.key.tickerRoot === parsedTicker.tickerRoot &&
acc.key.classSuffix === parsedTicker.classSuffix
);
if (exactTicker.length > 0) {
current = exactTicker;
}
}
if (current.length > 1) {
const activeOnly = current.filter(isActiveCandidate);
if (activeOnly.length > 0) {
current = activeOnly;
}
}
if (current.length > 1) {
const primaryOnly = current.filter(acc => acc.key.mic !== 'OTCM');
if (primaryOnly.length > 0) {
current = primaryOnly;
}
}
return current;
};
const parsedIbTicker =
enableIbTickerDisambiguation && typeof contract.ticker === 'string'
? (() => {
const parsed = classifyTicker(contract.ticker, 'ib');
return parsed.ok
? { tickerRoot: parsed.tickerRoot, classSuffix: parsed.classSuffix }
: null;
})()
: null;
if (enableIbTickerDisambiguation && candidates !== undefined && candidates.length > 1) {
candidates = narrowIbCandidates(candidates, parsedIbTicker);
}
if (
enableIbTickerDisambiguation &&
(candidates === undefined || candidates.length === 0) &&
parsedIbTicker !== null
) {
const currTickerKey = `${currency}\u0000${parsedIbTicker.tickerRoot}\u0000${parsedIbTicker.classSuffix}`;
const tickerPool = listingsByCurrencyTickerKey.get(currTickerKey);
if (tickerPool !== undefined && tickerPool.length > 0) {
const ibIssuerPrefix = !isSyntheticInstrumentKey(inst.primaryIsin)
? inst.primaryIsin.slice(0, 8)
: null;
const eligibleFallback = tickerPool.filter(
acc =>
isSyntheticInstrumentKey(acc.key.primaryIsin) ||
(ibIssuerPrefix !== null &&
!isSyntheticInstrumentKey(acc.key.primaryIsin) &&
acc.key.primaryIsin.slice(0, 8) === ibIssuerPrefix) ||
isActiveCandidate(acc)
);
if (eligibleFallback.length > 0) {
const narrowed = narrowIbCandidates(eligibleFallback, parsedIbTicker);
if (narrowed.length === 1) {
candidates = narrowed;
matchMethod = 'tier3_ticker_span';
}
}
}
}
const candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency);
if (candidates === undefined || candidates.length === 0) {
unresolved.push({
@ -1294,7 +1190,7 @@ export function matchListingsStageB(
currency,
conid: contract.conid,
primaryExchange,
method: matchMethod,
method: member.method,
});
}
}
@ -1587,29 +1483,6 @@ export function matchListingsStageB(
primaryIsin: null,
});
sourceStats.unresolved += 1;
} else if (
allowUniqueTickerFallbackForCrawlOnlyCeo &&
source === 'ceo' &&
spanCheck.span.firstBarDate === spanCheck.span.lastBarDate &&
candidates.length === 1 &&
candidates[0] !== undefined &&
candidates[0].aliasBounds === null &&
candidates[0].acc.listedFrom !== null &&
candidates[0].acc.listedTo !== null
) {
// CEO symbols without ceoShorts history carry only a single-day crawl `lastSeen` date;
// when there is a single unique EOD listing for `(mic, currency, ticker)` with zero ticker
// reuse, attach cleanly using that listing's observed span.
const uniqueListing = candidates[0].acc;
providerMappings.push({
source,
sourceId: record.sourceId,
listingKey: uniqueListing.key,
method: 'tier3_ticker_span',
validFrom: uniqueListing.listedFrom,
validTo: uniqueListing.listedTo,
});
sourceStats.matched += 1;
} else {
unresolved.push({
source,

View file

@ -36,13 +36,6 @@ export type ExcludedByDesignStageBReason = (typeof EXCLUDED_BY_DESIGN_STAGE_B_RE
export type SourceCountryLookup = ReadonlyMap<string, string> | Readonly<Record<string, string>>;
export type GateOutOfScopeReason =
| 'zero_bar_catalog_ghost'
| 'uncovered_venue'
| 'non_equity_instrument';
export type GateOutOfScopeLookup = ReadonlyMap<string, GateOutOfScopeReason>;
export interface MatchReportInput {
readonly exchanges?: ExchangeClassificationResult;
readonly stageA: StageAMatchResult;
@ -50,13 +43,10 @@ export interface MatchReportInput {
readonly priceCrossCheck?: PriceCrossCheckResult;
readonly delistingChains?: DelistingChainResult;
readonly sourceCountries?: SourceCountryLookup;
readonly gateOutOfScope?: GateOutOfScopeLookup;
readonly gateDenominatorNote?: string;
}
export interface BuildMatchReportOptions {
readonly minResolvedPct?: number;
readonly applyUsCaEquityGateDenominator?: boolean;
}
export interface ExchangeCoverageSummary {
@ -83,7 +73,6 @@ export interface SourceResolutionSummary {
unresolved: number;
conflict: number;
excludedByDesign: number;
outOfGateScope?: number;
eligibleTotal: number;
resolvedPct: number | null;
eligibleResolvedPct: number | null;
@ -152,8 +141,6 @@ export interface MatchReport {
resolutionBySource: SourceResolutionSummary[];
resolutionByCountry: CountryResolutionSummary[];
unresolvedByReason: UnresolvedBreakdown;
outOfGateScopeByReason?: UnresolvedBreakdownRow[];
gateDenominatorNote?: string;
conflicts: UnifiedConflictRow[];
conflictsByPassKind: ConflictCountRow[];
priceCrossCheck: PriceCrossCheckSummary | null;
@ -517,62 +504,16 @@ export function buildMatchReport(
qm: 0,
ceo: 0,
};
const outOfGateScopeBySource: Record<StageBSource, number> = {
eod: 0,
ib: 0,
qm: 0,
ceo: 0,
};
const outOfGateScopeCounts = new Map<string, number>();
const hasGateOutOfScope = input.gateOutOfScope !== undefined && input.gateOutOfScope.size > 0;
for (const record of input.stageB.unresolved) {
if (EXCLUDED_BY_DESIGN_SET.has(record.reason)) {
excludedBySource[record.source] += 1;
} else if (hasGateOutOfScope) {
const gateReason = input.gateOutOfScope?.get(sourceCountryKey(record.source, record.sourceId));
if (gateReason !== undefined) {
outOfGateScopeBySource[record.source] += 1;
const k = `${record.source}\u0000${gateReason}`;
outOfGateScopeCounts.set(k, (outOfGateScopeCounts.get(k) ?? 0) + 1);
}
}
}
if (hasGateOutOfScope) {
const countedConflictKeys = new Set<string>();
for (const conflict of input.stageB.conflicts) {
const key = sourceCountryKey(conflict.source, conflict.sourceId);
if (countedConflictKeys.has(key)) {
continue;
}
countedConflictKeys.add(key);
const gateReason = input.gateOutOfScope?.get(key);
if (gateReason !== undefined) {
outOfGateScopeBySource[conflict.source] += 1;
const k = `${conflict.source}\u0000${gateReason}`;
outOfGateScopeCounts.set(k, (outOfGateScopeCounts.get(k) ?? 0) + 1);
}
}
}
const outOfGateScopeByReason: UnresolvedBreakdownRow[] = Array.from(
outOfGateScopeCounts.entries()
)
.map(([key, count]) => {
const sep = key.indexOf('\u0000');
return {
source: key.slice(0, sep),
reason: key.slice(sep + 1),
count,
};
})
.sort((a, b) => compareAscii(a.source, b.source) || compareAscii(a.reason, b.reason));
const resolutionBySource: SourceResolutionSummary[] = STAGE_B_SOURCES.map(source => {
const stats = input.stageB.stats.bySource[source];
const excludedByDesign = excludedBySource[source];
const outOfGateScope = outOfGateScopeBySource[source];
const eligibleTotal = Math.max(0, stats.total - excludedByDesign - outOfGateScope);
const eligibleTotal = Math.max(0, stats.total - excludedByDesign);
return {
source,
total: stats.total,
@ -580,7 +521,6 @@ export function buildMatchReport(
unresolved: stats.unresolved,
conflict: stats.conflict,
excludedByDesign,
...(hasGateOutOfScope ? { outOfGateScope } : {}),
eligibleTotal,
resolvedPct: stats.total > 0 ? stats.matched / stats.total : null,
eligibleResolvedPct: eligibleTotal > 0 ? stats.matched / eligibleTotal : null,
@ -675,10 +615,6 @@ export function buildMatchReport(
resolutionBySource,
resolutionByCountry,
unresolvedByReason,
...(hasGateOutOfScope ? { outOfGateScopeByReason } : {}),
...(input.gateDenominatorNote !== undefined
? { gateDenominatorNote: input.gateDenominatorNote }
: {}),
conflicts,
conflictsByPassKind,
priceCrossCheck,
@ -733,48 +669,18 @@ export function renderMatchReportMarkdown(
lines.push('| 0 | 0 | 0 | N/A |');
}
if (report.gateDenominatorNote !== undefined && report.gateDenominatorNote.trim().length > 0) {
lines.push('', '## Gate Denominator Definition', '', report.gateDenominatorNote);
}
const showGateScopeColumn = report.outOfGateScopeByReason !== undefined;
lines.push(
'',
'## Per-Source Resolution',
'',
showGateScopeColumn
? '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Out of Gate Scope | Eligible Total | Resolved % | Eligible Resolved % |'
: '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |',
showGateScopeColumn
? '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |'
: '| --- | --- | --- | --- | --- | --- | --- | --- | --- |'
'| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |',
'| --- | --- | --- | --- | --- | --- | --- | --- | --- |'
);
for (const row of report.resolutionBySource) {
if (showGateScopeColumn) {
lines.push(
`| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.outOfGateScope ?? 0} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |`
);
} else {
lines.push(
`| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |`
);
}
}
if (report.outOfGateScopeByReason !== undefined && report.outOfGateScopeByReason.length > 0) {
lines.push(
'',
'## Out-of-Gate-Scope Breakdown',
'',
'| Source | Reason | Count |',
'| --- | --- | --- |'
`| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |`
);
for (const row of report.outOfGateScopeByReason) {
lines.push(
`| ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.reason)} | ${row.count} |`
);
}
}
if (report.resolutionByCountry.length > 0) {

View file

@ -16,13 +16,11 @@ import type {
Pass6DelistReason,
} from './delisting-chains';
import { compareAscii } from './exchange-pass1';
import {
isSyntheticInstrumentKey,
SYNTHETIC_EOD_ISIN_PREFIX,
type StageAInstrumentCandidate,
type StageAInstrumentMember,
type StageAMatchResult,
type StageASource,
import type {
StageAInstrumentCandidate,
StageAInstrumentMember,
StageAMatchResult,
StageASource,
} from './instrument-stage-a';
import type {
ListingNaturalKey,
@ -245,8 +243,6 @@ interface ExistingPass4ConflictRow {
interface PreparedInstrument {
readonly primaryIsin: string;
readonly isSynthetic: boolean;
readonly syntheticSourceId: string | null;
readonly primaryCusip: string | null;
readonly canonicalName: string;
readonly securityType: SecurityType;
@ -664,16 +660,9 @@ async function persistWithinTransaction(
skippedInstrumentIsins.add(candidate.primaryIsin);
continue;
}
const isSynthetic = isSyntheticInstrumentKey(candidate.primaryIsin);
const syntheticSourceId = isSynthetic
? (candidate.members.find(m => m.source === 'eod')?.sourceId ??
candidate.primaryIsin.slice(SYNTHETIC_EOD_ISIN_PREFIX.length))
: null;
preparedInstruments.push({
primaryIsin: candidate.primaryIsin,
isSynthetic,
syntheticSourceId,
primaryCusip: isSynthetic ? null : candidate.primaryCusip,
primaryCusip: candidate.primaryCusip,
canonicalName: trimmedName,
securityType,
issuerCountry: candidate.issuerCountry,
@ -683,11 +672,8 @@ async function persistWithinTransaction(
if (preparedInstruments.length > 0) {
const existingByIsin = new Map<string, ExistingInstrumentRow>();
const realInstruments = preparedInstruments.filter(item => !item.isSynthetic);
const syntheticInstruments = preparedInstruments.filter(item => item.isSynthetic);
for (let offset = 0; offset < realInstruments.length; offset += chunkSize) {
const slice = realInstruments.slice(offset, offset + chunkSize);
for (let offset = 0; offset < preparedInstruments.length; offset += chunkSize) {
const slice = preparedInstruments.slice(offset, offset + chunkSize);
const isins = slice.map(item => item.primaryIsin);
const res = await client.query<ExistingInstrumentRow>(
`SELECT
@ -706,70 +692,13 @@ async function persistWithinTransaction(
}
}
for (let offset = 0; offset < syntheticInstruments.length; offset += chunkSize) {
const slice = syntheticInstruments.slice(offset, offset + chunkSize);
const sourceIdToKey = new Map<string, string>();
const sourceIds: string[] = [];
for (const item of slice) {
if (item.syntheticSourceId !== null) {
sourceIdToKey.set(item.syntheticSourceId, item.primaryIsin);
sourceIds.push(item.syntheticSourceId);
}
}
if (sourceIds.length === 0) {
continue;
}
const res = await client.query<{
source_id: string;
instrument_id: number;
primary_cusip: string | null;
canonical_name: string;
security_type: string;
issuer_country: string | null;
}>(
`SELECT DISTINCT ON (pm.source_id)
pm.source_id,
i.instrument_id,
btrim(i.primary_cusip) AS primary_cusip,
i.canonical_name,
i.security_type,
btrim(i.issuer_country) AS issuer_country
FROM provider_mapping pm
JOIN listing l ON l.listing_id = pm.listing_id
JOIN instrument i ON i.instrument_id = l.instrument_id
WHERE pm.source = 'eod'
AND pm.source_id = ANY($1::text[])
AND i.primary_isin IS NULL
ORDER BY pm.source_id, pm.valid_from ASC`,
[sourceIds]
);
for (const row of res.rows) {
const key = sourceIdToKey.get(row.source_id);
if (key !== undefined) {
existingByIsin.set(key, {
instrument_id: row.instrument_id,
primary_isin: key,
primary_cusip: row.primary_cusip,
canonical_name: row.canonical_name,
security_type: row.security_type,
issuer_country: row.issuer_country,
});
}
}
}
const toInsertReal: PreparedInstrument[] = [];
const toInsertSynthetic: PreparedInstrument[] = [];
const toInsert: PreparedInstrument[] = [];
const toUpdate: Array<{ instrumentId: number; item: PreparedInstrument }> = [];
for (const item of preparedInstruments) {
const existing = existingByIsin.get(item.primaryIsin);
if (existing === undefined) {
if (item.isSynthetic) {
toInsertSynthetic.push(item);
} else {
toInsertReal.push(item);
}
toInsert.push(item);
continue;
}
instrumentIdByIsin.set(item.primaryIsin, existing.instrument_id);
@ -785,8 +714,8 @@ async function persistWithinTransaction(
}
}
for (let offset = 0; offset < toInsertReal.length; offset += chunkSize) {
const slice = toInsertReal.slice(offset, offset + chunkSize);
for (let offset = 0; offset < toInsert.length; offset += chunkSize) {
const slice = toInsert.slice(offset, offset + chunkSize);
const res = await client.query<InsertedInstrumentRow>(
`INSERT INTO instrument (
primary_isin,
@ -818,39 +747,6 @@ async function persistWithinTransaction(
instrumentsInserted += res.rows.length;
}
for (let offset = 0; offset < toInsertSynthetic.length; offset += chunkSize) {
const slice = toInsertSynthetic.slice(offset, offset + chunkSize);
const res = await client.query<{ instrument_id: number }>(
`INSERT INTO instrument (
primary_isin,
primary_cusip,
canonical_name,
security_type,
issuer_country
)
SELECT NULL, NULL, u.canonical_name, u.security_type, u.issuer_country
FROM UNNEST(
$1::text[],
$2::varchar[],
$3::bpchar[]
) AS u(canonical_name, security_type, issuer_country)
RETURNING instrument_id`,
[
slice.map(item => item.canonicalName),
slice.map(item => item.securityType),
slice.map(item => item.issuerCountry),
]
);
for (let i = 0; i < res.rows.length; i++) {
const item = slice[i];
const row = res.rows[i];
if (item !== undefined && row !== undefined) {
instrumentIdByIsin.set(item.primaryIsin, row.instrument_id);
}
}
instrumentsInserted += res.rows.length;
}
for (let offset = 0; offset < toUpdate.length; offset += chunkSize) {
const slice = toUpdate.slice(offset, offset + chunkSize);
await client.query(
@ -888,9 +784,6 @@ async function persistWithinTransaction(
source: StageASource;
}> = [];
for (const item of preparedInstruments) {
if (item.isSynthetic) {
continue;
}
const instrumentId = instrumentIdByIsin.get(item.primaryIsin);
if (instrumentId === undefined) {
continue;

View file

@ -1,291 +0,0 @@
import { mkdir, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import { getLogger } from '@stock-bot/logger';
import { MongoDBClient } from '@stock-bot/mongodb';
import { initializeStockConfig } from '@stock-bot/stock-config';
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
import {
DEFAULT_FIELD_SHAPE_LIMIT,
FIELD_SHAPE_PROBE_COLLECTIONS,
MAX_FIELD_SHAPE_LIMIT,
normalizeProbeCollections,
readFieldShapes,
renderFieldShapesMarkdown,
type FieldShapeProbeCollection,
type ReadFieldShapesResult,
} from './source-field-shapes';
import {
createReadOnlyMongoSourceSymbolReader,
type ReadOnlyMongoCollectionClient,
} from './source-symbol-readers';
export const PROBE_SOURCE_FIELD_SHAPES_USAGE = [
'Usage: bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --out <path> [--limit <n>] [--collections <c1,c2,...>] [--help]',
'',
'Options:',
' --out <path> Required. Output Markdown report file path.',
` --limit <n> Optional. Max documents sampled per collection (1..${MAX_FIELD_SHAPE_LIMIT}, default: ${DEFAULT_FIELD_SHAPE_LIMIT}).`,
` --collections <list> Optional. Comma-separated allowlisted collections (default: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(',')}).`,
' --help Show this help message and exit.',
].join('\n');
export type ParsedProbeSourceFieldShapesArgs =
| { readonly help: true }
| {
readonly help: false;
readonly outPath: string;
readonly limit: number;
readonly collections: readonly FieldShapeProbeCollection[];
};
export interface RunSourceFieldShapesProbeDeps {
readonly mongoCollectionClient: ReadOnlyMongoCollectionClient;
readonly closeMongo?: () => Promise<void> | void;
readonly writeFile?: (filePath: string, content: string) => Promise<void> | void;
readonly writeStdout?: (text: string) => void;
}
export interface RunSourceFieldShapesProbeOptions {
readonly outPath: string;
readonly limit?: number;
readonly collections?: readonly string[];
readonly maxExamples?: number;
readonly maxExampleLength?: number;
readonly batchSize?: number;
}
export interface RunSourceFieldShapesProbeOutput {
readonly outPath: string;
readonly result: ReadFieldShapesResult;
readonly markdown: string;
readonly summary: string;
}
const STRICT_INT_PATTERN = /^-?\d+$/;
function usageError(message: string): Error {
return new Error(`${message}\n\n${PROBE_SOURCE_FIELD_SHAPES_USAGE}`);
}
function parseLimitArg(raw: string): number {
if (!STRICT_INT_PATTERN.test(raw)) {
throw usageError(
`Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}`
);
}
const parsed = Number(raw);
if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_FIELD_SHAPE_LIMIT) {
throw usageError(
`Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}`
);
}
return parsed;
}
function parseCollectionsArg(raw: string): FieldShapeProbeCollection[] {
const parts = raw
.split(',')
.map(part => part.trim())
.filter(part => part.length > 0);
if (parts.length === 0) {
throw usageError('Missing value for --collections');
}
return normalizeProbeCollections(parts);
}
export function parseProbeSourceFieldShapesArgs(
argv: readonly string[]
): ParsedProbeSourceFieldShapesArgs {
let help = false;
let outPath: string | undefined;
let limit = DEFAULT_FIELD_SHAPE_LIMIT;
let collectionsRaw: string[] | undefined;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--help') {
help = true;
continue;
}
if (arg === '--out') {
const value = argv[i + 1];
if (!value || value.trim().length === 0 || value.startsWith('--')) {
throw usageError('Missing value for --out');
}
outPath = value.trim();
i += 1;
continue;
}
if (arg?.startsWith('--out=')) {
const value = arg.slice('--out='.length).trim();
if (value.length === 0) {
throw usageError('Missing value for --out');
}
outPath = value;
continue;
}
if (arg === '--limit') {
const value = argv[i + 1];
if (!value || value.trim().length === 0 || value.startsWith('--')) {
throw usageError('Missing value for --limit');
}
limit = parseLimitArg(value.trim());
i += 1;
continue;
}
if (arg?.startsWith('--limit=')) {
const value = arg.slice('--limit='.length).trim();
if (value.length === 0) {
throw usageError('Missing value for --limit');
}
limit = parseLimitArg(value);
continue;
}
if (arg === '--collections') {
const value = argv[i + 1];
if (!value || value.trim().length === 0 || value.startsWith('--')) {
throw usageError('Missing value for --collections');
}
const parsed = parseCollectionsArg(value);
collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed;
i += 1;
continue;
}
if (arg?.startsWith('--collections=')) {
const value = arg.slice('--collections='.length).trim();
if (value.length === 0) {
throw usageError('Missing value for --collections');
}
const parsed = parseCollectionsArg(value);
collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed;
continue;
}
throw usageError(`Unknown argument: ${String(arg)}`);
}
if (help) {
return { help: true };
}
if (outPath === undefined || outPath.trim().length === 0) {
throw usageError('Missing required argument: --out <path>');
}
const collections = normalizeProbeCollections(collectionsRaw);
return {
help: false,
outPath,
limit,
collections,
};
}
async function defaultWriteFile(filePath: string, content: string): Promise<void> {
await mkdir(dirname(filePath), { recursive: true });
await writeFile(filePath, content, 'utf8');
}
export async function runSourceFieldShapesProbe(
deps: RunSourceFieldShapesProbeDeps,
options: RunSourceFieldShapesProbeOptions
): Promise<RunSourceFieldShapesProbeOutput> {
let primaryError: unknown = undefined;
let hasPrimaryError = false;
let output: RunSourceFieldShapesProbeOutput | undefined;
try {
if (typeof options.outPath !== 'string' || options.outPath.trim().length === 0) {
throw new Error('outPath must be a non-empty string');
}
const reader = createReadOnlyMongoSourceSymbolReader(deps.mongoCollectionClient);
const result = await readFieldShapes(reader, {
limit: options.limit,
collections: options.collections,
maxExamples: options.maxExamples,
maxExampleLength: options.maxExampleLength,
batchSize: options.batchSize,
});
const markdown = renderFieldShapesMarkdown(result);
const writer = deps.writeFile ?? defaultWriteFile;
await writer(options.outPath, markdown);
const summary = [
`Source field-shape probe complete (limit=${result.limit})`,
` Collections: ${result.collections.length} | Documents sampled: ${result.totalDocsSampled}`,
` Report written: ${options.outPath}`,
].join('\n');
output = {
outPath: options.outPath,
result,
markdown,
summary: `${summary}\n`,
};
} catch (error) {
primaryError = error;
hasPrimaryError = true;
} finally {
if (deps.closeMongo) {
try {
await deps.closeMongo();
} catch (closeError) {
if (!hasPrimaryError) {
primaryError = closeError;
hasPrimaryError = true;
}
}
}
}
if (hasPrimaryError) {
throw primaryError;
}
if (output === undefined) {
throw new Error('Source field-shape probe completed without producing output');
}
const writeStdout =
deps.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(output.summary);
return output;
}
export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise<void> {
const parsed = parseProbeSourceFieldShapesArgs(argv);
if (parsed.help) {
process.stdout.write(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`);
return;
}
const logger = getLogger('source-field-shapes-probe');
const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
const mongo = new MongoDBClient(mongoConfig, logger);
await mongo.connect();
await runSourceFieldShapesProbe(
{
mongoCollectionClient: mongo,
closeMongo: () => mongo.disconnect(),
},
{
outPath: parsed.outPath,
limit: parsed.limit,
collections: parsed.collections,
}
);
}
if (import.meta.main) {
runCli().catch(error => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`Error: ${message}\n`);
process.exit(1);
});
}

View file

@ -1,345 +0,0 @@
import { getLogger } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import {
assertEnvironmentSafety,
initializeStockConfig,
type StockAppConfig,
} from '@stock-bot/stock-config';
import {
CURATE_INPUT_FILES,
DEFAULT_DELISTING_MAPPING_SOURCE,
DEFAULT_EXPORT_CHUNK_SIZE,
exportCurateInputs,
MAX_EXPORT_CHUNK_SIZE,
type ExportCurateInputsFsHooks,
type ExportCurateInputsResult,
} from './export-curate-inputs';
import type { SecurityMasterQueryable, SecurityMasterQueryResult } from './persist';
import type { SecurityMasterPostgresHandle } from './run-security-master';
export const EXPORT_CURATE_INPUTS_USAGE = [
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts --out-dir <dir> [--chunk-size <n>] [--help]',
'',
'Options:',
` --out-dir <dir> Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, and ${CURATE_INPUT_FILES.delistings}.`,
` --chunk-size <n> Optional. Keyset pagination chunk size (1..${MAX_EXPORT_CHUNK_SIZE}, default: ${DEFAULT_EXPORT_CHUNK_SIZE}).`,
' --help Show this help message and exit.',
].join('\n');
export type ParsedExportCurateInputsArgs =
| { readonly help: true }
| {
readonly help: false;
readonly outDir: string;
readonly chunkSize: number;
};
export interface RunExportCurateInputsDeps {
readonly assertSafety?: () => void;
readonly createPostgresClient: () =>
| Promise<SecurityMasterPostgresHandle>
| SecurityMasterPostgresHandle;
readonly exportFn?: typeof exportCurateInputs;
readonly writeStdout?: (text: string) => void;
}
export interface RunExportCurateInputsOptions {
readonly outDir: string;
readonly chunkSize?: number;
readonly delistingMappingSource?: string;
readonly fs?: ExportCurateInputsFsHooks;
}
export interface RunExportCurateInputsOutput {
readonly result: ExportCurateInputsResult;
readonly summary: string;
}
const STRICT_INT_PATTERN = /^-?\d+$/;
function usageError(message: string): Error {
return new Error(`${message}\n\n${EXPORT_CURATE_INPUTS_USAGE}`);
}
function parseChunkSizeArg(raw: string): number {
if (!STRICT_INT_PATTERN.test(raw)) {
throw usageError(
`Invalid --chunk-size value "${raw}": expected an integer between 1 and ${MAX_EXPORT_CHUNK_SIZE}`
);
}
const parsed = Number(raw);
if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_EXPORT_CHUNK_SIZE) {
throw usageError(
`Invalid --chunk-size value "${raw}": expected an integer between 1 and ${MAX_EXPORT_CHUNK_SIZE}`
);
}
return parsed;
}
export function parseExportCurateInputsArgs(
argv: readonly string[]
): ParsedExportCurateInputsArgs {
let help = false;
let outDir: string | undefined;
let chunkSize = DEFAULT_EXPORT_CHUNK_SIZE;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--help') {
help = true;
continue;
}
if (arg === '--out-dir') {
const value = argv[i + 1];
if (!value || value.trim().length === 0 || value.startsWith('--')) {
throw usageError('Missing value for --out-dir');
}
outDir = value.trim();
i += 1;
continue;
}
if (arg?.startsWith('--out-dir=')) {
const value = arg.slice('--out-dir='.length).trim();
if (value.length === 0) {
throw usageError('Missing value for --out-dir');
}
outDir = value;
continue;
}
if (arg === '--chunk-size') {
const value = argv[i + 1];
if (!value || value.trim().length === 0 || value.startsWith('--')) {
throw usageError('Missing value for --chunk-size');
}
chunkSize = parseChunkSizeArg(value.trim());
i += 1;
continue;
}
if (arg?.startsWith('--chunk-size=')) {
const value = arg.slice('--chunk-size='.length).trim();
if (value.length === 0) {
throw usageError('Missing value for --chunk-size');
}
chunkSize = parseChunkSizeArg(value);
continue;
}
throw usageError(`Unknown argument: ${String(arg)}`);
}
if (help) {
return { help: true };
}
if (outDir === undefined || outDir.trim().length === 0) {
throw usageError('Missing required argument: --out-dir <dir>');
}
return {
help: false,
outDir,
chunkSize,
};
}
export function assertExportCurateInputsSafety(
config: StockAppConfig,
env: Record<string, string | undefined> = process.env
): void {
const pg = config.database.postgres;
if (!pg.enabled) {
throw new Error('PostgreSQL is disabled in configuration; cannot export curate-etl inputs');
}
const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _stripped, ...safeEnv } = env;
const pgOnlyConfig: StockAppConfig = {
...config,
database: {
...config.database,
mongodb: {
...config.database.mongodb,
enabled: false,
},
},
};
assertEnvironmentSafety(pgOnlyConfig, 'dataPipeline', safeEnv);
}
export function formatExportCurateInputsSummary(result: ExportCurateInputsResult): string {
const d = result.delistings.stats;
const s = d.skipped;
const lines = [
`Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId}, snapshot_dir=${result.generationDir})`,
` ${CURATE_INPUT_FILES.providerMapping}: rows_in=${result.providerMapping.rowsIn} rows_out=${result.providerMapping.rowsOut} bytes=${result.providerMapping.bytesWritten}`,
` ${CURATE_INPUT_FILES.listingCurrencies}: rows_in=${result.listingCurrencies.rowsIn} rows_out=${result.listingCurrencies.rowsOut} bytes=${result.listingCurrencies.bytesWritten}`,
` ${CURATE_INPUT_FILES.delistings}: rows_in=${d.rowsIn} rows_out=${d.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut}) skipped=${d.skippedTotal} [active=${s.active} no_outcome=${s.noOutcome} missing_listed_to=${s.missingListedTo} missing_outgoing_qm=${s.missingOutgoingQmMapping} missing_successor_qm=${s.missingSuccessorQmMapping} non_otc_continuity=${s.nonOtcContinuity}] bytes=${result.delistings.bytesWritten}`,
` chunk_size=${result.chunkSize} mapping_source=${result.delistingMappingSource} total_bytes=${result.totalBytesWritten}`,
];
for (const warning of result.cleanupWarnings) {
lines.push(` warning: ${warning}`);
}
return `${lines.join('\n')}\n`;
}
export async function runExportCurateInputs(
deps: RunExportCurateInputsDeps,
options: RunExportCurateInputsOptions
): Promise<RunExportCurateInputsOutput> {
if (deps.assertSafety) {
deps.assertSafety();
}
const pgHandle = await deps.createPostgresClient();
let result: ExportCurateInputsResult;
let closeError: unknown = null;
try {
const exportFn = deps.exportFn ?? exportCurateInputs;
result = await exportFn(pgHandle.queryable, {
outDir: options.outDir,
chunkSize: options.chunkSize,
delistingMappingSource: options.delistingMappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE,
fs: options.fs,
});
} finally {
try {
await pgHandle.close();
} catch (error) {
closeError = error;
}
}
if (closeError !== null) {
throw closeError;
}
const summary = formatExportCurateInputsSummary(result);
const writeStdout =
deps.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(summary);
return { result, summary };
}
export async function runCli(
argv: readonly string[] = process.argv.slice(2),
overrides?: Partial<RunExportCurateInputsDeps>
): Promise<void> {
const parsed = parseExportCurateInputsArgs(argv);
if (parsed.help) {
const writeStdout =
overrides?.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(`${EXPORT_CURATE_INPUTS_USAGE}\n`);
return;
}
const logger = getLogger('security-master-export-curate-inputs-cli');
const config = initializeStockConfig('dataPipeline', { postgresOnly: true });
const assertSafety = (): void => {
assertExportCurateInputsSafety(config, process.env);
};
const createPostgresClient = async (): Promise<SecurityMasterPostgresHandle> => {
const pg = config.database.postgres;
const pgClient = new PostgreSQLClient(
{
host: pg.host,
port: pg.port,
database: pg.database,
username: pg.user,
password: pg.password,
poolSettings: {
min: 1,
max: Math.max(1, pg.poolSize),
idleTimeoutMillis: pg.idleTimeout,
},
ssl: {
enabled: pg.ssl,
rejectUnauthorized: true,
},
timeouts: {
connection: pg.connectionTimeout,
},
},
logger
);
await pgClient.connect();
try {
const pool = pgClient.connectionPool;
if (!pool) {
throw new Error('PostgreSQL connection pool was not initialized after connect()');
}
const poolClient = await pool.connect();
const queryable: SecurityMasterQueryable = {
query<Row = Record<string, unknown>>(
text: string,
values?: readonly unknown[]
): Promise<SecurityMasterQueryResult<Row>> {
return poolClient.query(
text,
values === undefined ? undefined : [...values]
) as unknown as Promise<SecurityMasterQueryResult<Row>>;
},
release: () => {
poolClient.release();
},
};
let closed = false;
return {
queryable,
async close(): Promise<void> {
if (closed) {
return;
}
closed = true;
let releaseError: unknown = null;
try {
poolClient.release();
} catch (error) {
releaseError = error;
}
try {
await pgClient.disconnect();
} catch (disconnectError) {
if (releaseError === null) {
throw disconnectError;
}
}
if (releaseError !== null) {
throw releaseError;
}
},
};
} catch (error) {
await pgClient.disconnect().catch(() => {});
throw error;
}
};
await runExportCurateInputs(
{
assertSafety: overrides?.assertSafety ?? assertSafety,
createPostgresClient: overrides?.createPostgresClient ?? createPostgresClient,
exportFn: overrides?.exportFn,
writeStdout: overrides?.writeStdout,
},
{
outDir: parsed.outDir,
chunkSize: parsed.chunkSize,
}
);
}
if (import.meta.main) {
runCli().catch(error => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`Error: ${message}\n`);
process.exit(1);
});
}

View file

@ -1,477 +0,0 @@
import { getLogger } from '@stock-bot/logger';
import { MongoDBClient } from '@stock-bot/mongodb';
import {
assertEnvironmentSafety,
initializeStockConfig,
type StockAppConfig,
} from '@stock-bot/stock-config';
import {
createReadOnlyMongoRawBsonSource,
DEFAULT_RAW_BSON_BATCH_SIZE,
exportRawBsonCollection,
isRawBsonExportCollection,
MAX_RAW_BSON_BATCH_SIZE,
RAW_BSON_EXPORT_COLLECTIONS,
RawBsonExportError,
type ExportRawBsonCollectionResult,
type ExportRawBsonFsHooks,
type RawBsonExportCollection,
type ReadOnlyMongoRawBsonClient,
} from './export-raw-bson';
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
export const EXPORT_RAW_BSON_USAGE = [
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts --out-dir <dir> [--collections <c1,c2,...>] [--eod-symbol <code>] [--te-symbol <sym>] [--limit <n>] [--batch-size <n>] [--help]',
'',
'Options:',
' --out-dir <dir> Required. Output directory for <collection>.bson files.',
` --collections <c1,c2,...> Optional. Comma-separated allowlisted collections (default: ${RAW_BSON_EXPORT_COLLECTIONS.join(',')}).`,
' --eod-symbol <code> Optional. Exact eodSearchCode filter (only valid when --collections is strictly eodPrices).',
' --te-symbol <sym> Optional. Exact teSymbol filter (only valid when --collections is strictly teMarketData).',
' --limit <n> Optional. Max documents to export per collection (positive integer, for smoke runs).',
` --batch-size <n> Optional. MongoDB cursor batchSize (1..${MAX_RAW_BSON_BATCH_SIZE}, default: ${DEFAULT_RAW_BSON_BATCH_SIZE}).`,
' --help Show this help message and exit.',
].join('\n');
export type ParsedExportRawBsonArgs =
| { readonly help: true }
| {
readonly help: false;
readonly outDir: string;
readonly collections: readonly RawBsonExportCollection[];
readonly eodSymbol?: string;
readonly teSymbol?: string;
readonly limit?: number;
readonly batchSize: number;
};
export interface RawBsonMongoHandle {
readonly client: ReadOnlyMongoRawBsonClient;
readonly close: () => Promise<void> | void;
}
export interface RunExportRawBsonDeps {
readonly assertSafety?: () => void;
readonly createMongoClient: () => Promise<RawBsonMongoHandle> | RawBsonMongoHandle;
readonly exportFn?: typeof exportRawBsonCollection;
readonly writeStdout?: (text: string) => void;
}
export interface RunExportRawBsonCliOverrides extends Partial<RunExportRawBsonDeps> {
readonly initializeConfig?: typeof initializeStockConfig;
}
export interface RunExportRawBsonOptions {
readonly outDir: string;
readonly collections: readonly RawBsonExportCollection[];
readonly eodSymbol?: string;
readonly teSymbol?: string;
readonly limit?: number;
readonly batchSize?: number;
readonly writeBufferBytes?: number;
readonly maxDocBytes?: number;
readonly fs?: ExportRawBsonFsHooks;
}
export interface RunExportRawBsonOutput {
readonly results: readonly ExportRawBsonCollectionResult[];
readonly summary: string;
}
const STRICT_INT_PATTERN = /^-?\d+$/;
function usageError(message: string): Error {
return new Error(`${message}\n\n${EXPORT_RAW_BSON_USAGE}`);
}
function parsePositiveIntArg(flag: string, raw: string, max?: number): number {
if (!STRICT_INT_PATTERN.test(raw)) {
throw usageError(
max !== undefined
? `Invalid ${flag} value "${raw}": expected an integer between 1 and ${max}`
: `Invalid ${flag} value "${raw}": expected a positive integer`
);
}
const parsed = Number(raw);
if (
!Number.isSafeInteger(parsed) ||
parsed < 1 ||
(max !== undefined && parsed > max)
) {
throw usageError(
max !== undefined
? `Invalid ${flag} value "${raw}": expected an integer between 1 and ${max}`
: `Invalid ${flag} value "${raw}": expected a positive integer`
);
}
return parsed;
}
function parseCollectionsList(raw: string): RawBsonExportCollection[] {
const segments = raw.split(',');
const result: RawBsonExportCollection[] = [];
const seen = new Set<string>();
for (const segment of segments) {
const trimmed = segment.trim();
if (trimmed.length === 0) {
throw usageError(`Malformed --collections value "${raw}": empty collection entry`);
}
if (!isRawBsonExportCollection(trimmed)) {
throw new RawBsonExportError({
code: 'DISALLOWED_COLLECTION',
collection: trimmed,
detail: `collection "${trimmed}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`,
});
}
if (seen.has(trimmed)) {
throw usageError(`Duplicate collection "${trimmed}" in --collections`);
}
seen.add(trimmed);
result.push(trimmed);
}
if (result.length === 0) {
throw usageError('Missing value for --collections');
}
return result;
}
function readFlagValue(
argv: readonly string[],
index: number,
flag: string
): { value: string; nextIndex: number } {
const arg = argv[index] ?? '';
const eqPrefix = `${flag}=`;
if (arg.startsWith(eqPrefix)) {
const value = arg.slice(eqPrefix.length).trim();
if (value.length === 0) {
throw usageError(`Missing value for ${flag}`);
}
if (value.startsWith('--')) {
throw usageError(`Invalid value for ${flag}: "${value}" must not start with "--"`);
}
return { value, nextIndex: index };
}
const next = argv[index + 1];
const trimmedNext = next?.trim() ?? '';
if (trimmedNext.length === 0 || trimmedNext.startsWith('--')) {
throw usageError(`Missing value for ${flag}`);
}
return { value: trimmedNext, nextIndex: index + 1 };
}
export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRawBsonArgs {
let help = false;
let outDir: string | undefined;
let collections: RawBsonExportCollection[] | undefined;
let eodSymbol: string | undefined;
let teSymbol: string | undefined;
let limit: number | undefined;
let batchSize = DEFAULT_RAW_BSON_BATCH_SIZE;
const seenFlags = new Set<string>();
const markSeen = (flag: string): void => {
if (seenFlags.has(flag)) {
throw usageError(`Duplicate flag: ${flag}`);
}
seenFlags.add(flag);
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--help') {
markSeen('--help');
help = true;
continue;
}
if (arg === '--out-dir' || arg?.startsWith('--out-dir=')) {
markSeen('--out-dir');
const { value, nextIndex } = readFlagValue(argv, i, '--out-dir');
outDir = value;
i = nextIndex;
continue;
}
if (arg === '--collections' || arg?.startsWith('--collections=')) {
markSeen('--collections');
const { value, nextIndex } = readFlagValue(argv, i, '--collections');
collections = parseCollectionsList(value);
i = nextIndex;
continue;
}
if (arg === '--eod-symbol' || arg?.startsWith('--eod-symbol=')) {
markSeen('--eod-symbol');
const { value, nextIndex } = readFlagValue(argv, i, '--eod-symbol');
eodSymbol = value;
i = nextIndex;
continue;
}
if (arg === '--te-symbol' || arg?.startsWith('--te-symbol=')) {
markSeen('--te-symbol');
const { value, nextIndex } = readFlagValue(argv, i, '--te-symbol');
teSymbol = value;
i = nextIndex;
continue;
}
if (arg === '--limit' || arg?.startsWith('--limit=')) {
markSeen('--limit');
const { value, nextIndex } = readFlagValue(argv, i, '--limit');
limit = parsePositiveIntArg('--limit', value);
i = nextIndex;
continue;
}
if (arg === '--batch-size' || arg?.startsWith('--batch-size=')) {
markSeen('--batch-size');
const { value, nextIndex } = readFlagValue(argv, i, '--batch-size');
batchSize = parsePositiveIntArg('--batch-size', value, MAX_RAW_BSON_BATCH_SIZE);
i = nextIndex;
continue;
}
throw usageError(`Unknown argument: ${String(arg)}`);
}
if (help) {
return { help: true };
}
if (outDir === undefined || outDir.trim().length === 0) {
throw usageError('Missing required argument: --out-dir <dir>');
}
const resolvedCollections: readonly RawBsonExportCollection[] =
collections ?? [...RAW_BSON_EXPORT_COLLECTIONS];
if (eodSymbol !== undefined) {
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'eodPrices') {
throw usageError(
'--eod-symbol is only permitted when --collections is strictly "eodPrices"'
);
}
}
if (teSymbol !== undefined) {
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'teMarketData') {
throw usageError(
'--te-symbol is only permitted when --collections is strictly "teMarketData"'
);
}
}
return {
help: false,
outDir,
collections: resolvedCollections,
...(eodSymbol !== undefined ? { eodSymbol } : {}),
...(teSymbol !== undefined ? { teSymbol } : {}),
...(limit !== undefined ? { limit } : {}),
batchSize,
};
}
export function assertExportRawBsonSafety(
config: StockAppConfig,
env: Record<string, string | undefined> = process.env
): void {
const mongo = config.database.mongodb;
if (!mongo.enabled) {
throw new Error('MongoDB is disabled in configuration; cannot export raw BSON collections');
}
if (mongo.readOnly !== true) {
throw new Error(
'Raw BSON exporter requires read-only MongoDB configuration (database.mongodb.readOnly === true)'
);
}
const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env;
const mongoOnlyConfig: StockAppConfig = {
...config,
database: {
...config.database,
postgres: {
...config.database.postgres,
enabled: false,
},
},
};
assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv);
}
export function formatExportRawBsonSummary(
results: readonly ExportRawBsonCollectionResult[]
): string {
const lines = [`Raw BSON export complete (${results.length} collection(s))`];
for (const r of results) {
lines.push(
` ${r.collection}: docs=${r.docsWritten} bytes=${r.bytesWritten} elapsed_ms=${r.elapsedMs.toFixed(1)} sha256=${r.sha256} out=${r.outPath}`
);
}
return `${lines.join('\n')}\n`;
}
export async function runExportRawBson(
deps: RunExportRawBsonDeps,
options: RunExportRawBsonOptions
): Promise<RunExportRawBsonOutput> {
if (options.collections.length === 0) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: '*',
detail: 'At least one allowlisted collection must be specified',
});
}
for (const collection of options.collections) {
if (!isRawBsonExportCollection(collection)) {
throw new RawBsonExportError({
code: 'DISALLOWED_COLLECTION',
collection: String(collection),
detail: `collection "${String(collection)}" is not in the M1 allowlist`,
});
}
}
if (
options.eodSymbol !== undefined &&
(options.collections.length !== 1 || options.collections[0] !== 'eodPrices')
) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: options.collections.join(','),
detail: '--eod-symbol is only permitted when exporting strictly "eodPrices"',
});
}
if (
options.teSymbol !== undefined &&
(options.collections.length !== 1 || options.collections[0] !== 'teMarketData')
) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: options.collections.join(','),
detail: '--te-symbol is only permitted when exporting strictly "teMarketData"',
});
}
if (deps.assertSafety) {
deps.assertSafety();
}
const mongoHandle = await deps.createMongoClient();
const results: ExportRawBsonCollectionResult[] = [];
let primaryError: unknown = undefined;
let hasPrimaryError = false;
try {
const source = createReadOnlyMongoRawBsonSource(mongoHandle.client);
const exportFn = deps.exportFn ?? exportRawBsonCollection;
for (const collection of options.collections) {
const result = await exportFn(source, {
collection,
outDir: options.outDir,
...(options.eodSymbol !== undefined ? { eodSymbol: options.eodSymbol } : {}),
...(options.teSymbol !== undefined ? { teSymbol: options.teSymbol } : {}),
...(options.limit !== undefined ? { limit: options.limit } : {}),
...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}),
...(options.writeBufferBytes !== undefined
? { writeBufferBytes: options.writeBufferBytes }
: {}),
...(options.maxDocBytes !== undefined ? { maxDocBytes: options.maxDocBytes } : {}),
...(options.fs !== undefined ? { fs: options.fs } : {}),
});
results.push(result);
}
} catch (error) {
primaryError = error;
hasPrimaryError = true;
} finally {
try {
await mongoHandle.close();
} catch (closeError) {
if (!hasPrimaryError) {
primaryError = closeError;
hasPrimaryError = true;
}
}
}
if (hasPrimaryError) {
throw primaryError;
}
const summary = formatExportRawBsonSummary(results);
const writeStdout =
deps.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(summary);
return { results, summary };
}
export async function runCli(
argv: readonly string[] = process.argv.slice(2),
overrides?: RunExportRawBsonCliOverrides
): Promise<void> {
const parsed = parseExportRawBsonArgs(argv);
if (parsed.help) {
const writeStdout =
overrides?.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(`${EXPORT_RAW_BSON_USAGE}\n`);
return;
}
const logger = getLogger('security-master-export-raw-bson-cli');
const initConfig = overrides?.initializeConfig ?? initializeStockConfig;
const config = initConfig('dataPipeline', { mongoReadOnly: true });
const assertSafety = (): void => {
assertExportRawBsonSafety(config, process.env);
};
const createMongoClient = async (): Promise<RawBsonMongoHandle> => {
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
const mongo = new MongoDBClient(mongoConfig, logger);
await mongo.connect();
let closed = false;
return {
client: mongo,
async close(): Promise<void> {
if (closed) {
return;
}
closed = true;
await mongo.disconnect();
},
};
};
await runExportRawBson(
{
assertSafety: overrides?.assertSafety ?? assertSafety,
createMongoClient: overrides?.createMongoClient ?? createMongoClient,
exportFn: overrides?.exportFn,
writeStdout: overrides?.writeStdout,
},
{
outDir: parsed.outDir,
collections: parsed.collections,
...(parsed.eodSymbol !== undefined ? { eodSymbol: parsed.eodSymbol } : {}),
...(parsed.teSymbol !== undefined ? { teSymbol: parsed.teSymbol } : {}),
...(parsed.limit !== undefined ? { limit: parsed.limit } : {}),
batchSize: parsed.batchSize,
}
);
}
if (import.meta.main) {
runCli().catch(error => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`Error: ${message}\n`);
process.exit(1);
});
}

View file

@ -21,7 +21,6 @@ import {
EXCHANGE_SOURCES,
ISO_EXCHANGE_SEEDS,
normalizeRawExchangeDoc,
REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS,
type ExchangeClassificationResult,
type ExchangeSource,
type SourceExchangeRecord,
@ -52,8 +51,6 @@ import {
import {
createExchangeSourceLookup,
createReadOnlyMongoSourceSymbolReader,
DEFAULT_SOURCE_COUNTRIES,
normalizeCountryIso2,
readSecurityMasterSources,
type ExchangeSourceLookup,
type ReadOnlyMongoCollectionClient,
@ -75,9 +72,7 @@ export const RUN_SECURITY_MASTER_USAGE = [
' --out-dir <dir> Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.',
' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).',
' --skip-price-cross-check Optional. Skip Pass 4 sample-close reads and price cross-checks (default: enabled).',
' --sample-dates <n> Optional. Number of stratified sample dates for Pass 4 (1..64, default: 25).',
' --reviewed-us-ca-exchanges Optional. Scope Pass 1 exchange classification to configured US/CA countries with reviewed US/CA venue rules.',
' --allow-identifierless-eod Optional. Admit US/CA EOD primary-venue listings lacking ISIN/CUSIP (stored with primary_isin = NULL).',
` --sample-dates <n> Optional. Number of stratified sample dates for Pass 4 (1..${MAX_SAMPLE_DATES}, default: ${DEFAULT_SAMPLE_DATE_COUNT}).`,
' --help Show this help message and exit.',
].join('\n');
@ -90,8 +85,6 @@ export type ParsedRunSecurityMasterArgs =
readonly persist: boolean;
readonly skipPriceCrossCheck: boolean;
readonly sampleDateCount: number;
readonly useReviewedUsCaExchanges?: boolean;
readonly allowIdentifierlessEod?: boolean;
};
export interface RunSecurityMasterPass4Options {
@ -141,8 +134,6 @@ export interface RunSecurityMasterOptions {
readonly batchSize?: number;
readonly barSpans?: Omit<ComputeBarSpansOptions, 'sourceIdsBySource'>;
readonly pass4?: RunSecurityMasterPass4Options;
readonly useReviewedUsCaExchanges?: boolean;
readonly allowIdentifierlessEod?: boolean;
}
export interface RunSecurityMasterOutput {
@ -360,8 +351,6 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
let persist = false;
let skipPriceCrossCheck = false;
let sampleDateCount = DEFAULT_SAMPLE_DATE_COUNT;
let useReviewedUsCaExchanges = false;
let allowIdentifierlessEod = false;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
@ -377,14 +366,6 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
skipPriceCrossCheck = true;
continue;
}
if (arg === '--reviewed-us-ca-exchanges') {
useReviewedUsCaExchanges = true;
continue;
}
if (arg === '--allow-identifierless-eod') {
allowIdentifierlessEod = true;
continue;
}
if (arg === '--sample-dates') {
const value = argv[i + 1];
if (!value || value.trim().length === 0 || value.startsWith('--')) {
@ -462,8 +443,6 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
persist,
skipPriceCrossCheck,
sampleDateCount,
...(useReviewedUsCaExchanges ? { useReviewedUsCaExchanges: true } : {}),
...(allowIdentifierlessEod ? { allowIdentifierlessEod: true } : {}),
};
}
@ -648,31 +627,8 @@ export async function runSecurityMaster(
}
exchangeCountsByCollection[source] = count;
}
let recordsToClassify = normalizedRecords;
if (options.useReviewedUsCaExchanges === true && options.countries !== null) {
const allowedCountries = new Set<string>(
(options.countries ?? DEFAULT_SOURCE_COUNTRIES)
.map(c => normalizeCountryIso2(c) ?? c.trim().toUpperCase())
.filter(c => c.length > 0)
);
recordsToClassify = normalizedRecords.filter(rec => {
const codeUpper = rec.code.trim().toUpperCase();
if (rec.source === 'eod' && codeUpper === 'FOREX') {
return true;
}
const iso = normalizeCountryIso2(rec.country);
return (
rec.country === null ||
rec.country === undefined ||
(iso !== null && allowedCountries.has(iso))
);
});
}
exchanges = classifySourceExchanges(recordsToClassify, {
exchanges = classifySourceExchanges(normalizedRecords, {
knownExchanges: ISO_EXCHANGE_SEEDS,
...(options.useReviewedUsCaExchanges === true
? { reviewedRows: REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS }
: {}),
});
}
@ -688,7 +644,6 @@ export async function runSecurityMaster(
exchangeLookup,
countries: options.countries,
batchSize: options.batchSize,
...(options.allowIdentifierlessEod === true ? { includeExtendedMetadata: true } : {}),
});
} catch (error) {
throw wrapStepError('read-sources', error);
@ -718,41 +673,6 @@ export async function runSecurityMaster(
}
// Step 5: Compose Stage A -> Stage B -> Pass 6 -> candidate Pass 4 pairs.
const composeOptions =
options.allowIdentifierlessEod === true
? {
asOfDate: options.asOfDate,
stageA: { allowIdentifierlessEod: true },
stageB: {
enableIbTickerDisambiguation: true,
allowUniqueTickerFallbackForCrawlOnlyCeo: true,
},
report: {
applyUsCaEquityGateDenominator: true,
},
}
: {
asOfDate: options.asOfDate,
};
// Preserve verified pre-2024 FB -> META ticker history (2012-05-18 .. 2022-06-08) when
// META.US is present and eodSymbolChange only covers recent years, so historical FB bars
// map to Meta while the 2025 ProShares FB ETF (FB.US) retains a distinct listing_id.
if (
options.allowIdentifierlessEod === true &&
sources.stageBInput.eodListings.some(e => e.sourceId === 'META.US') &&
!sources.stageBInput.symbolChanges.some(
sc => sc.eodSourceId === 'META.US' && sc.oldTicker === 'FB'
)
) {
sources.stageBInput.symbolChanges.push({
eodSourceId: 'META.US',
oldTicker: 'FB',
effectiveDate: '2022-06-09',
validFrom: '2012-05-18',
});
}
const composeFn = deps.composeFn ?? composeSecurityMasterRun;
let composed: ComposeSecurityMasterRunResult;
try {
@ -762,7 +682,9 @@ export async function runSecurityMaster(
barSpans,
exchanges,
},
composeOptions
{
asOfDate: options.asOfDate,
}
);
} catch (error) {
throw wrapStepError('compose', error);
@ -836,7 +758,9 @@ export async function runSecurityMaster(
sampleCloses: sampleCloses.closes,
fxRates: sampleCloses.fxRates,
},
composeOptions
{
asOfDate: options.asOfDate,
}
);
} catch (error) {
throw wrapStepError('compose', error);
@ -1101,8 +1025,6 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
asOfDate: parsed.asOfDate,
outDir: parsed.outDir,
persist: parsed.persist,
...(parsed.useReviewedUsCaExchanges ? { useReviewedUsCaExchanges: true } : {}),
...(parsed.allowIdentifierlessEod ? { allowIdentifierlessEod: true } : {}),
pass4: {
enabled: !parsed.skipPriceCrossCheck,
sampleDateCount: parsed.sampleDateCount,

View file

@ -22,12 +22,10 @@ import {
isStageASource,
matchInstrumentsStageA,
STAGE_A_SOURCES,
SYNTHETIC_EOD_ISIN_PREFIX,
type MatchInstrumentsStageAOptions,
type StageAMatchResult,
type StageASourceRecord,
} from './instrument-stage-a';
import { classifyEodSecurityType } from './security-type';
import {
matchListingsStageB,
MAX_TICKER_ROOT_LENGTH,
@ -48,8 +46,6 @@ import {
sourceCountryKey,
type BuildMatchReportOptions,
type CountryResolutionSummary,
type GateOutOfScopeLookup,
type GateOutOfScopeReason,
type MatchReport,
type RenderMatchReportMarkdownOptions,
type SourceCountryLookup,
@ -937,8 +933,7 @@ function applyEndToEndStageACoverage(
const unresolved = row.unresolved + d.unresolved;
const conflict = row.conflict + d.conflict;
const excludedByDesign = row.excludedByDesign + d.excludedByDesign;
const outOfGateScope = row.outOfGateScope ?? 0;
const eligibleTotal = Math.max(0, total - excludedByDesign - outOfGateScope);
const eligibleTotal = Math.max(0, total - excludedByDesign);
return {
source: row.source,
total,
@ -946,7 +941,6 @@ function applyEndToEndStageACoverage(
unresolved,
conflict,
excludedByDesign,
...(row.outOfGateScope !== undefined ? { outOfGateScope } : {}),
eligibleTotal,
resolvedPct: total > 0 ? row.matched / total : null,
eligibleResolvedPct: eligibleTotal > 0 ? row.matched / eligibleTotal : null,
@ -1181,143 +1175,6 @@ export function composeSecurityMasterRun(
const sourceCountries =
input.sourceCountries ??
deriveSourceCountries(sanitizedStageARecords, attached.stageBInput, stageB);
const NON_EQUITY_CLASS_SUFFIX_RE =
/^(WT|WS|DB|RT|R|U|UN|H|P|PR|PF|PA|PB|PC|PD|PE|PG|PH|PI|PJ|PK|PL|PM|PN|PO|PP|PQ|PS|PT|PU|PV|PW|PX|PY|PZ|PR[A-Z]|PF[A-Z])(\..+)?$/;
const TEST_SYMBOL_RE = /^(NTEST|ZXYZ|ZVZZT|ZWZZT|ZXZZT)/i;
const NON_EQUITY_NAME_RE =
/\b(WARRANTS?|DEBENTURES?|PREFERRED|PFD|RIGHTS?|SUBSCRIPTION\s+RECEIPTS?|UNITS?|TEST\s+SYMBOL)\b/i;
const US_CA_EQUITY_GATE_DENOMINATOR_NOTE = [
'The M1 `>= 95.00%` equity resolution gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered exchanges** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`).',
'All raw catalog rows remain visible in `Total` and `Resolved %`; non-matched records outside the gate denominator are transparently itemized under `Excluded by Design` (`excluded_fund`, `composite_venue`, `ats_routing_venue`, `forex_venue`) and `Out of Gate Scope`:',
'- `zero_bar_catalog_ghost`: secondary ticker-only rows (`qm`) with `missing_span` (zero price bars in `qmPrices`, intentionally refused by Stage B Tier 3/4 temporal-overlap safety to prevent ticker-reuse corruption such as `FB`).',
'- `uncovered_venue`: listings on venues absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`/`ceo`/`ib:AEQLIT`, and `ceo:NEOE` where EODHD carries only 19 of 587 listings).',
'- `non_equity_instrument`: non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX shells `.H`, TSXV CPCs `.P`, and exchange test symbols).',
].join('\n');
function isNonEquityRecord(
source: 'ib' | 'qm' | 'ceo',
ticker: string | null | undefined,
name: string | null | undefined
): boolean {
if (typeof name === 'string' && NON_EQUITY_NAME_RE.test(name)) {
return true;
}
if (typeof ticker !== 'string' || ticker.trim().length === 0) {
return false;
}
const trimmed = ticker.trim();
if (TEST_SYMBOL_RE.test(trimmed)) {
return true;
}
if (source === 'ceo' && /\.(CN|NEO)$/i.test(trimmed)) {
return false;
}
const parsed = parseTickerDetailed(trimmed, source);
if (!parsed.ok) {
return false;
}
return (
parsed.classSuffix.length > 0 &&
NON_EQUITY_CLASS_SUFFIX_RE.test(parsed.classSuffix.toUpperCase())
);
}
function buildUsCaEquityGateOutOfScope(
stageBInput: SecurityMasterStageBSourceInput,
stageB: StageBMatchResult
): GateOutOfScopeLookup {
const out = new Map<string, GateOutOfScopeReason>();
const ibById = new Map<string, StageBIbContractInput>();
for (const contract of stageBInput.ibContracts) {
if (contract !== undefined) {
ibById.set(contract.sourceId, contract);
}
}
const tickerByKey = new Map<string, StageBTickerSourceInput>();
for (const entry of stageBInput.tickerSources) {
if (entry !== undefined) {
tickerByKey.set(sourceCountryKey(entry.source, entry.sourceId), entry);
}
}
for (const rec of stageB.unresolved) {
const key = sourceCountryKey(rec.source, rec.sourceId);
if (rec.source === 'qm') {
if (rec.reason === 'missing_span') {
out.set(key, 'zero_bar_catalog_ghost');
continue;
}
const meta = tickerByKey.get(key);
if (meta !== undefined) {
if (meta.mic === 'XCNQ') {
out.set(key, 'uncovered_venue');
continue;
}
if (isNonEquityRecord('qm', meta.ticker, meta.name)) {
out.set(key, 'non_equity_instrument');
}
}
} else if (rec.source === 'ceo') {
const meta = tickerByKey.get(key);
if (meta !== undefined) {
if (
meta.mic === 'XCNQ' ||
meta.mic === 'NEOE' ||
(typeof meta.ticker === 'string' && /\.(CN|NEO)$/i.test(meta.ticker.trim()))
) {
out.set(key, 'uncovered_venue');
continue;
}
if (isNonEquityRecord('ceo', meta.ticker, meta.name)) {
out.set(key, 'non_equity_instrument');
}
}
} else if (rec.source === 'ib') {
const meta = ibById.get(rec.sourceId);
if (meta !== undefined) {
if (isNonEquityRecord('ib', meta.ticker, meta.name)) {
out.set(key, 'non_equity_instrument');
continue;
}
if (meta.exchangeId === 'AEQLIT' && meta.currency === 'CAD') {
out.set(key, 'uncovered_venue');
}
}
}
}
for (const conflict of stageB.conflicts) {
const key = sourceCountryKey(conflict.source, conflict.sourceId);
if (out.has(key)) {
continue;
}
if (conflict.source === 'ib') {
const meta = ibById.get(conflict.sourceId);
if (meta !== undefined && isNonEquityRecord('ib', meta.ticker, meta.name)) {
out.set(key, 'non_equity_instrument');
}
} else if (conflict.source === 'qm' || conflict.source === 'ceo') {
const meta = tickerByKey.get(key);
if (meta !== undefined) {
if (meta.mic === 'XCNQ' || (conflict.source === 'ceo' && meta.mic === 'NEOE')) {
out.set(key, 'uncovered_venue');
} else if (isNonEquityRecord(conflict.source, meta.ticker, meta.name)) {
out.set(key, 'non_equity_instrument');
}
}
}
}
return out;
}
const gateOutOfScope =
options.report?.applyUsCaEquityGateDenominator === true
? buildUsCaEquityGateOutOfScope(attached.stageBInput, stageB)
: undefined;
const baseReport = buildMatchReport(
{
...(input.exchanges !== undefined ? { exchanges: input.exchanges } : {}),
@ -1326,12 +1183,6 @@ function buildUsCaEquityGateOutOfScope(
...(pass4 !== null ? { priceCrossCheck: pass4 } : {}),
delistingChains: pass6,
sourceCountries,
...(gateOutOfScope !== undefined
? {
gateOutOfScope,
gateDenominatorNote: US_CA_EQUITY_GATE_DENOMINATOR_NOTE,
}
: {}),
},
options.report
);
@ -1357,29 +1208,6 @@ function buildUsCaEquityGateOutOfScope(
sortedSecurityTypeByIsin.set(entry[0], entry[1]);
}
}
if (
options.stageA?.allowIdentifierlessEod === true &&
Array.isArray(input.sources.securityTypeRecords)
) {
const syntheticEntries: Array<[string, SecurityType]> = [];
for (const rec of input.sources.securityTypeRecords) {
if (rec !== undefined && rec.isin === null && typeof rec.sourceId === 'string') {
const mapped = classifyEodSecurityType(rec.rawType);
if (mapped !== null) {
syntheticEntries.push([
`${SYNTHETIC_EOD_ISIN_PREFIX}${rec.sourceId.trim().toUpperCase()}`,
mapped,
]);
}
}
}
syntheticEntries.sort((a, b) => compareAscii(a[0], b[0]));
for (const [k, v] of syntheticEntries) {
if (!sortedSecurityTypeByIsin.has(k)) {
sortedSecurityTypeByIsin.set(k, v);
}
}
}
const persistInput: PersistSecurityMasterInput = {
stageA,
@ -1394,7 +1222,7 @@ function buildUsCaEquityGateOutOfScope(
let stageAUnresolved = 0;
for (const source of STAGE_A_SOURCES) {
const s = stageA.stats.bySource[source];
stageAResolved += s.tier1Isin + s.tier2Cusip + (s.tier3Synthetic ?? 0);
stageAResolved += s.tier1Isin + s.tier2Cusip;
stageAUnresolved += s.unresolved + s.conflict;
}
const stageAStepStats: StageAComposeStepStats = {

View file

@ -1,915 +0,0 @@
import { compareAscii } from './exchange-pass1';
import type {
ReadOnlySourceSymbolCursor,
ReadOnlySourceSymbolReader,
SourceSymbolFindOptions,
} from './source-symbol-readers';
export const FIELD_SHAPE_PROBE_COLLECTIONS = Object.freeze([
'ceoShorts',
'qmSplits',
'qmDividends',
'qmFilings',
'qmEarnings',
'qmPrices',
'eodPrices',
'teMarketData',
] as const);
export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number];
export const FIELD_VALUE_TYPES = Object.freeze([
'string',
'int',
'double',
'bool',
'date',
'null',
'objectId',
'array',
'object',
'other',
] as const);
export type FieldValueType = (typeof FIELD_VALUE_TYPES)[number];
export const STRING_PATTERN_CLASSES = Object.freeze([
'ymd',
'isoDatetime',
'numeric',
'emptyOrWhitespace',
'other',
] as const);
export type StringPatternClass = (typeof STRING_PATTERN_CLASSES)[number];
export const DEFAULT_FIELD_SHAPE_LIMIT = 1_000;
export const MAX_FIELD_SHAPE_LIMIT = 10_000;
export const DEFAULT_MAX_EXAMPLES = 3;
export const MAX_EXAMPLES_CAP = 10;
export const DEFAULT_MAX_EXAMPLE_LENGTH = 48;
export const MAX_EXAMPLE_LENGTH_CAP = 120;
const ALLOWED_PROBE_COLLECTION_SET: ReadonlySet<string> = new Set<string>(
FIELD_SHAPE_PROBE_COLLECTIONS
);
export class UnknownProbeCollectionError extends Error {
readonly collectionName: string;
readonly allowedCollections: readonly FieldShapeProbeCollection[];
constructor(collectionName: string) {
super(
`Unknown probe collection "${collectionName}". Allowed collections: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(', ')}`
);
this.name = 'UnknownProbeCollectionError';
this.collectionName = collectionName;
this.allowedCollections = FIELD_SHAPE_PROBE_COLLECTIONS;
Object.setPrototypeOf(this, new.target.prototype);
}
}
export type FieldValueTypeCounts = Record<FieldValueType, number>;
export type StringPatternCounts = Record<StringPatternClass, number>;
export interface FieldStringStats {
minLength: number;
maxLength: number;
patterns: StringPatternCounts;
}
export interface FieldShapeSummary {
field: string;
presentCount: number;
missingCount: number;
typeCounts: FieldValueTypeCounts;
stringStats: FieldStringStats | null;
examples: string[];
}
export interface SummarizeFieldShapesOptions {
readonly maxExamples?: number;
readonly maxExampleLength?: number;
}
export interface CollectionFieldShapesSummary {
docCount: number;
fields: FieldShapeSummary[];
}
export interface ReadFieldShapesOptions extends SummarizeFieldShapesOptions {
readonly collections?: readonly string[];
readonly limit?: number;
readonly batchSize?: number;
}
export interface CollectionFieldShapesProbeResult extends CollectionFieldShapesSummary {
collection: FieldShapeProbeCollection;
}
export interface ReadFieldShapesResult {
limit: number;
maxExamples: number;
maxExampleLength: number;
totalDocsSampled: number;
collections: CollectionFieldShapesProbeResult[];
}
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
const STRICT_ISO_DATETIME_PATTERN =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|([+-])(\d{2}):?(\d{2}))?$/;
const NUMERIC_STRING_PATTERN = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function isValidCalendarDate(year: number, month: number, day: number): boolean {
if (year < 1 || year > 9999 || month < 1 || month > 12) {
return false;
}
const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0);
return day >= 1 && day <= maxDay;
}
function isValidYmd(value: string): boolean {
if (!EXACT_YMD_PATTERN.test(value)) {
return false;
}
const year =
(value.charCodeAt(0) - 48) * 1000 +
(value.charCodeAt(1) - 48) * 100 +
(value.charCodeAt(2) - 48) * 10 +
(value.charCodeAt(3) - 48);
const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48);
const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48);
return isValidCalendarDate(year, month, day);
}
function isValidIsoDatetime(value: string): boolean {
const match = STRICT_ISO_DATETIME_PATTERN.exec(value);
if (match === null) {
return false;
}
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]);
if (!isValidCalendarDate(year, month, day)) {
return false;
}
if (hour > 23 || minute > 59 || second > 59) {
return false;
}
if (match[7] !== undefined) {
const tzHour = Number(match[8]);
const tzMinute = Number(match[9]);
if (tzHour > 23 || tzMinute > 59) {
return false;
}
}
return true;
}
function classifyStringPattern(value: string): StringPatternClass {
if (value.length === 0 || value.trim().length === 0) {
return 'emptyOrWhitespace';
}
if (value.length === 10 && isValidYmd(value)) {
return 'ymd';
}
if (value.length >= 19 && value.charCodeAt(10) === 84 && isValidIsoDatetime(value)) {
return 'isoDatetime';
}
if (NUMERIC_STRING_PATTERN.test(value)) {
return 'numeric';
}
return 'other';
}
function createEmptyTypeCounts(): FieldValueTypeCounts {
return {
string: 0,
int: 0,
double: 0,
bool: 0,
date: 0,
null: 0,
objectId: 0,
array: 0,
object: 0,
other: 0,
};
}
function createEmptyStringPatternCounts(): StringPatternCounts {
return {
ymd: 0,
isoDatetime: 0,
numeric: 0,
emptyOrWhitespace: 0,
other: 0,
};
}
function isNonPlainBuiltInObject(value: object): boolean {
return (
value instanceof Date ||
Array.isArray(value) ||
ArrayBuffer.isView(value) ||
value instanceof ArrayBuffer ||
value instanceof RegExp ||
value instanceof Map ||
value instanceof Set
);
}
function getBsonTypeTag(value: object): string | null {
const tag = (value as { _bsontype?: unknown })._bsontype;
return typeof tag === 'string' && tag.length > 0 ? tag : null;
}
function isPlainNestedObject(value: unknown): value is Record<string, unknown> {
if (value === null || typeof value !== 'object') {
return false;
}
if (isNonPlainBuiltInObject(value)) {
return false;
}
if (getBsonTypeTag(value) !== null) {
return false;
}
return true;
}
function classifyValueType(value: unknown): FieldValueType {
if (value === null) {
return 'null';
}
const primitiveType = typeof value;
if (primitiveType === 'string') {
return 'string';
}
if (primitiveType === 'boolean') {
return 'bool';
}
if (primitiveType === 'number') {
return Number.isInteger(value) ? 'int' : 'double';
}
if (primitiveType === 'bigint') {
return 'int';
}
if (primitiveType !== 'object') {
return 'other';
}
const obj = value as object;
if (obj instanceof Date) {
return 'date';
}
if (Array.isArray(obj)) {
return 'array';
}
const bsonTag = getBsonTypeTag(obj);
if (bsonTag !== null) {
if (bsonTag === 'Int32' || bsonTag === 'Long') {
return 'int';
}
if (bsonTag === 'Double') {
return 'double';
}
if (bsonTag === 'ObjectId' || bsonTag === 'ObjectID') {
return 'objectId';
}
return 'other';
}
if (isNonPlainBuiltInObject(obj)) {
return 'other';
}
return 'object';
}
function escapeFieldSegment(segment: string): string {
if (!segment.includes('.') && !segment.includes('\\')) {
return segment;
}
return segment.replace(/\\/g, '\\\\').replace(/\./g, '\\.');
}
function formatFieldPath(parentKey: string, childKey?: string): string {
const escapedParent = escapeFieldSegment(parentKey);
return childKey === undefined ? escapedParent : `${escapedParent}.${escapeFieldSegment(childKey)}`;
}
function sanitizeAndTruncateExample(raw: string, maxLength: number): string {
let cleaned = '';
for (let i = 0; i < raw.length; i++) {
const code = raw.charCodeAt(i);
if (code === 9 || code === 10 || code === 13) {
cleaned += ' ';
} else if (code >= 32 && code !== 127) {
cleaned += raw[i];
}
}
if (cleaned.length <= maxLength) {
return cleaned;
}
if (maxLength <= 3) {
return cleaned.slice(0, maxLength);
}
return `${cleaned.slice(0, maxLength - 3)}...`;
}
function extractScalarExample(
value: unknown,
valueType: FieldValueType,
maxExampleLength: number
): string | null {
if (valueType === 'null' || valueType === 'array' || valueType === 'object') {
return null;
}
let raw: string | null = null;
if (valueType === 'string') {
raw = value as string;
} else if (valueType === 'bool') {
raw = (value as boolean) ? 'true' : 'false';
} else if (valueType === 'int' || valueType === 'double') {
if (typeof value === 'number' || typeof value === 'bigint') {
raw = String(value);
} else if (value !== null && typeof value === 'object') {
raw = String(value);
}
} else if (valueType === 'date' && value instanceof Date) {
raw = Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString();
} else if (valueType === 'objectId') {
raw = String(value);
} else if (valueType === 'other' && value !== null && typeof value === 'object') {
const bsonTag = getBsonTypeTag(value);
if (bsonTag === 'Decimal128' || bsonTag === 'UUID') {
raw = String(value);
}
}
if (raw === null) {
return null;
}
return sanitizeAndTruncateExample(raw, maxExampleLength);
}
function validateBoundedInt(value: unknown, name: string, min: number, max: number): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) {
throw new RangeError(`${name} must be an integer between ${min} and ${max}, received ${String(value)}`);
}
return value;
}
function validatePositiveSafeInt(value: unknown, name: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`);
}
return value;
}
function resolveSummarizeOptions(options?: SummarizeFieldShapesOptions): {
maxExamples: number;
maxExampleLength: number;
} {
if (options !== undefined && (options === null || typeof options !== 'object')) {
throw new TypeError('options must be an object');
}
const maxExamples =
options?.maxExamples !== undefined
? validateBoundedInt(options.maxExamples, 'options.maxExamples', 0, MAX_EXAMPLES_CAP)
: DEFAULT_MAX_EXAMPLES;
const maxExampleLength =
options?.maxExampleLength !== undefined
? validateBoundedInt(
options.maxExampleLength,
'options.maxExampleLength',
1,
MAX_EXAMPLE_LENGTH_CAP
)
: DEFAULT_MAX_EXAMPLE_LENGTH;
return { maxExamples, maxExampleLength };
}
interface MutableFieldAccumulator {
presentCount: number;
typeCounts: FieldValueTypeCounts;
stringStats: FieldStringStats | null;
examples: string[];
}
/**
* Streaming, order-independent field-shape accumulator shared by `summarizeFieldShapes`
* and `readFieldShapes`. Keeps O(`maxExamples`) distinct ASCII-smallest examples per field.
*/
class FieldShapeAccumulator {
private readonly maxExamples: number;
private readonly maxExampleLength: number;
private readonly fields = new Map<string, MutableFieldAccumulator>();
private docCount = 0;
constructor(maxExamples: number, maxExampleLength: number) {
this.maxExamples = maxExamples;
this.maxExampleLength = maxExampleLength;
}
addDocument(doc: unknown): void {
this.docCount += 1;
if (!isPlainNestedObject(doc)) {
return;
}
const keys = Object.keys(doc);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === undefined) {
continue;
}
const value = doc[key];
if (value === undefined) {
continue;
}
const suppressExamples = key === '_id';
const valueType = this.recordFieldValue(formatFieldPath(key), value, suppressExamples);
if (valueType === 'object' && isPlainNestedObject(value)) {
const childKeys = Object.keys(value);
for (let j = 0; j < childKeys.length; j++) {
const childKey = childKeys[j];
if (childKey === undefined) {
continue;
}
const childValue = value[childKey];
if (childValue === undefined) {
continue;
}
this.recordFieldValue(formatFieldPath(key, childKey), childValue, suppressExamples);
}
}
}
}
finalize(): CollectionFieldShapesSummary {
const sortedNames = Array.from(this.fields.keys()).sort(compareAscii);
const summaries: FieldShapeSummary[] = [];
for (let i = 0; i < sortedNames.length; i++) {
const fieldName = sortedNames[i];
if (fieldName === undefined) {
continue;
}
const acc = this.fields.get(fieldName);
if (acc === undefined) {
continue;
}
summaries.push({
field: fieldName,
presentCount: acc.presentCount,
missingCount: this.docCount - acc.presentCount,
typeCounts: { ...acc.typeCounts },
stringStats:
acc.stringStats === null
? null
: {
minLength: acc.stringStats.minLength,
maxLength: acc.stringStats.maxLength,
patterns: { ...acc.stringStats.patterns },
},
examples: [...acc.examples],
});
}
return {
docCount: this.docCount,
fields: summaries,
};
}
private recordFieldValue(
fieldPath: string,
value: unknown,
suppressExamples: boolean
): FieldValueType {
let acc = this.fields.get(fieldPath);
if (acc === undefined) {
acc = {
presentCount: 0,
typeCounts: createEmptyTypeCounts(),
stringStats: null,
examples: [],
};
this.fields.set(fieldPath, acc);
}
const valueType = classifyValueType(value);
acc.presentCount += 1;
acc.typeCounts[valueType] += 1;
if (valueType === 'string') {
const str = value as string;
const len = str.length;
if (acc.stringStats === null) {
acc.stringStats = {
minLength: len,
maxLength: len,
patterns: createEmptyStringPatternCounts(),
};
} else {
if (len < acc.stringStats.minLength) {
acc.stringStats.minLength = len;
}
if (len > acc.stringStats.maxLength) {
acc.stringStats.maxLength = len;
}
}
acc.stringStats.patterns[classifyStringPattern(str)] += 1;
}
if (this.maxExamples > 0 && !suppressExamples) {
const example = extractScalarExample(value, valueType, this.maxExampleLength);
if (example !== null) {
this.insertExample(acc.examples, example);
}
}
return valueType;
}
private insertExample(examples: string[], candidate: string): void {
const len = examples.length;
const last = len > 0 ? examples[len - 1] : undefined;
if (len === this.maxExamples && last !== undefined && compareAscii(candidate, last) >= 0) {
return;
}
let insertAt = len;
for (let i = 0; i < len; i++) {
const existing = examples[i];
if (existing === undefined) {
continue;
}
const cmp = compareAscii(candidate, existing);
if (cmp === 0) {
return;
}
if (cmp < 0) {
insertAt = i;
break;
}
}
examples.splice(insertAt, 0, candidate);
if (examples.length > this.maxExamples) {
examples.pop();
}
}
}
/**
* Pure, deterministic summarizer for field names, BSON/JS value types, string patterns,
* and bounded sanitized examples across an iterable of documents from one collection.
*/
export function summarizeFieldShapes(
docs: Iterable<Record<string, unknown>>,
options?: SummarizeFieldShapesOptions
): CollectionFieldShapesSummary {
if (
docs === null ||
docs === undefined ||
typeof (docs as unknown as Record<symbol, unknown>)[Symbol.iterator] !== 'function'
) {
throw new TypeError('docs must be an Iterable of document objects');
}
const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options);
const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength);
for (const doc of docs) {
accumulator.addDocument(doc);
}
return accumulator.finalize();
}
export function isFieldShapeProbeCollection(value: string): value is FieldShapeProbeCollection {
return ALLOWED_PROBE_COLLECTION_SET.has(value);
}
export function normalizeProbeCollections(
collections?: readonly string[]
): FieldShapeProbeCollection[] {
const source = collections === undefined ? FIELD_SHAPE_PROBE_COLLECTIONS : collections;
if (!Array.isArray(source) || source.length === 0) {
throw new RangeError('collections must be a non-empty array of allowed probe collection names');
}
const unique = new Set<FieldShapeProbeCollection>();
for (let i = 0; i < source.length; i++) {
const name = source[i];
if (typeof name !== 'string' || !isFieldShapeProbeCollection(name)) {
throw new UnknownProbeCollectionError(String(name));
}
unique.add(name);
}
return Array.from(unique).sort(compareAscii);
}
function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void {
if (
reader === null ||
reader === undefined ||
typeof reader !== 'object' ||
typeof reader.isReadOnly !== 'function' ||
typeof reader.find !== 'function' ||
reader.isReadOnly() !== true
) {
throw new Error(
'Source field-shape probe requires a read-only MongoDB reader (isReadOnly() must be true)'
);
}
}
function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] === 'function'
);
}
function wrapCollectionReadError(collectionName: string, error: unknown): Error {
const detail = error instanceof Error ? error.message : String(error);
const message = detail.includes(collectionName)
? detail
: `Failed reading collection "${collectionName}": ${detail}`;
return new Error(message, { cause: error });
}
async function streamBoundedCollectionIntoAccumulator(
reader: ReadOnlySourceSymbolReader,
collectionName: FieldShapeProbeCollection,
limit: number,
findOptions: SourceSymbolFindOptions,
accumulator: FieldShapeAccumulator
): Promise<void> {
assertReadOnlyReader(reader);
let closableHandle: Pick<ReadOnlySourceSymbolCursor<Record<string, unknown>>, 'close'> | null =
null;
let primaryError: unknown = undefined;
let hasPrimaryError = false;
let isInvalidCursorError = false;
try {
const rawCursor = await reader.find<Record<string, unknown>>(collectionName, {}, findOptions);
if (
rawCursor !== null &&
(typeof rawCursor === 'object' || typeof rawCursor === 'function')
) {
closableHandle = rawCursor as Pick<
ReadOnlySourceSymbolCursor<Record<string, unknown>>,
'close'
>;
}
if (Array.isArray(rawCursor) || !isAsyncIterable<Record<string, unknown>>(rawCursor)) {
isInvalidCursorError = true;
throw new TypeError(
`Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)`
);
}
let seen = 0;
if (limit > 0) {
for await (const doc of rawCursor) {
accumulator.addDocument(doc);
seen += 1;
if (seen >= limit) {
break;
}
}
}
} catch (error) {
primaryError = error;
hasPrimaryError = true;
} finally {
if (closableHandle !== null && typeof closableHandle.close === 'function') {
try {
await closableHandle.close();
} catch (closeError) {
if (!hasPrimaryError) {
primaryError = closeError;
hasPrimaryError = true;
}
}
}
}
if (hasPrimaryError) {
if (isInvalidCursorError) {
throw primaryError;
}
throw wrapCollectionReadError(collectionName, primaryError);
}
}
/**
* Bounded, read-only MongoDB field-shape probe over allowlisted source collections.
* Issues strictly `find({}, { limit, promoteValues: false, promoteLongs: false })`
* with zero aggregations, `$sample`, writes, or index operations.
*/
export async function readFieldShapes(
reader: ReadOnlySourceSymbolReader,
options?: ReadFieldShapesOptions
): Promise<ReadFieldShapesResult> {
assertReadOnlyReader(reader);
if (options !== undefined && (options === null || typeof options !== 'object')) {
throw new TypeError('options must be an object');
}
const limit =
options?.limit !== undefined
? validateBoundedInt(options.limit, 'options.limit', 1, MAX_FIELD_SHAPE_LIMIT)
: DEFAULT_FIELD_SHAPE_LIMIT;
const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options);
const batchSize =
options?.batchSize !== undefined
? validatePositiveSafeInt(options.batchSize, 'options.batchSize')
: undefined;
const collections = normalizeProbeCollections(options?.collections);
const findOptions: SourceSymbolFindOptions = {
limit,
promoteValues: false,
promoteLongs: false,
...(batchSize !== undefined ? { batchSize } : {}),
};
const results: CollectionFieldShapesProbeResult[] = [];
let totalDocsSampled = 0;
for (const collection of collections) {
const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength);
await streamBoundedCollectionIntoAccumulator(
reader,
collection,
limit,
findOptions,
accumulator
);
const summary = accumulator.finalize();
totalDocsSampled += summary.docCount;
results.push({
collection,
docCount: summary.docCount,
fields: summary.fields,
});
}
return {
limit,
maxExamples,
maxExampleLength,
totalDocsSampled,
collections: results,
};
}
function formatHtmlCodeElement(value: string): string {
const escaped = value.replace(/[&<>|\\`*_~[\]!]/g, ch => {
switch (ch) {
case '&':
return '&amp;';
case '<':
return '&lt;';
case '>':
return '&gt;';
case '|':
return '&#124;';
default:
return `&#${ch.charCodeAt(0)};`;
}
});
return `<code>${escaped}</code>`;
}
function formatMarkdownCodeCell(value: string): string {
const normalized = value.replace(/\r\n|\r|\n/g, ' ');
// Empty spans cannot be written with backtick fences; values containing `\|`
// would become `\\|` under pipe escaping, which GFM/micromark parses as an
// escaped backslash followed by a cell-splitting pipe. Use an HTML <code>
// element with entity-encoded pipes and Markdown metacharacters instead.
if (normalized.length === 0 || normalized.includes('\\|')) {
return formatHtmlCodeElement(normalized);
}
const tableSafe = normalized.replace(/\|/g, '\\|');
let maxBacktickRun = 0;
let currentRun = 0;
for (let i = 0; i < tableSafe.length; i++) {
if (tableSafe.charCodeAt(i) === 96) {
currentRun += 1;
if (currentRun > maxBacktickRun) {
maxBacktickRun = currentRun;
}
} else {
currentRun = 0;
}
}
const fence = '`'.repeat(maxBacktickRun + 1);
const startsWithBacktick = tableSafe.charCodeAt(0) === 96;
const endsWithBacktick = tableSafe.charCodeAt(tableSafe.length - 1) === 96;
const startsAndEndsWithSpace =
tableSafe.charCodeAt(0) === 32 &&
tableSafe.charCodeAt(tableSafe.length - 1) === 32 &&
tableSafe.trim().length > 0;
const needsPadding = startsWithBacktick || endsWithBacktick || startsAndEndsWithSpace;
return needsPadding ? `${fence} ${tableSafe} ${fence}` : `${fence}${tableSafe}${fence}`;
}
function formatTypeCountsCell(typeCounts: FieldValueTypeCounts): string {
const parts: string[] = [];
for (const typeName of FIELD_VALUE_TYPES) {
const count = typeCounts[typeName];
if (count > 0) {
parts.push(`${typeName}: ${count}`);
}
}
return parts.length > 0 ? parts.join(', ') : '—';
}
function formatStringStatsCell(stringStats: FieldStringStats | null): string {
if (stringStats === null) {
return '—';
}
const parts: string[] = [];
for (const pattern of STRING_PATTERN_CLASSES) {
const count = stringStats.patterns[pattern];
if (count > 0) {
parts.push(`${pattern}: ${count}`);
}
}
const patternText = parts.length > 0 ? parts.join(', ') : 'none';
return `${patternText} (len ${stringStats.minLength}..${stringStats.maxLength})`;
}
function formatExamplesCell(examples: readonly string[]): string {
if (examples.length === 0) {
return '—';
}
return examples.map(formatMarkdownCodeCell).join(', ');
}
/**
* Renders a deterministic Markdown field-shape report (zero wall-clock timestamps or
* filesystem paths). Identical results always produce byte-identical Markdown.
*/
export function renderFieldShapesMarkdown(result: ReadFieldShapesResult): string {
const sortedCollections = [...result.collections].sort((a, b) =>
compareAscii(a.collection, b.collection)
);
const lines: string[] = [
'# Source Field Shapes Report',
'',
'- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`)',
`- **Sample limit per collection:** ${result.limit}`,
`- **Collections probed:** ${sortedCollections.length}`,
`- **Total documents sampled:** ${result.totalDocsSampled}`,
];
for (const col of sortedCollections) {
lines.push('', `## \`${col.collection}\` (${col.docCount} docs sampled)`, '');
if (col.docCount === 0) {
lines.push('_No documents sampled._');
continue;
}
const sortedFields = [...col.fields].sort((a, b) => compareAscii(a.field, b.field));
if (sortedFields.length === 0) {
lines.push('_No fields observed._');
continue;
}
lines.push('| Field | Presence | Types | String Patterns | Examples |');
lines.push('| --- | --- | --- | --- | --- |');
for (const field of sortedFields) {
const pct = ((field.presentCount / col.docCount) * 100).toFixed(1);
const fieldCell = formatMarkdownCodeCell(field.field);
const presenceCell = `${pct}% (${field.presentCount}/${col.docCount})`;
const typesCell = formatTypeCountsCell(field.typeCounts);
const patternsCell = formatStringStatsCell(field.stringStats);
const examplesCell = formatExamplesCell(field.examples);
lines.push(
`| ${fieldCell} | ${presenceCell} | ${typesCell} | ${patternsCell} | ${examplesCell} |`
);
}
}
return `${lines.join('\n')}\n`;
}

View file

@ -53,9 +53,6 @@ export const DEFAULT_SOURCE_COUNTRIES: readonly string[] = Object.freeze(['US',
export interface SourceSymbolFindOptions {
projection?: Record<string, 0 | 1>;
batchSize?: number;
limit?: number;
promoteValues?: boolean;
promoteLongs?: boolean;
}
/**
@ -164,7 +161,6 @@ export interface ReadSourceCollectionOptions {
readonly knownExchanges?: readonly ExchangeSeedRow[];
readonly batchSize?: number;
readonly maxSecurityTypeConflicts?: number;
readonly includeExtendedMetadata?: boolean;
}
export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions;
@ -179,7 +175,6 @@ export interface AdaptEodSymbolContext {
export interface AdaptIbSymbolContext {
readonly exchangeLookup: ExchangeSourceLookup;
readonly allowedCountries: ReadonlySet<string> | null;
readonly includeExtendedMetadata?: boolean;
}
export interface AdaptQmSymbolContext {
@ -187,7 +182,6 @@ export interface AdaptQmSymbolContext {
readonly barSpans?: Pick<BarSpanIndex, 'get'> | null;
readonly allowedCountries: ReadonlySet<string> | null;
readonly micCurrencyMap: ReadonlyMap<string, string>;
readonly includeExtendedMetadata?: boolean;
}
export interface AdaptCeoSymbolContext {
@ -195,7 +189,6 @@ export interface AdaptCeoSymbolContext {
readonly ceoSpans?: ReadonlyMap<string, SpanDateRange> | null;
readonly allowedCountries: ReadonlySet<string> | null;
readonly micCurrencyMap: ReadonlyMap<string, string>;
readonly includeExtendedMetadata?: boolean;
}
export interface AdaptEodSymbolChangeContext {
@ -446,9 +439,7 @@ export const CEO_SYMBOLS_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.fr
export const EOD_SYMBOL_CHANGE_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
_id: 0,
oldSymbol: 1,
old_symbol: 1,
newSymbol: 1,
new_symbol: 1,
exchange: 1,
eodExchange: 1,
eodSearchCode: 1,
@ -1362,13 +1353,6 @@ export function adaptIbSymbolDoc(
conid: rawConid,
currency,
primaryExchange,
...(context.includeExtendedMetadata === true
? {
ticker: symbolField.value,
name,
exchangeId: exchangeIdField.value !== null ? exchangeIdField.value.toUpperCase() : null,
}
: {}),
},
invalidIdentifiersNulled,
};
@ -1449,11 +1433,6 @@ export function adaptQmSymbolDoc(
: countryFallbackCurrency(effectiveCountry);
const span = toSpanDateRange(context.barSpans?.get('qm', sourceId));
const qmNameResult =
context.includeExtendedMetadata === true
? readFirstOptionalString(doc, ['name', 'companyName'])
: null;
const qmName = qmNameResult !== null && qmNameResult.ok ? qmNameResult.value : null;
return {
ok: true,
@ -1465,7 +1444,6 @@ export function adaptQmSymbolDoc(
role: exchangeEntry.role,
currency,
span,
...(context.includeExtendedMetadata === true ? { name: qmName } : {}),
},
};
}
@ -1558,10 +1536,6 @@ export function adaptCeoSymbolDoc(
}
}
const ceoNameResult =
context.includeExtendedMetadata === true ? readOptionalString(doc, 'name') : null;
const ceoName = ceoNameResult !== null && ceoNameResult.ok ? ceoNameResult.value : null;
return {
ok: true,
tickerSource: {
@ -1572,7 +1546,6 @@ export function adaptCeoSymbolDoc(
role: exchangeEntry.role,
currency,
span,
...(context.includeExtendedMetadata === true ? { name: ceoName } : {}),
},
};
}
@ -1589,8 +1562,8 @@ export function adaptEodSymbolChangeDoc(
return { ok: false, skipReason: 'invalidFieldType' };
}
const oldSymbolField = readFirstOptionalString(doc, ['oldSymbol', 'old_symbol']);
const newSymbolField = readFirstOptionalString(doc, ['newSymbol', 'new_symbol']);
const oldSymbolField = readOptionalString(doc, 'oldSymbol');
const newSymbolField = readOptionalString(doc, 'newSymbol');
const exchangeField = readOptionalString(doc, 'exchange');
const eodExchangeField = readOptionalString(doc, 'eodExchange');
const eodSearchCodeField = readOptionalString(doc, 'eodSearchCode');
@ -1790,7 +1763,6 @@ export async function readIbSymbols(
const context: AdaptIbSymbolContext = {
exchangeLookup: options.exchangeLookup,
allowedCountries,
includeExtendedMetadata: options.includeExtendedMetadata,
};
const stageARecords: StageASourceRecord[] = [];
@ -1839,7 +1811,6 @@ export async function readQmSymbols(
barSpans: options.barSpans,
allowedCountries,
micCurrencyMap,
includeExtendedMetadata: options.includeExtendedMetadata,
};
const tickerSources: StageBTickerSourceInput[] = [];
@ -1872,26 +1843,6 @@ export async function readQmSymbols(
return { tickerSources, stats };
}
function expectedMicFromCeoSymbolSuffix(rawSymbol: unknown): string | null {
if (typeof rawSymbol !== 'string') {
return null;
}
const upper = rawSymbol.trim().toUpperCase();
if (upper.endsWith('.TO')) {
return 'XTSE';
}
if (upper.endsWith('.V')) {
return 'XTSX';
}
if (upper.endsWith('.CN')) {
return 'XCNQ';
}
if (upper.endsWith('.NEO') || upper.endsWith('.NE')) {
return 'NEOE';
}
return null;
}
/** Streams and adapts `ceoSymbols` from a read-only MongoDB reader. */
export async function readCeoSymbols(
reader: ReadOnlySourceSymbolReader,
@ -1904,15 +1855,9 @@ export async function readCeoSymbols(
ceoSpans: options.ceoSpans,
allowedCountries,
micCurrencyMap,
includeExtendedMetadata: options.includeExtendedMetadata,
};
const tickerSources: StageBTickerSourceInput[] = [];
const rawEntries: Array<{
readonly tickerSource: StageBTickerSourceInput;
readonly rawSymbolKey: string | null;
readonly matchesSuffixMic: boolean;
}> = [];
const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.ceo);
const findOptions: SourceSymbolFindOptions = {
@ -1932,59 +1877,11 @@ export async function readCeoSymbols(
stats.skips[adapted.skipReason] += 1;
return;
}
const rawSymbol =
isPlainRecord(doc) && typeof doc.symbol === 'string'
? doc.symbol.trim().toUpperCase()
: null;
const expectedMic = expectedMicFromCeoSymbolSuffix(rawSymbol);
rawEntries.push({
tickerSource: adapted.tickerSource,
rawSymbolKey: rawSymbol !== null && rawSymbol.length > 0 ? rawSymbol : null,
matchesSuffixMic: expectedMic !== null && adapted.tickerSource.mic === expectedMic,
});
tickerSources.push(adapted.tickerSource);
stats.emitted += 1;
}
);
// Deduplicate crawl artifacts where the exact same (ceoId, symbol) was ingested under
// multiple Canadian exchange lists (e.g. ACB.TO under both TSX and CNQ). Prefer the row
// whose mapped MIC matches the symbol's own Canadian venue suffix (.TO/.V/.CN/.NEO).
// Distinct symbols sharing a ceoId are preserved so Stage B still flags true collisions.
const groupedByIdAndSymbol = new Map<string, typeof rawEntries>();
for (const entry of rawEntries) {
if (entry.rawSymbolKey === null) {
tickerSources.push(entry.tickerSource);
stats.emitted += 1;
continue;
}
const key = `${entry.tickerSource.sourceId}\u0000${entry.rawSymbolKey}`;
const existing = groupedByIdAndSymbol.get(key);
if (existing !== undefined) {
existing.push(entry);
} else {
groupedByIdAndSymbol.set(key, [entry]);
}
}
for (const entries of groupedByIdAndSymbol.values()) {
const first = entries[0];
if (first === undefined) {
continue;
}
if (entries.length === 1) {
tickerSources.push(first.tickerSource);
stats.emitted += 1;
continue;
}
const suffixMatched = entries.filter(e => e.matchesSuffixMic);
const chosen =
suffixMatched.length === 1 && suffixMatched[0] !== undefined
? suffixMatched[0]
: ([...entries].sort((a, b) => compareTickerSources(a.tickerSource, b.tickerSource))[0] ??
first);
tickerSources.push(chosen.tickerSource);
stats.emitted += 1;
}
tickerSources.sort(compareTickerSources);
return { tickerSources, stats };

View file

@ -1,293 +0,0 @@
import { describe, expect, mock, test } from 'bun:test';
import { createHash } from 'node:crypto';
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { BSON } from 'mongodb';
import {
createReadOnlyMongoRawBsonSource,
exportRawBsonCollection,
RawBsonExportError,
validateRawBsonFrame,
walkRawBsonFrames,
type ExportRawBsonFsHooks,
type ReadOnlyMongoRawBsonClient,
type ReadOnlyRawBsonSource,
} from '../src/security-master/export-raw-bson';
import { runExportRawBson } from '../src/security-master/run-export-raw-bson';
function sha256Hex(bytes: Uint8Array): string {
return createHash('sha256').update(bytes).digest('hex');
}
function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
const out = new Uint8Array(chunks.reduce((acc, c) => acc + c.byteLength, 0));
let offset = 0;
for (const chunk of chunks) {
out.set(chunk, offset);
offset += chunk.byteLength;
}
return out;
}
function sourceOf(docs: readonly unknown[], onYield?: () => void): ReadOnlyRawBsonSource {
return {
isReadOnly: () => true,
find: () => ({
async *[Symbol.asyncIterator]() {
for (const doc of docs) {
onYield?.();
yield doc;
}
},
}),
};
}
async function withTempDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
const dir = await mkdtemp(join(tmpdir(), 'export-raw-bson-qa-'));
try {
return await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
/**
* The mongodb 6.x driver returns `raw: true` documents as `subarray` views into the shared
* wire-reply buffer (`OnDemandDocument.toBytes`), so frames have non-zero `byteOffset` and
* neighbouring bytes belong to other documents / reply headers.
*/
function packAsReplyViews(docs: readonly Uint8Array[]): Uint8Array[] {
const junk = new Uint8Array([0xde, 0xad, 0xbe, 0xef, 0x07]);
const reply = concatBytes(docs.flatMap(d => [junk, d]).concat([junk]));
const views: Uint8Array[] = [];
let offset = 0;
for (const doc of docs) {
offset += junk.byteLength;
views.push(Buffer.from(reply.buffer, reply.byteOffset + offset, doc.byteLength));
offset += doc.byteLength;
}
return views;
}
describe('exportRawBsonCollection (QA edge cases)', () => {
test('writes only the frame bytes when raw documents are offset views into a shared reply buffer (buffered and direct-write paths, real fs)', async () => {
const small = Array.from({ length: 40 }, (_, i) =>
Uint8Array.from(BSON.serialize({ eodSearchCode: `S${i}.US`, close: i + 0.5 }))
);
const large = Uint8Array.from(BSON.serialize({ eodSearchCode: 'BIG.US', pad: 'z'.repeat(300) }));
const originals = [...small.slice(0, 20), large, ...small.slice(20)];
const views = packAsReplyViews(originals);
expect(views.every(v => v.byteOffset > 0)).toBe(true);
const expected = concatBytes(originals);
await withTempDir(async outDir => {
const result = await exportRawBsonCollection(sourceOf(views), {
collection: 'eodPrices',
outDir,
writeBufferBytes: 128,
});
const fileBytes = Uint8Array.from(await readFile(result.outPath));
expect(fileBytes).toEqual(expected);
expect(result.sha256).toBe(sha256Hex(expected));
expect(result.docsWritten).toBe(originals.length);
expect(walkRawBsonFrames(fileBytes).map(f => BSON.deserialize(f))).toEqual(
originals.map(o => BSON.deserialize(o))
);
});
});
test('flushes correctly when frames exactly fill the write buffer', async () => {
const doc = Uint8Array.from(BSON.serialize({ k: 'v' }));
const writeBufferBytes = Math.max(64, doc.byteLength * 4);
const perBuffer = Math.floor(writeBufferBytes / doc.byteLength);
const docs = Array.from({ length: perBuffer * 3 }, () => doc);
const writes: number[] = [];
await withTempDir(async outDir => {
const fsHooks: ExportRawBsonFsHooks = {
open: async () => ({
write: async (_b, _o, len) => {
writes.push(len ?? 0);
return { bytesWritten: len ?? 0 };
},
sync: async () => {},
close: async () => {},
}),
rename: async () => {},
unlink: async () => {},
};
const result = await exportRawBsonCollection(sourceOf(docs), {
collection: 'qmEarnings',
outDir,
writeBufferBytes,
fs: fsHooks,
});
expect(result.bytesWritten).toBe(doc.byteLength * docs.length);
expect(writes.reduce((a, b) => a + b, 0)).toBe(result.bytesWritten);
expect(writes.every(w => w <= writeBufferBytes)).toBe(true);
expect(writes).toHaveLength(3);
});
});
test('completes partial writes by continuing from the reported offset', async () => {
const docs = Array.from({ length: 10 }, (_, i) => Uint8Array.from(BSON.serialize({ i })));
const expected = concatBytes(docs);
const received: Uint8Array[] = [];
await withTempDir(async outDir => {
const fsHooks: ExportRawBsonFsHooks = {
open: async () => ({
write: async (buf, off, len) => {
const start = off ?? 0;
const n = Math.min(len ?? 0, 7);
received.push(Uint8Array.from(buf.subarray(start, start + n)));
return { bytesWritten: n };
},
sync: async () => {},
close: async () => {},
}),
rename: async () => {},
unlink: async () => {},
};
const result = await exportRawBsonCollection(sourceOf(docs), {
collection: 'qmSplits',
outDir,
writeBufferBytes: 64,
fs: fsHooks,
});
expect(concatBytes(received)).toEqual(expected);
expect(result.sha256).toBe(sha256Hex(expected));
});
});
test('stops pulling from the source once limit is reached', async () => {
const docs = Array.from({ length: 50 }, (_, i) => Uint8Array.from(BSON.serialize({ i })));
let pulled = 0;
await withTempDir(async outDir => {
const result = await exportRawBsonCollection(
sourceOf(docs, () => {
pulled += 1;
}),
{ collection: 'eodPrices', outDir, limit: 3 }
);
expect(result.docsWritten).toBe(3);
expect(pulled).toBe(3);
expect(Uint8Array.from(await readFile(result.outPath))).toEqual(concatBytes(docs.slice(0, 3)));
});
});
test('creates a missing nested out-dir and leaves no temp files after success', async () => {
await withTempDir(async root => {
const outDir = join(root, 'a', 'b');
const doc = Uint8Array.from(BSON.serialize({ x: 1 }));
const result = await exportRawBsonCollection(sourceOf([doc]), { collection: 'qmFilings', outDir });
expect(await readdir(outDir)).toEqual(['qmFilings.bson']);
expect(result.outPath).toBe(join(outDir, 'qmFilings.bson'));
});
});
test('rejects frames whose length prefix has the sign bit set (negative int32)', () => {
const frame = new Uint8Array([0xff, 0xff, 0xff, 0xff, 0x00]);
expect(() => validateRawBsonFrame(frame, 'eodPrices', 7)).toThrow(RawBsonExportError);
expect(() => walkRawBsonFrames(frame)).toThrow(/corrupt BSON document length -1/);
});
test('walkRawBsonFrames rejects truncated trailing bytes like curate-etl iter_raw_bson_docs', () => {
const doc = Uint8Array.from(BSON.serialize({ a: 1 }));
expect(() => walkRawBsonFrames(concatBytes([doc, new Uint8Array([1, 2])]))).toThrow(
/truncated BSON length prefix/
);
expect(() => walkRawBsonFrames(concatBytes([doc, doc.subarray(0, doc.byteLength - 1)]))).toThrow(
/truncated BSON document/
);
expect(walkRawBsonFrames(new Uint8Array())).toEqual([]);
});
test('rejects out-of-range writeBufferBytes, batchSize and limit before any fs or source call', async () => {
const openMock = mock(async () => {
throw new Error('open must not be called');
});
const findMock = mock(() => {
throw new Error('find must not be called');
});
const source: ReadOnlyRawBsonSource = { isReadOnly: () => true, find: findMock };
const bad = [
{ writeBufferBytes: 63 },
{ writeBufferBytes: 64 * 1024 * 1024 + 1 },
{ writeBufferBytes: 100.5 },
{ batchSize: 0 },
{ batchSize: 100_001 },
{ limit: 0 },
{ limit: -1 },
{ maxDocBytes: 4 },
{ eodSymbol: ' ' },
];
for (const opts of bad) {
await expect(
exportRawBsonCollection(source, { collection: 'eodPrices', outDir: '/tmp/unused', fs: { open: openMock }, ...opts })
).rejects.toMatchObject({ code: 'INVALID_OPTION' });
}
await expect(
exportRawBsonCollection(source, { collection: 'eodPrices', outDir: ' ', fs: { open: openMock } })
).rejects.toMatchObject({ code: 'INVALID_OPTION' });
expect(openMock).not.toHaveBeenCalled();
expect(findMock).not.toHaveBeenCalled();
});
});
describe('runExportRawBson multi-collection (QA edge cases)', () => {
test('a failure in a later collection keeps earlier published files, preserves that collection\'s previous output, and closes the client once', async () => {
await withTempDir(async outDir => {
const splitsDoc = Uint8Array.from(BSON.serialize({ split: '2:1' }));
const previousDividends = Uint8Array.from(BSON.serialize({ previous: true }));
await writeFile(join(outDir, 'qmDividends.bson'), previousDividends);
const closeMongo = mock(async () => {});
const findCalls: string[] = [];
const client: ReadOnlyMongoRawBsonClient = {
isReadOnly: () => true,
getCollection: name => ({
find: () => {
findCalls.push(name);
return {
async *[Symbol.asyncIterator]() {
if (name === 'qmSplits') {
yield splitsDoc;
return;
}
yield new Uint8Array([9, 0, 0, 0, 0]);
},
};
},
}),
};
await expect(
runExportRawBson(
{ createMongoClient: () => ({ client, close: closeMongo }), writeStdout: () => {} },
{ outDir, collections: ['qmSplits', 'qmDividends', 'qmEarnings'] }
)
).rejects.toMatchObject({ code: 'INVALID_BSON_FRAME', collection: 'qmDividends', docOrdinal: 0 });
expect(findCalls).toEqual(['qmSplits', 'qmDividends']);
expect(closeMongo).toHaveBeenCalledTimes(1);
expect((await readdir(outDir)).sort()).toEqual(['qmDividends.bson', 'qmSplits.bson']);
expect(Uint8Array.from(await readFile(join(outDir, 'qmSplits.bson')))).toEqual(splitsDoc);
expect(Uint8Array.from(await readFile(join(outDir, 'qmDividends.bson')))).toEqual(previousDividends);
});
});
test('createReadOnlyMongoRawBsonSource re-checks read-only mode at find time', () => {
let readOnly = true;
const getCollection = mock(() => ({
find: () => ({ async *[Symbol.asyncIterator]() {} }),
}));
const source = createReadOnlyMongoRawBsonSource({ isReadOnly: () => readOnly, getCollection });
readOnly = false;
expect(() => source.find('eodPrices', {}, { raw: true })).toThrow(RawBsonExportError);
expect(getCollection).not.toHaveBeenCalled();
});
});

View file

@ -1,667 +0,0 @@
import { describe, expect, mock, test } from 'bun:test';
import { createHash } from 'node:crypto';
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { BSON } from 'mongodb';
import {
createReadOnlyMongoRawBsonSource,
exportRawBsonCollection,
RAW_BSON_EXPORT_COLLECTIONS,
RawBsonExportError,
validateRawBsonFrame,
walkRawBsonFrames,
type ExportRawBsonFileHandle,
type ExportRawBsonFsHooks,
type RawBsonFindOptions,
type ReadOnlyMongoRawBsonClient,
type ReadOnlyRawBsonSource,
} from '../src/security-master/export-raw-bson';
const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
function sha256Hex(bytes: Uint8Array): string {
return createHash('sha256').update(bytes).digest('hex');
}
function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
const total = chunks.reduce((acc, c) => acc + c.byteLength, 0);
const out = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
out.set(chunk, offset);
offset += chunk.byteLength;
}
return out;
}
function createFakeSource(
docs: readonly unknown[],
options: {
readOnly?: boolean;
errorAfter?: number;
error?: Error;
onFind?: (collection: string, filter: Record<string, unknown>, findOpts: RawBsonFindOptions) => void;
onCursorClose?: () => void;
} = {}
): ReadOnlyRawBsonSource {
const readOnly = options.readOnly ?? true;
return {
isReadOnly: () => readOnly,
find(collection, filter, findOpts) {
options.onFind?.(collection, filter, findOpts);
return {
async *[Symbol.asyncIterator]() {
let index = 0;
try {
for (const doc of docs) {
if (options.errorAfter !== undefined && index === options.errorAfter) {
throw options.error ?? new Error('Simulated mid-stream cursor failure');
}
yield doc;
index += 1;
}
} finally {
options.onCursorClose?.();
}
},
};
},
};
}
async function withTempDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
const dir = await mkdtemp(join(tmpdir(), 'export-raw-bson-test-'));
try {
return await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
describe('exportRawBsonCollection', () => {
test('streams raw BSON frames verbatim, matches concatenation, round-trips via 4-byte LE framing, and is deterministic', async () => {
const originalDocs = [
{
eodSearchCode: 'AAPL.US',
date: '2025-01-02',
open: 248.93,
high: 249.1,
low: 241.82,
close: 243.85,
volume: 55740731,
ts: new Date('2025-01-02T21:00:00.000Z'),
meta: { exchange: 'US', adjusted: false },
},
{
eodSearchCode: 'RY.TO',
date: '2025-01-02',
open: 173.4,
high: 175.0,
low: 172.8,
close: 174.65,
volume: 2150000,
tags: ['CA', 'TSX'],
},
{
eodSearchCode: 'NVDA.US',
date: '2024-06-10',
open: 120.37,
high: 123.1,
low: 117.01,
close: 121.79,
volume: 314162700,
},
];
const serialized = originalDocs.map(doc => Uint8Array.from(BSON.serialize(doc)));
const expectedBytes = concatBytes(serialized);
const expectedSha = sha256Hex(expectedBytes);
await withTempDir(async outDir => {
const findCalls: Array<{
collection: string;
filter: Record<string, unknown>;
options: RawBsonFindOptions;
}> = [];
const source = createFakeSource(serialized, {
onFind: (collection, filter, options) => {
findCalls.push({ collection, filter, options });
},
});
const run1 = await exportRawBsonCollection(source, {
collection: 'eodPrices',
outDir,
});
expect(run1.collection).toBe('eodPrices');
expect(run1.outPath).toBe(join(outDir, 'eodPrices.bson'));
expect(run1.docsWritten).toBe(originalDocs.length);
expect(run1.bytesWritten).toBe(expectedBytes.byteLength);
expect(run1.elapsedMs).toBeGreaterThanOrEqual(0);
expect(run1.sha256).toBe(expectedSha);
expect(run1.filter).toEqual({});
expect(findCalls).toEqual([
{
collection: 'eodPrices',
filter: {},
options: { raw: true, batchSize: 4096 },
},
]);
const fileBytes = Uint8Array.from(await readFile(run1.outPath));
expect(fileBytes).toEqual(expectedBytes);
// Cross-language framing parity: walk output by 4-byte LE length prefix
const walked = walkRawBsonFrames(fileBytes);
expect(walked).toHaveLength(originalDocs.length);
for (let i = 0; i < originalDocs.length; i++) {
const frame = walked[i];
expect(frame).toEqual(serialized[i]);
expect(BSON.deserialize(frame!)).toEqual(originalDocs[i]);
}
// Determinism / replay invariant: running twice yields byte-identical output and sha256
const run2 = await exportRawBsonCollection(source, {
collection: 'eodPrices',
outDir,
});
const fileBytes2 = Uint8Array.from(await readFile(run2.outPath));
expect(run2.sha256).toBe(run1.sha256);
expect(run2.bytesWritten).toBe(run1.bytesWritten);
expect(fileBytes2).toEqual(fileBytes);
expect(await readdir(outDir)).toEqual(['eodPrices.bson']);
});
});
test('publishes a 0-byte file with docsWritten === 0 and empty SHA-256 for an empty collection', async () => {
await withTempDir(async outDir => {
const source = createFakeSource([]);
const result = await exportRawBsonCollection(source, {
collection: 'ceoShorts',
outDir,
});
expect(result.collection).toBe('ceoShorts');
expect(result.docsWritten).toBe(0);
expect(result.bytesWritten).toBe(0);
expect(result.sha256).toBe(EMPTY_SHA256);
const fileBytes = await readFile(result.outPath);
expect(fileBytes.byteLength).toBe(0);
expect(await readdir(outDir)).toEqual(['ceoShorts.bson']);
});
});
test('rejects invalid BSON frames with typed error naming collection and ordinal, cleans temp file, and preserves existing output', async () => {
const validDoc = Uint8Array.from(BSON.serialize({ a: 1 }));
const shortFrame = new Uint8Array([4, 0, 0, 0]);
const tooSmallPrefix = Uint8Array.from(validDoc);
tooSmallPrefix[0] = (tooSmallPrefix[0] ?? 0) - 1;
const tooLargePrefix = Uint8Array.from(validDoc);
tooLargePrefix[0] = (tooLargePrefix[0] ?? 0) + 1;
const missingTerminator = Uint8Array.from(validDoc);
missingTerminator[missingTerminator.byteLength - 1] = 0x01;
const oversizedDoc = Uint8Array.from(BSON.serialize({ payload: 'x'.repeat(200) }));
const cases: Array<{
name: string;
docs: unknown[];
expectedOrdinal: number;
maxDocBytes?: number;
}> = [
{ name: 'shorter than 5 bytes', docs: [validDoc, shortFrame], expectedOrdinal: 1 },
{ name: 'LE prefix smaller than byteLength', docs: [validDoc, tooSmallPrefix], expectedOrdinal: 1 },
{ name: 'LE prefix larger than byteLength', docs: [tooLargePrefix], expectedOrdinal: 0 },
{ name: 'missing trailing 0x00', docs: [validDoc, validDoc, missingTerminator], expectedOrdinal: 2 },
{ name: 'non-Uint8Array chunk', docs: [validDoc, { plain: 'object' }], expectedOrdinal: 1 },
{
name: 'exceeds maxDocBytes',
docs: [validDoc, oversizedDoc],
expectedOrdinal: 1,
maxDocBytes: 64,
},
];
for (const c of cases) {
await withTempDir(async outDir => {
const existingPath = join(outDir, 'qmSplits.bson');
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: c.name }));
await writeFile(existingPath, sentinel);
const source = createFakeSource(c.docs);
let caught: unknown;
try {
await exportRawBsonCollection(source, {
collection: 'qmSplits',
outDir,
maxDocBytes: c.maxDocBytes,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(RawBsonExportError);
const typed = caught as RawBsonExportError;
expect(typed.code).toBe('INVALID_BSON_FRAME');
expect(typed.collection).toBe('qmSplits');
expect(typed.docOrdinal).toBe(c.expectedOrdinal);
expect(typed.message).toContain('qmSplits');
expect(typed.message).toContain(`doc#${c.expectedOrdinal}`);
// No temp file left behind and pre-existing output is byte-identical
expect(await readdir(outDir)).toEqual(['qmSplits.bson']);
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
});
}
});
test('cleans up temp file, closes cursor/handle, and preserves existing output on mid-stream cursor, write, short-write, fsync, and rename errors', async () => {
const docs = [
Uint8Array.from(BSON.serialize({ seq: 0 })),
Uint8Array.from(BSON.serialize({ seq: 1 })),
Uint8Array.from(BSON.serialize({ seq: 2 })),
];
// 1. Mid-stream cursor error
await withTempDir(async outDir => {
const existingPath = join(outDir, 'qmDividends.bson');
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'cursor-err' }));
await writeFile(existingPath, sentinel);
let cursorClosed = false;
const source = createFakeSource(docs, {
errorAfter: 2,
error: new Error('Cursor network reset'),
onCursorClose: () => {
cursorClosed = true;
},
});
await expect(
exportRawBsonCollection(source, { collection: 'qmDividends', outDir })
).rejects.toThrow('Cursor network reset');
expect(cursorClosed).toBe(true);
expect(await readdir(outDir)).toEqual(['qmDividends.bson']);
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
});
// 2. Write, short-write, fsync, and rename errors
const failureModes = ['write', 'shortWrite', 'sync', 'rename'] as const;
for (const mode of failureModes) {
await withTempDir(async outDir => {
const existingPath = join(outDir, 'qmPrices.bson');
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: mode }));
await writeFile(existingPath, sentinel);
let handleClosed = false;
let tempFileCreated: string | null = null;
let unlinkedPath: string | null = null;
const fsHooks: ExportRawBsonFsHooks = {
open: async (filePath: string) => {
tempFileCreated = filePath;
await writeFile(filePath, new Uint8Array());
const handle: ExportRawBsonFileHandle = {
write: async (_buf, _off, len) => {
if (mode === 'write') {
throw new Error('ENOSPC simulated write failure');
}
if (mode === 'shortWrite') {
return { bytesWritten: 0 };
}
return { bytesWritten: len ?? 0 };
},
sync: async () => {
if (mode === 'sync') {
throw new Error('EIO simulated fsync failure');
}
},
close: async () => {
handleClosed = true;
},
};
return handle;
},
rename: async () => {
if (mode === 'rename') {
throw new Error('EXDEV simulated rename failure');
}
},
unlink: async filePath => {
unlinkedPath = String(filePath);
await rm(filePath, { force: true });
},
};
const source = createFakeSource(docs);
await expect(
exportRawBsonCollection(source, {
collection: 'qmPrices',
outDir,
fs: fsHooks,
})
).rejects.toThrow();
expect(handleClosed).toBe(true);
expect(tempFileCreated).not.toBeNull();
expect(unlinkedPath).toBe(tempFileCreated);
expect(await readdir(outDir)).toEqual(['qmPrices.bson']);
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
});
}
});
test('enforces bounded write buffer size, handles oversized single docs, and strictly awaits write backpressure', async () => {
const smallDocs = Array.from({ length: 120 }, (_, i) =>
Uint8Array.from(
BSON.serialize({
eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`,
date: '2025-01-02',
open: 10 + i,
close: 11 + i,
volume: 1000 + i,
})
)
);
const largeDoc = Uint8Array.from(
BSON.serialize({
eodSearchCode: 'LARGE.US',
payload: 'A'.repeat(350),
})
);
const allDocs = [...smallDocs.slice(0, 60), largeDoc, ...smallDocs.slice(60)];
const expectedConcat = concatBytes(allDocs);
const writeBufferBytes = 256;
expect(largeDoc.byteLength).toBeGreaterThan(writeBufferBytes);
const writeLengths: number[] = [];
const writtenChunks: Uint8Array[] = [];
let inFlight = 0;
let maxInFlight = 0;
await withTempDir(async outDir => {
const fsHooks: ExportRawBsonFsHooks = {
open: async () => ({
write: async (buf, offset, length) => {
inFlight += 1;
if (inFlight > maxInFlight) {
maxInFlight = inFlight;
}
const start = offset ?? 0;
const len = length ?? buf.byteLength - start;
writeLengths.push(len);
// Copy slice immediately to simulate kernel read of buffer before async completion
const copy = Uint8Array.from(buf.subarray(start, start + len));
await new Promise<void>(resolve => setTimeout(resolve, 0));
writtenChunks.push(copy);
inFlight -= 1;
return { bytesWritten: len };
},
sync: async () => {},
close: async () => {},
}),
rename: async () => {},
unlink: async () => {},
};
const source = createFakeSource(allDocs);
const result = await exportRawBsonCollection(source, {
collection: 'eodPrices',
outDir,
writeBufferBytes,
fs: fsHooks,
});
expect(maxInFlight).toBe(1);
expect(writeLengths.length).toBeGreaterThan(10);
// Every write must be <= writeBufferBytes except the single oversized document write
const oversizedWrites = writeLengths.filter(len => len > writeBufferBytes);
expect(oversizedWrites).toEqual([largeDoc.byteLength]);
for (const len of writeLengths) {
expect(len).toBeLessThanOrEqual(Math.max(writeBufferBytes, largeDoc.byteLength));
}
const assembled = concatBytes(writtenChunks);
expect(assembled).toEqual(expectedConcat);
expect(result.docsWritten).toBe(allDocs.length);
expect(result.bytesWritten).toBe(expectedConcat.byteLength);
expect(result.sha256).toBe(sha256Hex(expectedConcat));
});
});
test('rejects disallowed collections, invalid filters, and non-read-only sources before any source or fs call', async () => {
const findMock = mock(() => {
throw new Error('source.find should never be called');
});
const openMock = mock(async () => {
throw new Error('fs.open should never be called');
});
const source: ReadOnlyRawBsonSource = {
isReadOnly: () => true,
find: findMock,
};
const fsHooks: ExportRawBsonFsHooks = { open: openMock };
for (const disallowed of ['eodIntraday1M', 'qmIntraday', 'qmFinancials', 'ceoPosts', 'symbols']) {
await expect(
exportRawBsonCollection(source, { collection: disallowed, outDir: '/tmp/unused', fs: fsHooks })
).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION', collection: disallowed });
}
await expect(
exportRawBsonCollection(source, {
collection: 'teMarketData',
outDir: '/tmp/unused',
eodSymbol: 'CAD.FOREX',
fs: fsHooks,
})
).rejects.toMatchObject({ code: 'INVALID_OPTION' });
await expect(
exportRawBsonCollection(source, {
collection: 'eodPrices',
outDir: '/tmp/unused',
teSymbol: 'USDCAD',
fs: fsHooks,
})
).rejects.toMatchObject({ code: 'INVALID_OPTION' });
const writableSource: ReadOnlyRawBsonSource = {
isReadOnly: () => false,
find: findMock,
};
await expect(
exportRawBsonCollection(writableSource, {
collection: 'eodPrices',
outDir: '/tmp/unused',
fs: fsHooks,
})
).rejects.toMatchObject({ code: 'INVALID_SOURCE' });
expect(findMock).not.toHaveBeenCalled();
expect(openMock).not.toHaveBeenCalled();
});
test('applies eodSymbol, teSymbol, and limit filters and defensively caps output at limit', async () => {
const docs = Array.from({ length: 5 }, (_, i) =>
Uint8Array.from(BSON.serialize({ seq: i }))
);
await withTempDir(async outDir => {
const calls: Array<{ collection: string; filter: Record<string, unknown>; options: RawBsonFindOptions }> = [];
const source = createFakeSource(docs, {
onFind: (collection, filter, options) => {
calls.push({ collection, filter, options });
},
});
const eodRes = await exportRawBsonCollection(source, {
collection: 'eodPrices',
outDir,
eodSymbol: 'CAD.FOREX',
limit: 2,
batchSize: 64,
});
expect(eodRes.docsWritten).toBe(2);
expect(eodRes.filter).toEqual({ eodSearchCode: 'CAD.FOREX' });
expect(calls[0]).toEqual({
collection: 'eodPrices',
filter: { eodSearchCode: 'CAD.FOREX' },
options: { raw: true, batchSize: 64, limit: 2 },
});
const teRes = await exportRawBsonCollection(source, {
collection: 'teMarketData',
outDir,
teSymbol: 'USDCAD',
limit: 3,
});
expect(teRes.docsWritten).toBe(3);
expect(teRes.filter).toEqual({ teSymbol: 'USDCAD' });
expect(calls[1]).toEqual({
collection: 'teMarketData',
filter: { teSymbol: 'USDCAD' },
options: { raw: true, batchSize: 4096, limit: 3 },
});
});
});
test('createReadOnlyMongoRawBsonSource enforces read-only, rejects buffered arrays, and always closes cursors', async () => {
const writableClient: ReadOnlyMongoRawBsonClient = {
isReadOnly: () => false,
getCollection: () => {
throw new Error('should not be called');
},
};
expect(() => createReadOnlyMongoRawBsonSource(writableClient)).toThrow(RawBsonExportError);
const bufferedArrayClient: ReadOnlyMongoRawBsonClient = {
isReadOnly: () => true,
getCollection: () => ({
find: () => [] as unknown as ReturnType<ReadOnlyMongoRawBsonClient['getCollection']> extends {
find: (...args: never[]) => infer R;
}
? R
: never,
}),
};
const badSource = createReadOnlyMongoRawBsonSource(bufferedArrayClient);
expect(() => badSource.find('eodPrices', {}, { raw: true })).toThrow(RawBsonExportError);
// Cursor close is called on normal exhaustion and early break
const closeMock = mock(async () => {});
const docs = [
Uint8Array.from(BSON.serialize({ a: 1 })),
Uint8Array.from(BSON.serialize({ a: 2 })),
Uint8Array.from(BSON.serialize({ a: 3 })),
];
const goodClient: ReadOnlyMongoRawBsonClient = {
isReadOnly: () => true,
getCollection: () => ({
find: () => ({
close: closeMock,
async *[Symbol.asyncIterator]() {
for (const d of docs) {
yield d;
}
},
}),
}),
};
const source = createReadOnlyMongoRawBsonSource(goodClient);
await withTempDir(async outDir => {
const res = await exportRawBsonCollection(source, {
collection: 'qmFilings',
outDir,
limit: 1,
});
expect(res.docsWritten).toBe(1);
expect(closeMock).toHaveBeenCalledTimes(1);
});
// Limited export with rejecting cursor.close() must surface the close error,
// clean up the temp file, and leave any pre-existing output file byte-identical.
const rejectingCloseClient: ReadOnlyMongoRawBsonClient = {
isReadOnly: () => true,
getCollection: () => ({
find: () => ({
close: async () => {
throw new Error('Cursor close rejected after limit break');
},
async *[Symbol.asyncIterator]() {
for (const d of docs) {
yield d;
}
},
}),
}),
};
const rejectingSource = createReadOnlyMongoRawBsonSource(rejectingCloseClient);
await withTempDir(async outDir => {
const existingPath = join(outDir, 'qmFilings.bson');
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'preserve-on-close-error' }));
await writeFile(existingPath, sentinel);
await expect(
exportRawBsonCollection(rejectingSource, {
collection: 'qmFilings',
outDir,
limit: 1,
})
).rejects.toThrow('Cursor close rejected after limit break');
expect(await readdir(outDir)).toEqual(['qmFilings.bson']);
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
});
// When iteration itself fails AND cursor.close() rejects, the primary iteration error wins.
const dualFailureClient: ReadOnlyMongoRawBsonClient = {
isReadOnly: () => true,
getCollection: () => ({
find: () => ({
close: async () => {
throw new Error('Secondary cursor close failure');
},
async *[Symbol.asyncIterator]() {
yield docs[0];
throw new Error('Primary cursor iteration failure');
},
}),
}),
};
const dualFailureSource = createReadOnlyMongoRawBsonSource(dualFailureClient);
await withTempDir(async outDir => {
await expect(
exportRawBsonCollection(dualFailureSource, {
collection: 'qmFilings',
outDir,
})
).rejects.toThrow('Primary cursor iteration failure');
expect(await readdir(outDir)).toEqual([]);
});
});
test('exports exact M1 allowlist of 8 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => {
expect([...RAW_BSON_EXPORT_COLLECTIONS]).toEqual([
'eodPrices',
'qmSplits',
'qmDividends',
'qmPrices',
'teMarketData',
'ceoShorts',
'qmFilings',
'qmEarnings',
]);
const emptyBson = new Uint8Array([5, 0, 0, 0, 0]);
expect(validateRawBsonFrame(emptyBson, 'eodPrices', 0)).toBe(emptyBson);
});
});

View file

@ -1,399 +0,0 @@
import { describe, expect, mock, test } from 'bun:test';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { BSON } from 'mongodb';
import {
DEFAULT_RAW_BSON_BATCH_SIZE,
RAW_BSON_EXPORT_COLLECTIONS,
RawBsonExportError,
type ReadOnlyMongoRawBsonClient,
} from '../src/security-master/export-raw-bson';
import {
assertExportRawBsonSafety,
EXPORT_RAW_BSON_USAGE,
parseExportRawBsonArgs,
runCli,
runExportRawBson,
} from '../src/security-master/run-export-raw-bson';
function createBaseConfig(overrides: Partial<StockAppConfig['database']['mongodb']> = {}): StockAppConfig {
return {
environment: 'development',
database: {
postgres: {
enabled: true,
host: 'localhost',
port: 5432,
database: 'trading_bot',
user: 'trading_user',
password: 'pw',
ssl: false,
poolSize: 5,
idleTimeout: 10000,
connectionTimeout: 5000,
},
mongodb: {
enabled: true,
uri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock',
readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock',
readOnly: true,
host: 'localhost',
port: 27017,
database: 'stock',
poolSize: 5,
...overrides,
},
dragonfly: {
enabled: false,
host: 'localhost',
port: 6380,
},
questdb: {
enabled: false,
host: 'localhost',
port: 9100,
},
},
} as unknown as StockAppConfig;
}
describe('parseExportRawBsonArgs', () => {
test('parses valid flags in both space-separated and equals forms', () => {
const parsed1 = parseExportRawBsonArgs([
'--out-dir',
'./tmp/bson',
'--collections',
'eodPrices',
'--eod-symbol',
'CAD.FOREX',
'--limit',
'100',
'--batch-size',
'512',
]);
expect(parsed1).toEqual({
help: false,
outDir: './tmp/bson',
collections: ['eodPrices'],
eodSymbol: 'CAD.FOREX',
limit: 100,
batchSize: 512,
});
const parsed2 = parseExportRawBsonArgs([
'--out-dir=./tmp/te',
'--collections=teMarketData',
'--te-symbol=USDCAD',
]);
expect(parsed2).toEqual({
help: false,
outDir: './tmp/te',
collections: ['teMarketData'],
teSymbol: 'USDCAD',
batchSize: DEFAULT_RAW_BSON_BATCH_SIZE,
});
const parsedDefault = parseExportRawBsonArgs(['--out-dir', './tmp/all']);
expect(parsedDefault).toEqual({
help: false,
outDir: './tmp/all',
collections: [...RAW_BSON_EXPORT_COLLECTIONS],
batchSize: DEFAULT_RAW_BSON_BATCH_SIZE,
});
expect(parseExportRawBsonArgs(['--help'])).toEqual({ help: true });
});
test('rejects unknown, duplicate, missing-value, positional, and malformed flags', () => {
expect(() => parseExportRawBsonArgs([])).toThrow(/Missing required argument: --out-dir/);
expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', '--bogus'])).toThrow(/Unknown argument/);
expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', 'positional'])).toThrow(/Unknown argument/);
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--out-dir', './b'])).toThrow(/Duplicate flag/);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--limit', '10', '--limit=20'])
).toThrow(/Duplicate flag/);
expect(() => parseExportRawBsonArgs(['--out-dir', '--collections', 'eodPrices'])).toThrow(
/Missing value for --out-dir/
);
expect(() => parseExportRawBsonArgs(['--out-dir='])).toThrow(/Missing value for --out-dir/);
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '0'])).toThrow(/Invalid --limit/);
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '-5'])).toThrow(/Invalid --limit/);
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '1.5'])).toThrow(/Invalid --limit/);
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '0'])).toThrow(
/Invalid --batch-size/
);
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '999999'])).toThrow(
/Invalid --batch-size/
);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,'])
).toThrow(/Malformed --collections/);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,eodPrices'])
).toThrow(/Duplicate collection/);
expect(() => parseExportRawBsonArgs(['--help', '--help'])).toThrow(/Duplicate flag: --help/);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--eod-symbol=--help'])
).toThrow(/Invalid value for --eod-symbol/);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--eod-symbol', '--help'])
).toThrow(/Missing value for --eod-symbol/);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--te-symbol=--limit'])
).toThrow(/Invalid value for --te-symbol/);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--te-symbol', '--limit'])
).toThrow(/Missing value for --te-symbol/);
});
test('rejects disallowed collections and mismatched --eod-symbol / --te-symbol filters', () => {
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M'])
).toThrow(RawBsonExportError);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'symbols'])
).toThrow(RawBsonExportError);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--eod-symbol', 'CAD.FOREX'])
).toThrow(/--eod-symbol is only permitted/);
expect(() =>
parseExportRawBsonArgs([
'--out-dir',
'./a',
'--collections',
'eodPrices,qmSplits',
'--eod-symbol',
'CAD.FOREX',
])
).toThrow(/--eod-symbol is only permitted/);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--eod-symbol', 'CAD.FOREX'])
).toThrow(/--eod-symbol is only permitted/);
expect(() =>
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--te-symbol', 'USDCAD'])
).toThrow(/--te-symbol is only permitted/);
});
});
describe('assertExportRawBsonSafety', () => {
test('allows read-only dev MongoDB even if Postgres config points to QA, and rejects disabled/writable/admin MongoDB', () => {
expect(() => assertExportRawBsonSafety(createBaseConfig(), {})).not.toThrow();
expect(() => assertExportRawBsonSafety(createBaseConfig({ enabled: false }), {})).toThrow(
/MongoDB is disabled/
);
expect(() => assertExportRawBsonSafety(createBaseConfig({ readOnly: false }), {})).toThrow(
/read-only MongoDB configuration/
);
expect(() =>
assertExportRawBsonSafety(
createBaseConfig({
readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin',
readOnly: true,
}),
{}
)
).toThrow(/Safety guard/);
});
});
describe('runExportRawBson & runCli', () => {
test('--help prints usage and performs zero config, Mongo, or fs I/O', async () => {
const stdout: string[] = [];
const initConfigMock = mock(() => {
throw new Error('initializeConfig must not be called on --help');
});
const createClientMock = mock(() => {
throw new Error('createMongoClient must not be called on --help');
});
await runCli(['--help'], {
initializeConfig: initConfigMock as never,
createMongoClient: createClientMock,
writeStdout: text => stdout.push(text),
});
expect(stdout.join('')).toBe(`${EXPORT_RAW_BSON_USAGE}\n`);
expect(initConfigMock).not.toHaveBeenCalled();
expect(createClientMock).not.toHaveBeenCalled();
});
test('runCli initializes config with mongoReadOnly: true, issues strictly raw find(), calls zero write methods, and closes client', async () => {
const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-cli-'));
try {
const sampleBytes = Uint8Array.from(
BSON.serialize({ eodSearchCode: 'CAD.FOREX', date: '2025-01-02', close: 1.44 })
);
const findCalls: Array<{ collection: string; filter: unknown; options: unknown }> = [];
const forbiddenWrite = mock(() => {
throw new Error('Write/DDL method must never be called');
});
const closeMongoMock = mock(async () => {});
const closeCursorMock = mock(async () => {});
const fakeClient: ReadOnlyMongoRawBsonClient & Record<string, unknown> = {
isReadOnly: () => true,
insertOne: forbiddenWrite,
updateOne: forbiddenWrite,
deleteMany: forbiddenWrite,
createIndex: forbiddenWrite,
dropCollection: forbiddenWrite,
getCollection: (name: string) => ({
find: (filter, options) => {
findCalls.push({ collection: name, filter, options });
return {
close: closeCursorMock,
async *[Symbol.asyncIterator]() {
yield sampleBytes;
},
};
},
}),
};
const initCalls: Array<{ service: string; opts: unknown }> = [];
const stdout: string[] = [];
await runCli(
[
'--out-dir',
outDir,
'--collections',
'eodPrices',
'--eod-symbol',
'CAD.FOREX',
'--batch-size',
'256',
],
{
initializeConfig: ((service: string, opts?: unknown) => {
initCalls.push({ service, opts });
return createBaseConfig();
}) as never,
createMongoClient: async () => ({
client: fakeClient,
close: closeMongoMock,
}),
writeStdout: text => stdout.push(text),
}
);
expect(initCalls).toEqual([{ service: 'dataPipeline', opts: { mongoReadOnly: true } }]);
expect(findCalls).toEqual([
{
collection: 'eodPrices',
filter: { eodSearchCode: 'CAD.FOREX' },
options: { raw: true, batchSize: 256 },
},
]);
expect(forbiddenWrite).not.toHaveBeenCalled();
expect(closeCursorMock).toHaveBeenCalledTimes(1);
expect(closeMongoMock).toHaveBeenCalledTimes(1);
const written = Uint8Array.from(await readFile(join(outDir, 'eodPrices.bson')));
expect(written).toEqual(sampleBytes);
expect(stdout.join('')).toContain('eodPrices: docs=1');
expect(stdout.join('')).toContain('sha256=');
} finally {
await rm(outDir, { recursive: true, force: true });
}
});
test('runExportRawBson closes Mongo client on mid-stream export failure and preserves primary error', async () => {
const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-fail-'));
try {
const closeMongoMock = mock(async () => {});
const fakeClient: ReadOnlyMongoRawBsonClient = {
isReadOnly: () => true,
getCollection: () => ({
find: () => ({
async *[Symbol.asyncIterator]() {
yield Uint8Array.from(BSON.serialize({ ok: 1 }));
throw new Error('Mid-stream Mongo failure');
},
}),
}),
};
await expect(
runExportRawBson(
{
createMongoClient: () => ({ client: fakeClient, close: closeMongoMock }),
writeStdout: () => {},
},
{
outDir,
collections: ['qmSplits'],
}
)
).rejects.toThrow('Mid-stream Mongo failure');
expect(closeMongoMock).toHaveBeenCalledTimes(1);
} finally {
await rm(outDir, { recursive: true, force: true });
}
});
test('runExportRawBson rejects disallowed collections before calling assertSafety or createMongoClient', async () => {
const assertSafetyMock = mock(() => {});
const createClientMock = mock(() => {
throw new Error('createMongoClient must not be called');
});
await expect(
runExportRawBson(
{
assertSafety: assertSafetyMock,
createMongoClient: createClientMock,
},
{
outDir: '/tmp/unused',
collections: ['eodIntraday1M' as never],
}
)
).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION' });
expect(assertSafetyMock).not.toHaveBeenCalled();
expect(createClientMock).not.toHaveBeenCalled();
});
test('runCli rejects flag-shaped --eod-symbol and --te-symbol values before config or MongoDB access and preserves existing output', async () => {
const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-flag-val-'));
try {
const existingEodPath = join(outDir, 'eodPrices.bson');
const sentinel = Uint8Array.from(BSON.serialize({ eodSearchCode: 'CAD.FOREX', close: 1.44 }));
await writeFile(existingEodPath, sentinel);
const initConfigMock = mock(() => {
throw new Error('initializeConfig must not be called on malformed filter');
});
const createClientMock = mock(() => {
throw new Error('createMongoClient must not be called on malformed filter');
});
const invalidInvocations: string[][] = [
['--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol=--help'],
['--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol', '--help'],
['--out-dir', outDir, '--collections', 'teMarketData', '--te-symbol=--help'],
['--out-dir', outDir, '--collections', 'teMarketData', '--te-symbol', '--help'],
];
for (const argv of invalidInvocations) {
await expect(
runCli(argv, {
initializeConfig: initConfigMock as never,
createMongoClient: createClientMock,
})
).rejects.toThrow(/(?:Invalid|Missing) value for --(?:eod|te)-symbol/);
}
expect(initConfigMock).not.toHaveBeenCalled();
expect(createClientMock).not.toHaveBeenCalled();
expect(Uint8Array.from(await readFile(existingEodPath))).toEqual(sentinel);
} finally {
await rm(outDir, { recursive: true, force: true });
}
});
});

View file

@ -1,364 +0,0 @@
import { describe, expect, test } from 'bun:test';
import { BSON } from 'mongodb';
import {
createReadOnlyMongoSourceSymbolReader,
MAX_EXAMPLES_CAP,
parseProbeSourceFieldShapesArgs,
readFieldShapes,
renderFieldShapesMarkdown,
runSourceFieldShapesProbe,
summarizeFieldShapes,
type ReadOnlyMongoCollectionClient,
type ReadOnlySourceSymbolCursor,
type ReadOnlySourceSymbolReader,
type SourceSymbolFindOptions,
} from '../src/security-master';
// QA coverage for T-108 beyond the programmer's suite: real BSON wire decoding,
// option pass-through via the production read-only adapter, fail-fast safety,
// and CLI/runner failure paths. No MongoDB connection is opened anywhere here.
const OBJECT_ID_HEX = '507f1f77bcf86cd799439011';
function serializeRealBsonDoc(): Uint8Array {
return BSON.serialize({
_id: new BSON.ObjectId(OBJECT_ID_HEX),
i32: new BSON.Int32(7),
dbl: new BSON.Double(1.0),
lng: BSON.Long.fromString('9007199254740993'),
dec: BSON.Decimal128.fromString('12.34'),
flag: true,
text: '2025-01-02',
when: new Date('2025-01-02T00:00:00.000Z'),
nothing: null,
list: [1, 2],
nested: { px: new BSON.Double(2.5), qty: new BSON.Int32(3) },
bin: new BSON.Binary(new Uint8Array([1, 2, 3])),
ts: new BSON.Timestamp({ t: 1, i: 1 }),
min: new BSON.MinKey(),
});
}
function nonZeroTypes(counts: Record<string, number>): Record<string, number> {
return Object.fromEntries(Object.entries(counts).filter(([, count]) => count > 0));
}
function asyncCursor<T>(
docs: readonly T[],
onClose?: () => void
): { [Symbol.asyncIterator](): AsyncIterator<T>; close(): Promise<void> } {
return {
async *[Symbol.asyncIterator]() {
for (const doc of docs) {
yield doc;
}
},
async close() {
onClose?.();
},
};
}
describe('summarizeFieldShapes with real BSON wire documents', () => {
test('promoteValues:false decoding keeps int/double/long/objectId distinct and maps other BSON types to other', () => {
const doc = BSON.deserialize(serializeRealBsonDoc(), {
promoteValues: false,
promoteLongs: false,
});
const summary = summarizeFieldShapes([doc]);
const types = Object.fromEntries(summary.fields.map(f => [f.field, nonZeroTypes(f.typeCounts)]));
expect(types).toEqual({
_id: { objectId: 1 },
bin: { other: 1 },
dbl: { double: 1 },
dec: { other: 1 },
flag: { bool: 1 },
i32: { int: 1 },
list: { array: 1 },
lng: { int: 1 },
min: { other: 1 },
nested: { object: 1 },
'nested.px': { double: 1 },
'nested.qty': { int: 1 },
nothing: { null: 1 },
text: { string: 1 },
ts: { other: 1 },
when: { date: 1 },
});
const examples = Object.fromEntries(summary.fields.map(f => [f.field, f.examples]));
expect(examples._id).toEqual([]);
expect(examples.dbl).toEqual(['1']);
expect(examples.lng).toEqual(['9007199254740993']);
expect(examples.dec).toEqual(['12.34']);
expect(examples.when).toEqual(['2025-01-02T00:00:00.000Z']);
expect(examples.bin).toEqual([]);
});
test('default driver promotion collapses Double(1.0) into int, which is why the probe disables promotion', () => {
const promoted = BSON.deserialize(serializeRealBsonDoc());
const summary = summarizeFieldShapes([promoted]);
const dbl = summary.fields.find(f => f.field === 'dbl')!;
expect(nonZeroTypes(dbl.typeCounts)).toEqual({ int: 1 });
});
});
describe('readFieldShapes through the production read-only Mongo adapter', () => {
test('forwards limit/promoteValues/promoteLongs verbatim to collection.find and classifies decoded BSON', async () => {
const findCalls: Array<{ name: string; filter: unknown; options: unknown }> = [];
const closed: string[] = [];
const wireDoc = BSON.deserialize(serializeRealBsonDoc(), {
promoteValues: false,
promoteLongs: false,
});
const client: ReadOnlyMongoCollectionClient = {
isReadOnly: () => true,
getCollection(name: string) {
return {
find(filter?: Record<string, unknown>, options?: SourceSymbolFindOptions) {
findCalls.push({ name, filter, options });
return asyncCursor(name === 'qmDividends' ? [wireDoc] : [], () => closed.push(name));
},
};
},
};
const reader = createReadOnlyMongoSourceSymbolReader(client);
const result = await readFieldShapes(reader, {
collections: ['qmDividends', 'qmSplits'],
limit: 25,
});
expect(findCalls).toEqual([
{
name: 'qmDividends',
filter: {},
options: { limit: 25, promoteValues: false, promoteLongs: false },
},
{
name: 'qmSplits',
filter: {},
options: { limit: 25, promoteValues: false, promoteLongs: false },
},
]);
expect(closed).toEqual(['qmDividends', 'qmSplits']);
expect(result.totalDocsSampled).toBe(1);
const dbl = result.collections[0]!.fields.find(f => f.field === 'dbl')!;
expect(dbl.typeCounts.double).toBe(1);
});
test('re-checks read-only before every collection and stops if the reader stops being read-only', async () => {
let readOnly = true;
const findCalls: string[] = [];
const reader: ReadOnlySourceSymbolReader = {
isReadOnly: () => readOnly,
find<T extends Record<string, unknown>>(name: string): ReadOnlySourceSymbolCursor<T> {
findCalls.push(name);
readOnly = false; // simulate a reader that flips after its first query
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
},
};
await expect(
readFieldShapes(reader, { collections: ['ceoShorts', 'qmSplits'] })
).rejects.toThrow(/read-only/i);
expect(findCalls).toEqual(['ceoShorts']);
});
test('fails fast: an error on one collection prevents queries on later collections', async () => {
const findCalls: string[] = [];
const reader: ReadOnlySourceSymbolReader = {
isReadOnly: () => true,
find<T extends Record<string, unknown>>(name: string): ReadOnlySourceSymbolCursor<T> {
findCalls.push(name);
if (name === 'eodPrices') {
throw new Error('not authorized on stock');
}
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
},
};
let caught: unknown;
try {
await readFieldShapes(reader, { collections: ['qmSplits', 'eodPrices', 'ceoShorts'] });
} catch (error) {
caught = error;
}
// Collections are ASCII-sorted: ceoShorts, eodPrices, qmSplits.
expect(findCalls).toEqual(['ceoShorts', 'eodPrices']);
expect((caught as Error).message).toContain('eodPrices');
expect((caught as Error).message).toContain('not authorized on stock');
expect(((caught as Error).cause as Error).message).toBe('not authorized on stock');
});
test('rejects non-integer limit and invalid batchSize before any query', async () => {
let findCalls = 0;
const reader: ReadOnlySourceSymbolReader = {
isReadOnly: () => true,
find<T extends Record<string, unknown>>(): ReadOnlySourceSymbolCursor<T> {
findCalls += 1;
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
},
};
await expect(readFieldShapes(reader, { limit: 1.5 })).rejects.toThrow(RangeError);
await expect(readFieldShapes(reader, { limit: Number.NaN })).rejects.toThrow(RangeError);
await expect(readFieldShapes(reader, { batchSize: 0 })).rejects.toThrow(RangeError);
await expect(readFieldShapes(reader, { collections: [] })).rejects.toThrow(RangeError);
expect(findCalls).toBe(0);
});
});
describe('summarizeFieldShapes edge cases', () => {
test('non-object documents count toward docCount and keep presence invariants', () => {
const docs = [{ a: 1 }, null, 'oops', { a: 'x' }] as unknown as Record<string, unknown>[];
const summary = summarizeFieldShapes(docs);
expect(summary.docCount).toBe(4);
const a = summary.fields.find(f => f.field === 'a')!;
expect(a.presentCount).toBe(2);
expect(a.missingCount).toBe(2);
});
test('undefined values are treated as missing, not as a present type', () => {
const summary = summarizeFieldShapes([{ a: undefined }, { a: 1 }]);
const a = summary.fields.find(f => f.field === 'a')!;
expect(a.presentCount).toBe(1);
expect(a.missingCount).toBe(1);
});
test('rejects near-miss dates and times as ymd/isoDatetime', () => {
const values = [
'2024-13-01', // month 13
'2024-04-31', // April has 30 days
'2025-01-01T24:00:00Z', // hour 24
'2025-01-01T10:60:00Z', // minute 60
'2025-01-01 10:00:00', // space separator
'20250101', // compact date is numeric, not ymd
];
const summary = summarizeFieldShapes(values.map(s => ({ s })));
const s = summary.fields.find(f => f.field === 's')!;
expect(s.stringStats!.patterns).toEqual({
ymd: 0,
isoDatetime: 0,
numeric: 1,
emptyOrWhitespace: 0,
other: 5,
});
});
test('examples are distinct, strip control characters, and honour maxExamples 0 and the cap', () => {
const docs = [{ s: 'dup' }, { s: 'dup' }, { s: '\u0000\u001bbell\u0007' }];
expect(summarizeFieldShapes(docs).fields[0]!.examples).toEqual(['bell', 'dup']);
expect(summarizeFieldShapes(docs, { maxExamples: 0 }).fields[0]!.examples).toEqual([]);
const many = Array.from({ length: 50 }, (_, i) => ({ s: `v${String(i).padStart(2, '0')}` }));
const capped = summarizeFieldShapes(many, { maxExamples: MAX_EXAMPLES_CAP }).fields[0]!;
expect(capped.examples.length).toBe(MAX_EXAMPLES_CAP);
expect(capped.examples[0]).toBe('v00');
});
});
describe('renderFieldShapesMarkdown privacy and header', () => {
test('never renders _id values and states the bounded sample in the header', async () => {
const reader: ReadOnlySourceSymbolReader = {
isReadOnly: () => true,
find<T extends Record<string, unknown>>(): ReadOnlySourceSymbolCursor<T> {
return asyncCursor<T>([
{ _id: new BSON.ObjectId(OBJECT_ID_HEX), symbol: 'ABC' },
{ _id: { ticker: 'SECRET-COMPOSITE' }, symbol: 'DEF' },
] as unknown as T[]) as unknown as ReadOnlySourceSymbolCursor<T>;
},
};
const result = await readFieldShapes(reader, { collections: ['ceoShorts'], limit: 7 });
const markdown = renderFieldShapesMarkdown(result);
expect(markdown).not.toContain(OBJECT_ID_HEX);
expect(markdown).not.toContain('SECRET-COMPOSITE');
expect(markdown).toContain('bounded sample, not a full scan');
expect(markdown).toContain('**Sample limit per collection:** 7');
expect(markdown).toContain('**Total documents sampled:** 2');
expect(markdown).toContain('| `_id.ticker` | 50.0% (1/2) |');
expect(markdown).not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/); // no wall-clock stamp
});
});
describe('probe CLI parsing and runner failure paths', () => {
test('rejects a flag in place of a value and empty inline values', () => {
expect(() => parseProbeSourceFieldShapesArgs(['--out', '--limit', '5'])).toThrow(/--out/);
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit'])).toThrow(/--limit/);
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections='])).toThrow(
/--collections/
);
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections', ' , '])).toThrow(
/--collections/
);
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1e3'])).toThrow(/--limit/);
});
test('merges repeated --collections, accepts boundary limits, and lets --help win', () => {
expect(
parseProbeSourceFieldShapesArgs([
'--out=x.md',
'--collections=qmSplits',
'--collections',
'ceoShorts,qmSplits',
'--limit=10000',
])
).toEqual({ help: false, outPath: 'x.md', limit: 10_000, collections: ['ceoShorts', 'qmSplits'] });
expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1'])).toMatchObject({ limit: 1 });
expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--help'])).toEqual({ help: true });
});
test('closes Mongo and surfaces the write error when the report cannot be written', async () => {
let closeCalls = 0;
const stdout: string[] = [];
const client: ReadOnlyMongoCollectionClient = {
isReadOnly: () => true,
getCollection() {
return { find: () => asyncCursor([{ a: 1 }]) };
},
};
await expect(
runSourceFieldShapesProbe(
{
mongoCollectionClient: client,
closeMongo: () => {
closeCalls += 1;
},
writeFile: () => {
throw new Error('EACCES: permission denied');
},
writeStdout: text => stdout.push(text),
},
{ outPath: './tmp/out.md', collections: ['qmSplits'] }
)
).rejects.toThrow('EACCES');
expect(closeCalls).toBe(1);
expect(stdout).toEqual([]);
});
test('blank outPath is rejected before any collection is opened', async () => {
let getCollectionCalls = 0;
const client: ReadOnlyMongoCollectionClient = {
isReadOnly: () => true,
getCollection() {
getCollectionCalls += 1;
return { find: () => asyncCursor([]) };
},
};
await expect(
runSourceFieldShapesProbe(
{ mongoCollectionClient: client, writeFile: () => {}, writeStdout: () => {} },
{ outPath: ' ' }
)
).rejects.toThrow(/outPath/);
expect(getCollectionCalls).toBe(0);
});
});

View file

@ -1,812 +0,0 @@
import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { ParserOptions } from 'prettier';
import * as markdownPlugin from 'prettier/plugins/markdown';
import {
DEFAULT_FIELD_SHAPE_LIMIT,
DEFAULT_MAX_EXAMPLE_LENGTH,
DEFAULT_MAX_EXAMPLES,
FIELD_SHAPE_PROBE_COLLECTIONS,
FIELD_VALUE_TYPES,
MAX_EXAMPLE_LENGTH_CAP,
MAX_EXAMPLES_CAP,
MAX_FIELD_SHAPE_LIMIT,
parseProbeSourceFieldShapesArgs,
readFieldShapes,
renderFieldShapesMarkdown,
runSourceFieldShapesProbe,
STRING_PATTERN_CLASSES,
summarizeFieldShapes,
UnknownProbeCollectionError,
type FieldShapeSummary,
type ReadOnlyMongoCollectionClient,
type ReadOnlySourceSymbolCursor,
type ReadOnlySourceSymbolReader,
type SourceSymbolFindOptions,
} from '../src/security-master';
interface RecordedFindCall {
collectionName: string;
filter: Record<string, unknown> | undefined;
options: SourceSymbolFindOptions | undefined;
}
interface FakeBsonWrapper {
_bsontype: string;
valueOf?: () => unknown;
toString: () => string;
}
function fakeInt32(value: number): FakeBsonWrapper {
return {
_bsontype: 'Int32',
valueOf: () => value,
toString: () => String(value),
};
}
function fakeDouble(value: number): FakeBsonWrapper {
return {
_bsontype: 'Double',
valueOf: () => value,
toString: () => String(value),
};
}
function fakeLong(value: string): FakeBsonWrapper {
return {
_bsontype: 'Long',
toString: () => value,
};
}
function fakeObjectId(hex: string): FakeBsonWrapper {
return {
_bsontype: 'ObjectId',
toString: () => hex,
};
}
function fakeDecimal128(value: string): FakeBsonWrapper {
return {
_bsontype: 'Decimal128',
toString: () => value,
};
}
function sumTypeCounts(summary: FieldShapeSummary): number {
let total = 0;
for (const typeName of FIELD_VALUE_TYPES) {
total += summary.typeCounts[typeName];
}
return total;
}
function sumPatternCounts(summary: FieldShapeSummary): number {
if (summary.stringStats === null) {
return 0;
}
let total = 0;
for (const pattern of STRING_PATTERN_CLASSES) {
total += summary.stringStats.patterns[pattern];
}
return total;
}
function createFakeReader(
docsByCollection: Record<string, readonly Record<string, unknown>[]>,
opts?: {
readOnly?: boolean;
failFindOnCollection?: string;
failIterOnCollection?: string;
failIterAtIndex?: number;
failCloseOnCollection?: string;
returnBufferedArrayOnCollection?: string;
ignoreLimit?: boolean;
}
): {
reader: ReadOnlySourceSymbolReader;
calls: RecordedFindCall[];
closedCollections: string[];
pullsByCollection: Record<string, number>;
} {
const calls: RecordedFindCall[] = [];
const closedCollections: string[] = [];
const pullsByCollection: Record<string, number> = {};
const readOnly = opts?.readOnly ?? true;
const reader: ReadOnlySourceSymbolReader = {
isReadOnly(): boolean {
return readOnly;
},
find<T extends Record<string, unknown> = Record<string, unknown>>(
collectionName: string,
filter?: Record<string, unknown>,
options?: SourceSymbolFindOptions
): ReadOnlySourceSymbolCursor<T> {
calls.push({ collectionName, filter, options });
if (opts?.failFindOnCollection === collectionName) {
throw new Error('simulated find failure');
}
if (opts?.returnBufferedArrayOnCollection === collectionName) {
return [...(docsByCollection[collectionName] ?? [])] as unknown as ReadOnlySourceSymbolCursor<T>;
}
const sourceDocs = docsByCollection[collectionName] ?? [];
const maxToYield =
opts?.ignoreLimit === true || options?.limit === undefined
? sourceDocs.length
: Math.min(sourceDocs.length, options.limit);
const failAt = opts?.failIterAtIndex ?? 1;
return {
async *[Symbol.asyncIterator](): AsyncIterator<T> {
for (let i = 0; i < maxToYield; i++) {
pullsByCollection[collectionName] = (pullsByCollection[collectionName] ?? 0) + 1;
if (opts?.failIterOnCollection === collectionName && i === failAt) {
throw new Error('simulated cursor iteration failure');
}
yield sourceDocs[i] as T;
}
},
async close(): Promise<void> {
closedCollections.push(collectionName);
if (opts?.failCloseOnCollection === collectionName) {
throw new Error('simulated cursor close failure');
}
},
};
},
};
return { reader, calls, closedCollections, pullsByCollection };
}
describe('source-field-shapes static purity', () => {
test('source-field-shapes.ts has zero runtime DB, FS, or network imports', () => {
const filePath = resolve(import.meta.dir, '../src/security-master/source-field-shapes.ts');
const source = readFileSync(filePath, 'utf8');
const runtimeImportLines = source
.split('\n')
.filter(line => /^\s*import\s+(?!type\b)/.test(line));
for (const line of runtimeImportLines) {
expect(line).not.toMatch(/mongodb|postgres|node:fs|node:http|node:https|node:net|fetch/i);
}
expect(source).not.toMatch(/\bDate\.now\s*\(|\bnew Date\s*\(\s*\)/);
});
});
describe('summarizeFieldShapes', () => {
test('classifies mixed JS and BSON value types on one field and reconciles counts', () => {
const docs: Record<string, unknown>[] = [
{ mixed: 'hello' },
{ mixed: 42 },
{ mixed: 3.14 },
{ mixed: fakeInt32(7) },
{ mixed: fakeLong('9007199254740993') },
{ mixed: fakeDouble(1.0) },
{ mixed: true },
{ mixed: new Date('2025-01-15T12:00:00.000Z') },
{ mixed: null },
{ mixed: fakeObjectId('507f1f77bcf86cd799439011') },
{ mixed: [1, 2, 3] },
{ mixed: { nested: 'a' } },
{ mixed: fakeDecimal128('12.34') },
{ mixed: new Uint8Array([1, 2]) },
{}, // missing
];
const summary = summarizeFieldShapes(docs);
expect(summary.docCount).toBe(docs.length);
const mixed = summary.fields.find(f => f.field === 'mixed');
expect(mixed).toBeDefined();
expect(mixed!.presentCount).toBe(14);
expect(mixed!.missingCount).toBe(1);
expect(mixed!.presentCount + mixed!.missingCount).toBe(summary.docCount);
expect(sumTypeCounts(mixed!)).toBe(mixed!.presentCount);
expect(mixed!.typeCounts).toEqual({
string: 1,
int: 3, // 42, Int32(7), Long(...)
double: 2, // 3.14, Double(1.0)
bool: 1,
date: 1,
null: 1,
objectId: 1,
array: 1,
object: 1,
other: 2, // Decimal128, Uint8Array
});
});
test('tracks one level of nested parent.child keys and stops at depth 1', () => {
const docs: Record<string, unknown>[] = [
{
meta: {
exchange: 'TSX',
deep: { level2: 'ignored' },
recordedAt: new Date('2025-02-01T00:00:00Z'),
},
arr: [{ insideArray: 1 }],
bsonObj: fakeObjectId('507f1f77bcf86cd799439012'),
},
{
meta: {
exchange: 'NYSE',
},
},
];
const summary = summarizeFieldShapes(docs);
const fieldNames = summary.fields.map(f => f.field);
expect(fieldNames).toEqual([
'arr',
'bsonObj',
'meta',
'meta.deep',
'meta.exchange',
'meta.recordedAt',
]);
expect(fieldNames).not.toContain('meta.deep.level2');
expect(fieldNames).not.toContain('bsonObj._bsontype');
const metaExchange = summary.fields.find(f => f.field === 'meta.exchange')!;
expect(metaExchange.presentCount).toBe(2);
expect(metaExchange.missingCount).toBe(0);
expect(metaExchange.typeCounts.string).toBe(2);
const metaDeep = summary.fields.find(f => f.field === 'meta.deep')!;
expect(metaDeep.presentCount).toBe(1);
expect(metaDeep.missingCount).toBe(1);
expect(metaDeep.typeCounts.object).toBe(1);
});
test('keeps literal dotted top-level keys distinct from nested parent.child keys', () => {
const docs: Record<string, unknown>[] = [
{
'meta.exchange': 'LITERAL_EXCHANGE',
meta: {
exchange: 42,
},
},
];
const summary = summarizeFieldShapes(docs);
expect(summary.docCount).toBe(1);
const literalField = summary.fields.find(f => f.field === 'meta\\.exchange');
const nestedField = summary.fields.find(f => f.field === 'meta.exchange');
expect(literalField).toBeDefined();
expect(nestedField).toBeDefined();
expect(literalField!.presentCount).toBe(1);
expect(literalField!.missingCount).toBe(0);
expect(literalField!.typeCounts.string).toBe(1);
expect(literalField!.typeCounts.int).toBe(0);
expect(literalField!.examples).toEqual(['LITERAL_EXCHANGE']);
expect(nestedField!.presentCount).toBe(1);
expect(nestedField!.missingCount).toBe(0);
expect(nestedField!.typeCounts.int).toBe(1);
expect(nestedField!.typeCounts.string).toBe(0);
expect(nestedField!.examples).toEqual(['42']);
});
test('classifies all five string pattern classes and tracks min/max string length', () => {
const docs: Record<string, unknown>[] = [
{ s: '2024-02-29' }, // valid leap-year ymd (len 10)
{ s: '2023-02-29' }, // invalid calendar date -> other (len 10)
{ s: '2025-05-01T14:30:00Z' }, // isoDatetime (len 20)
{ s: '2025-05-01T14:30:00.123-04:00' }, // isoDatetime (len 29)
{ s: '-123.45' }, // numeric (len 7)
{ s: '1.5e-4' }, // numeric (len 6)
{ s: '' }, // emptyOrWhitespace (len 0)
{ s: ' \t ' }, // emptyOrWhitespace (len 5)
{ s: 'AAPL.US' }, // other (len 7)
];
const summary = summarizeFieldShapes(docs);
const field = summary.fields.find(f => f.field === 's')!;
expect(field.typeCounts.string).toBe(9);
expect(field.stringStats).toEqual({
minLength: 0,
maxLength: 29,
patterns: {
ymd: 1,
isoDatetime: 2,
numeric: 2,
emptyOrWhitespace: 2,
other: 2,
},
});
expect(sumPatternCounts(field)).toBe(field.typeCounts.string);
});
test('truncates and caps examples, suppresses _id and _id.* examples, and validates bounds', () => {
const docs: Record<string, unknown>[] = [
{
_id: fakeObjectId('507f1f77bcf86cd799439011'),
symbol: 'ZZZZ',
note: 'line1\nline2\twith a very long description that must be truncated',
},
{
_id: { key: 'secret-composite-id' },
symbol: 'AAAA',
note: 'short',
},
{
_id: 'string-id-should-never-appear',
symbol: 'MMMM',
},
{
symbol: 'BBBB',
},
];
const summary = summarizeFieldShapes(docs, { maxExamples: 2, maxExampleLength: 16 });
const idField = summary.fields.find(f => f.field === '_id')!;
const idChildField = summary.fields.find(f => f.field === '_id.key')!;
const symbolField = summary.fields.find(f => f.field === 'symbol')!;
const noteField = summary.fields.find(f => f.field === 'note')!;
expect(idField.examples).toEqual([]);
expect(idChildField.examples).toEqual([]);
expect(symbolField.examples).toEqual(['AAAA', 'BBBB']);
expect(noteField.examples.length).toBe(2);
expect(noteField.examples[0]).toBe('line1 line2 w...');
expect(noteField.examples[0]!.length).toBeLessThanOrEqual(16);
expect(noteField.examples[1]).toBe('short');
expect(() => summarizeFieldShapes(docs, { maxExamples: -1 })).toThrow(RangeError);
expect(() => summarizeFieldShapes(docs, { maxExamples: MAX_EXAMPLES_CAP + 1 })).toThrow(
RangeError
);
expect(() => summarizeFieldShapes(docs, { maxExampleLength: 0 })).toThrow(RangeError);
expect(() =>
summarizeFieldShapes(docs, { maxExampleLength: MAX_EXAMPLE_LENGTH_CAP + 1 })
).toThrow(RangeError);
});
test('produces deep-equal output for shuffled input order and handles empty iterable', () => {
expect(summarizeFieldShapes([])).toEqual({ docCount: 0, fields: [] });
const original: Record<string, unknown>[] = [
{ _id: fakeObjectId('000000000000000000000001'), z: 'delta', a: 10, meta: { k: 'v3' } },
{ _id: fakeObjectId('000000000000000000000002'), z: 'alpha', a: 2.5, meta: { k: 'v1' } },
{ _id: fakeObjectId('000000000000000000000003'), z: 'charlie', b: true, meta: { k: 'v4' } },
{ _id: fakeObjectId('000000000000000000000004'), z: 'bravo', a: null, meta: { k: 'v2' } },
];
const shuffled = [original[2]!, original[0]!, original[3]!, original[1]!];
const a = summarizeFieldShapes(original, { maxExamples: 2 });
const b = summarizeFieldShapes(shuffled, { maxExamples: 2 });
expect(b).toEqual(a);
expect(a.fields.map(f => f.field)).toEqual(['_id', 'a', 'b', 'meta', 'meta.k', 'z']);
});
});
describe('readFieldShapes', () => {
test('calls only find() with limit and promoteValues/promoteLongs false, closes cursors, and enforces client limit', async () => {
const docsByCollection: Record<string, Record<string, unknown>[]> = {
qmDividends: [
{ _id: fakeObjectId('507f1f77bcf86cd799439011'), amount: fakeDouble(0.25), currency: 'USD' },
{ _id: fakeObjectId('507f1f77bcf86cd799439012'), amount: fakeDouble(0.5), currency: 'CAD' },
{ _id: fakeObjectId('507f1f77bcf86cd799439013'), amount: fakeDouble(1.0), currency: 'USD' },
],
ceoShorts: [
{ _id: fakeObjectId('507f1f77bcf86cd799439014'), symbol: 'ABC', shares: fakeInt32(1000) },
],
};
const { reader, calls, closedCollections, pullsByCollection } = createFakeReader(
docsByCollection,
{
ignoreLimit: true,
failIterOnCollection: 'qmDividends',
failIterAtIndex: 2,
}
);
const result = await readFieldShapes(reader, {
collections: ['qmDividends', 'ceoShorts', 'qmDividends'],
limit: 2,
batchSize: 500,
});
expect(calls.length).toBe(2);
expect(calls.map(c => c.collectionName)).toEqual(['ceoShorts', 'qmDividends']);
for (const call of calls) {
expect(call.filter).toEqual({});
expect(call.options).toEqual({
limit: 2,
promoteValues: false,
promoteLongs: false,
batchSize: 500,
});
}
expect(closedCollections).toEqual(['ceoShorts', 'qmDividends']);
// Breaks immediately after recording the limit-th doc without pulling a 3rd item
expect(pullsByCollection).toEqual({ ceoShorts: 1, qmDividends: 2 });
// Defensively capped at limit=2 even though fake reader ignored limit
expect(result.limit).toBe(2);
expect(result.totalDocsSampled).toBe(3);
const qmDiv = result.collections.find(c => c.collection === 'qmDividends')!;
expect(qmDiv.docCount).toBe(2);
const amountField = qmDiv.fields.find(f => f.field === 'amount')!;
expect(amountField.typeCounts.double).toBe(2);
});
test('defaults to all allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => {
const { reader, calls } = createFakeReader({});
const result = await readFieldShapes(reader);
expect(result.limit).toBe(DEFAULT_FIELD_SHAPE_LIMIT);
expect(result.maxExamples).toBe(DEFAULT_MAX_EXAMPLES);
expect(result.maxExampleLength).toBe(DEFAULT_MAX_EXAMPLE_LENGTH);
expect(calls.length).toBe(FIELD_SHAPE_PROBE_COLLECTIONS.length);
for (const call of calls) {
expect(call.options).toEqual({
limit: DEFAULT_FIELD_SHAPE_LIMIT,
promoteValues: false,
promoteLongs: false,
});
}
});
test('rejects invalid limit, unknown collection, and non-read-only reader before any query', async () => {
const nonRo = createFakeReader({}, { readOnly: false });
await expect(readFieldShapes(nonRo.reader)).rejects.toThrow(/read-only/i);
expect(nonRo.calls.length).toBe(0);
const badLimitHigh = createFakeReader({});
await expect(
readFieldShapes(badLimitHigh.reader, { limit: MAX_FIELD_SHAPE_LIMIT + 1 })
).rejects.toThrow(RangeError);
expect(badLimitHigh.calls.length).toBe(0);
const badLimitZero = createFakeReader({});
await expect(readFieldShapes(badLimitZero.reader, { limit: 0 })).rejects.toThrow(RangeError);
expect(badLimitZero.calls.length).toBe(0);
const unknownCol = createFakeReader({});
let caught: unknown;
try {
await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', 'notACollection'] });
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(UnknownProbeCollectionError);
expect((caught as UnknownProbeCollectionError).collectionName).toBe('notACollection');
expect(unknownCol.calls.length).toBe(0);
});
test('rejects buffered array cursor with TypeError and surfaces per-collection errors with cause', async () => {
const buffered = createFakeReader(
{ eodPrices: [{ date: '2025-01-02' }] },
{ returnBufferedArrayOnCollection: 'eodPrices' }
);
await expect(
readFieldShapes(buffered.reader, { collections: ['eodPrices'] })
).rejects.toThrow(TypeError);
const findErr = createFakeReader({}, { failFindOnCollection: 'qmFilings' });
let caughtFind: unknown;
try {
await readFieldShapes(findErr.reader, { collections: ['eodPrices', 'qmFilings'] });
} catch (err) {
caughtFind = err;
}
expect(caughtFind).toBeInstanceOf(Error);
expect((caughtFind as Error).message).toContain('qmFilings');
expect((caughtFind as Error).cause).toBeInstanceOf(Error);
const iterErr = createFakeReader(
{ qmEarnings: [{ a: 1 }, { a: 2 }] },
{ failIterOnCollection: 'qmEarnings' }
);
let caughtIter: unknown;
try {
await readFieldShapes(iterErr.reader, { collections: ['qmEarnings'] });
} catch (err) {
caughtIter = err;
}
expect(caughtIter).toBeInstanceOf(Error);
expect((caughtIter as Error).message).toContain('qmEarnings');
expect((caughtIter as Error).cause).toBeInstanceOf(Error);
expect(iterErr.closedCollections).toEqual(['qmEarnings']);
const closeErr = createFakeReader(
{ teMarketData: [{ country: 'US' }] },
{ failCloseOnCollection: 'teMarketData' }
);
let caughtClose: unknown;
try {
await readFieldShapes(closeErr.reader, { collections: ['teMarketData'] });
} catch (err) {
caughtClose = err;
}
expect(caughtClose).toBeInstanceOf(Error);
expect((caughtClose as Error).message).toContain('teMarketData');
expect((caughtClose as Error).cause).toBeInstanceOf(Error);
});
});
interface MdastNode {
type: string;
value?: string;
children?: MdastNode[];
}
function decodeHtmlEntities(text: string): string {
return text.replace(/&(amp|lt|gt|#(\d+));/g, (_, entity: string, code?: string) => {
if (code !== undefined) {
return String.fromCharCode(Number(code));
}
switch (entity) {
case 'amp':
return '&';
case 'lt':
return '<';
case 'gt':
return '>';
default:
return `&${entity};`;
}
});
}
function parseGfmTables(markdown: string): MdastNode[][] {
const ast = markdownPlugin.parsers.markdown.parse(
markdown,
{} as ParserOptions
) as unknown as MdastNode;
const rows: MdastNode[][] = [];
for (const node of ast.children ?? []) {
if (node.type !== 'table') {
continue;
}
const tableRows = node.children ?? [];
for (let rowIndex = 1; rowIndex < tableRows.length; rowIndex++) {
rows.push(tableRows[rowIndex]?.children ?? []);
}
}
return rows;
}
function extractGfmCodeCellValues(cell: MdastNode): string[] {
const nodes = cell.children ?? [];
if (nodes.length === 1 && nodes[0]?.type === 'text' && nodes[0].value === '—') {
return [];
}
const values: string[] = [];
let i = 0;
while (i < nodes.length) {
const node = nodes[i]!;
if (node.type === 'inlineCode') {
values.push(node.value ?? '');
i += 1;
} else if (node.type === 'html' && node.value === '<code>') {
let inner = '';
i += 1;
let closed = false;
while (i < nodes.length) {
const innerNode = nodes[i]!;
if (innerNode.type === 'html' && innerNode.value === '</code>') {
closed = true;
i += 1;
break;
}
if (innerNode.type !== 'text') {
throw new Error(
`Unexpected Markdown node "${innerNode.type}" inside <code> element: ${JSON.stringify(innerNode)}`
);
}
inner += decodeHtmlEntities(innerNode.value ?? '');
i += 1;
}
if (!closed) {
throw new Error('Unclosed <code> HTML element in GFM table cell');
}
values.push(inner);
} else if (node.type === 'text' && node.value === ', ') {
i += 1;
} else {
throw new Error(`Unexpected node in GFM code cell: ${JSON.stringify(node)}`);
}
}
return values;
}
describe('renderFieldShapesMarkdown', () => {
test('renders byte-identical Markdown with bounded-sample header, valid GFM code spans, and empty collection notice', async () => {
const docsA = [
{
_id: fakeObjectId('000000000000000000000001'),
'pipe|col': 'val|with`ticks\\slash',
'slash\\|field': 'slash\\|pipe*em*_u_<tag>&',
'tick`field\nname': '`leading`',
edge: 'double``ticks',
dt: '2025-01-02',
},
{
_id: fakeObjectId('000000000000000000000002'),
'pipe|col': 'slash\\|pipe',
'slash\\|field': 'slash\\\\|pipe',
'tick`field\nname': ' spaced ',
edge: '',
dt: '2025-01-03',
},
];
const docsB = [docsA[1]!, docsA[0]!];
const run1 = await readFieldShapes(
createFakeReader({ eodPrices: docsA, qmSplits: [] }).reader,
{ collections: ['eodPrices', 'qmSplits'], limit: 500 }
);
const run2 = await readFieldShapes(
createFakeReader({ eodPrices: docsB, qmSplits: [] }).reader,
{ collections: ['qmSplits', 'eodPrices'], limit: 500 }
);
const md1 = renderFieldShapesMarkdown(run1);
const md2 = renderFieldShapesMarkdown(run2);
expect(md1).toBe(md2);
expect(md1).toContain('bounded sample');
expect(md1).toContain('Sample limit per collection:** 500');
expect(md1).toContain('Total documents sampled:** 2');
expect(md1).toContain('_No documents sampled._');
const tableRows = parseGfmTables(md1);
expect(tableRows.length).toBe(6);
const visibleByField = new Map<string, string[]>();
for (const cells of tableRows) {
expect(cells.length).toBe(5);
const parsedField = extractGfmCodeCellValues(cells[0]!);
expect(parsedField.length).toBe(1);
const parsedExamples = extractGfmCodeCellValues(cells[4]!);
visibleByField.set(parsedField[0]!, parsedExamples);
}
expect(visibleByField.get('pipe|col')).toEqual(['slash\\|pipe', 'val|with`ticks\\slash']);
expect(visibleByField.get('slash\\\\|field')).toEqual([
'slash\\\\|pipe',
'slash\\|pipe*em*_u_<tag>&',
]);
expect(visibleByField.get('tick`field name')).toEqual([' spaced ', '`leading`']);
expect(visibleByField.get('edge')).toEqual(['', 'double``ticks']);
expect(visibleByField.get('_id')).toEqual([]);
});
});
describe('CLI arg parsing and headless probe runner', () => {
test('parseProbeSourceFieldShapesArgs validates flags without opening any DB connection', () => {
expect(parseProbeSourceFieldShapesArgs(['--help'])).toEqual({ help: true });
expect(() => parseProbeSourceFieldShapesArgs([])).toThrow(/--out/);
expect(() => parseProbeSourceFieldShapesArgs(['--out', ' '])).toThrow(/--out/);
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=0'])).toThrow(
/--limit/
);
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', '-1'])).toThrow(
/--limit/
);
expect(() =>
parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', String(MAX_FIELD_SHAPE_LIMIT + 1)])
).toThrow(/--limit/);
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=abc'])).toThrow(
/--limit/
);
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=1.5'])).toThrow(
/--limit/
);
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--bogus'])).toThrow(
/Unknown argument/
);
expect(() =>
parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--collections=eodPrices,bogusCol'])
).toThrow(UnknownProbeCollectionError);
const parsed = parseProbeSourceFieldShapesArgs([
'--out',
'./tmp/report.md',
'--limit',
'250',
'--collections',
'qmDividends,ceoShorts,qmDividends',
]);
expect(parsed).toEqual({
help: false,
outPath: './tmp/report.md',
limit: 250,
collections: ['ceoShorts', 'qmDividends'],
});
});
test('runSourceFieldShapesProbe rejects non-read-only client before any query and writes report headlessly', async () => {
let getCollectionCalls = 0;
let closeCalls = 0;
const writableClient: ReadOnlyMongoCollectionClient = {
isReadOnly: () => false,
getCollection() {
getCollectionCalls += 1;
throw new Error('should never be called');
},
};
await expect(
runSourceFieldShapesProbe(
{
mongoCollectionClient: writableClient,
closeMongo: () => {
closeCalls += 1;
},
writeFile: () => {},
writeStdout: () => {},
},
{ outPath: './tmp/should-not-write.md' }
)
).rejects.toThrow(/read-only/i);
expect(getCollectionCalls).toBe(0);
expect(closeCalls).toBe(1);
const writtenFiles: Array<{ filePath: string; content: string }> = [];
const stdoutChunks: string[] = [];
let roCloseCalls = 0;
const roClient: ReadOnlyMongoCollectionClient = {
isReadOnly: () => true,
getCollection(name: string) {
return {
find() {
const docs = name === 'ceoShorts' ? [{ symbol: 'XYZ', shares: 100 }] : [];
return {
async *[Symbol.asyncIterator]() {
for (const doc of docs) {
yield doc;
}
},
async close() {},
};
},
};
},
};
const output = await runSourceFieldShapesProbe(
{
mongoCollectionClient: roClient,
closeMongo: () => {
roCloseCalls += 1;
},
writeFile: (filePath, content) => {
writtenFiles.push({ filePath, content });
},
writeStdout: text => {
stdoutChunks.push(text);
},
},
{
outPath: './tmp/field-shapes.md',
limit: 10,
collections: ['ceoShorts'],
}
);
expect(roCloseCalls).toBe(1);
expect(writtenFiles.length).toBe(1);
expect(writtenFiles[0]!.filePath).toBe('./tmp/field-shapes.md');
expect(writtenFiles[0]!.content).toBe(output.markdown);
expect(stdoutChunks.join('')).toContain('Documents sampled: 1');
});
});

View file

@ -355,17 +355,6 @@
"typescript": "^5.3.0",
},
},
"libs/data/duckdb": {
"name": "@stock-bot/duckdb",
"version": "1.0.0",
"dependencies": {
"@duckdb/node-api": "^1.4.4-r.1",
"@stock-bot/research": "workspace:*",
},
"devDependencies": {
"@types/node": "^20.11.0",
},
},
"libs/data/mongodb": {
"name": "@stock-bot/mongodb",
"version": "1.0.0",
@ -551,22 +540,6 @@
"@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", {}, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="],
"@duckdb/node-api": ["@duckdb/node-api@1.4.4-r.4", "", { "dependencies": { "@duckdb/node-bindings": "1.4.4-r.4" } }, "sha512-yUotG8wPSmmEFxAODt07rXJZgV2fhvzhnZX3wrMspQNEaNVwXArzakgKyfakZkYL9me7SK9eDnXYv/XbdifWEg=="],
"@duckdb/node-bindings": ["@duckdb/node-bindings@1.4.4-r.4", "", { "optionalDependencies": { "@duckdb/node-bindings-darwin-arm64": "1.4.4-r.4", "@duckdb/node-bindings-darwin-x64": "1.4.4-r.4", "@duckdb/node-bindings-linux-arm64": "1.4.4-r.4", "@duckdb/node-bindings-linux-x64": "1.4.4-r.4", "@duckdb/node-bindings-win32-arm64": "1.4.4-r.4", "@duckdb/node-bindings-win32-x64": "1.4.4-r.4" } }, "sha512-JYjCaZmqvqrjFBjT3Q6jnb3OFz26lAUTFXUka/HQRxWRy23ZiURZwPYMLkyFBLHa696hNlC85M/EWXDRFnDIfg=="],
"@duckdb/node-bindings-darwin-arm64": ["@duckdb/node-bindings-darwin-arm64@1.4.4-r.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ozQbuBlV+01WzyXcqXjEV3TbN+qQ8UcelwPmQaqBn86pdXQHuYGuS8K9a5yATsg+JvivqHQSb95OBHdP7FYDkA=="],
"@duckdb/node-bindings-darwin-x64": ["@duckdb/node-bindings-darwin-x64@1.4.4-r.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-quoPmg26/fpLM80UNMXYSYKGnXJUiqKTSlDIgONQiMVYXJqPc2yz9qwcTuZgaQx7JhD2m1D/cc+h/4d8yVD79Q=="],
"@duckdb/node-bindings-linux-arm64": ["@duckdb/node-bindings-linux-arm64@1.4.4-r.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-Ve+kJ9+IqF5VBNWDzlUeg1xxKGHGqT9MJPxjRTSULgCpguL9ok13Klhw7WJQOs5ycB+osQe/40t5hOZk3cK82g=="],
"@duckdb/node-bindings-linux-x64": ["@duckdb/node-bindings-linux-x64@1.4.4-r.4", "", { "os": "linux", "cpu": "x64" }, "sha512-jBTL/WvfwxLToFa/pVHfT6elMtltJGnc3wSuxZD9OfMltit9YUdVFS37vBFQzXMT1Z8OWjtSjMh+zPKxOwHLHA=="],
"@duckdb/node-bindings-win32-arm64": ["@duckdb/node-bindings-win32-arm64@1.4.4-r.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-4tqE7r1c4wCqgm1iBfW/rP6B67nkHK1Pyj6dT8T3aqupKk2eV0QgKPBYtGOqOlE+jdhj4El9WKye7eTJ59yjZQ=="],
"@duckdb/node-bindings-win32-x64": ["@duckdb/node-bindings-win32-x64@1.4.4-r.4", "", { "os": "win32", "cpu": "x64" }, "sha512-lclo7ZibsYuCHd0ru5j9sw9x+wfXWOiNWIOjW3rcX9675xD7j4CB3RlWfZkBgdajLuXtRuo5FFfQZY249a7IlA=="],
"@esbuild/android-arm": ["@esbuild/android-arm@0.18.20", "", { "os": "android", "cpu": "arm" }, "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw=="],
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.18.20", "", { "os": "android", "cpu": "arm64" }, "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ=="],
@ -731,8 +704,6 @@
"@stock-bot/di": ["@stock-bot/di@workspace:libs/core/di"],
"@stock-bot/duckdb": ["@stock-bot/duckdb@workspace:libs/data/duckdb"],
"@stock-bot/engine": ["@stock-bot/engine@workspace:apps/stock/engine"],
"@stock-bot/handler-registry": ["@stock-bot/handler-registry@workspace:libs/core/handler-registry"],

View file

@ -1,99 +0,0 @@
-- Research findings & provider caveats schema (M2.1i)
-- Research track migration: creates append-only findings and provider_caveats tables,
-- lookup/idempotency indexes, and immutability triggers reusing
-- reject_research_evidence_mutation() from 17-research-retention.sql.
CREATE OR REPLACE FUNCTION research_trim_ecmascript(value TEXT)
RETURNS TEXT
LANGUAGE SQL
IMMUTABLE
STRICT
AS $$
-- Explicit ECMAScript WhiteSpace + LineTerminator set so nonblank checks and
-- trimmed length caps match String.prototype.trim() regardless of DB collation.
SELECT btrim(
value,
U&'\0009\000A\000B\000C\000D\0020\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000\FEFF'
);
$$;
CREATE OR REPLACE FUNCTION research_finding_refs_valid(refs TEXT[], max_len INTEGER)
RETURNS BOOLEAN
LANGUAGE SQL
IMMUTABLE
STRICT
AS $$
SELECT COALESCE(array_ndims(refs), 1) = 1
AND NOT EXISTS (
SELECT 1
FROM unnest(refs) AS r
WHERE r IS NULL
OR char_length(r) > max_len
);
$$;
CREATE TABLE IF NOT EXISTS findings (
id TEXT PRIMARY KEY
CHECK (research_trim_ecmascript(id) <> ''),
kind TEXT NOT NULL
CHECK (kind IN ('finding', 'dead_end')),
title TEXT NOT NULL
CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256),
summary TEXT NOT NULL
CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096),
status TEXT NOT NULL DEFAULT 'pending_review'
CHECK (research_trim_ecmascript(status) <> ''),
created_at TIMESTAMPTZ NOT NULL,
trial_refs TEXT[] NOT NULL
CHECK (cardinality(trial_refs) <= 32)
CHECK (COALESCE(array_ndims(trial_refs), 1) = 1)
CHECK (research_finding_refs_valid(trial_refs, 256)),
evidence_refs TEXT[] NOT NULL
CHECK (cardinality(evidence_refs) <= 32)
CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1)
CHECK (research_finding_refs_valid(evidence_refs, 256)),
idempotency_key TEXT
CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128))
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key
ON findings (idempotency_key)
WHERE idempotency_key IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_findings_created_at
ON findings (created_at);
CREATE TABLE IF NOT EXISTS provider_caveats (
id TEXT PRIMARY KEY
CHECK (research_trim_ecmascript(id) <> ''),
provider TEXT NOT NULL
CHECK (research_trim_ecmascript(provider) <> ''),
dataset TEXT NOT NULL
CHECK (research_trim_ecmascript(dataset) <> ''),
caveat TEXT NOT NULL
CHECK (research_trim_ecmascript(caveat) <> ''),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider
ON provider_caveats (lower(provider));
DROP TRIGGER IF EXISTS findings_retained ON findings;
CREATE TRIGGER findings_retained
BEFORE UPDATE OR DELETE ON findings
FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();
DROP TRIGGER IF EXISTS findings_no_truncate ON findings;
CREATE TRIGGER findings_no_truncate
BEFORE TRUNCATE ON findings
FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();
DROP TRIGGER IF EXISTS provider_caveats_retained ON provider_caveats;
CREATE TRIGGER provider_caveats_retained
BEFORE UPDATE OR DELETE ON provider_caveats
FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();
DROP TRIGGER IF EXISTS provider_caveats_no_truncate ON provider_caveats;
CREATE TRIGGER provider_caveats_no_truncate
BEFORE TRUNCATE ON provider_caveats
FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();

View file

@ -22,7 +22,7 @@ Authoritative specification for `data-pipeline`, PostgreSQL reference schemas, D
| `eodFinancialsOLD` (`2.98M`), `eodFundamentalsOLD` (`106.6k`) | `eodFinancialsOLD` sets `filingDate == reportDate` on **`99.26%`** of rows. `eodFundamentalsOLD` has `filing_date: null`, unversioned current valuation ratios, and mislabels USD figures as `"CAD"` on NEO CDRs (`AAPL` CDR `$335B` assets). | **Quarantine `eodFundamentalsOLD` `Highlights`/`Valuation` from all backtests.** Use `eodFinancialsOLD` only for pre-QM historical backfill with mandatory statutory lag (ignoring its `filingDate`). |
| `qmFilings` (`30.52M`) | Has exact second-level `timefiled` (`"2025-01-31T06:01:27 EST"`) for both US EDGAR (`10-Q`, `10-K`, `8-K`, `4`, `144`) and **Canadian SEDAR+** (`Interim financial statements/report`, `Annual financial statements`, `MD&A`, `52-109`, `NI 43-101`, `45-106F1`). Metadata + external download URLs only (no parsed Form 4 share counts). | Primary `known_at` clock for `qmFinancials` and `qmEarnings`, plus standalone filing-arrival/form-type event stream. Convert `EST`/`EDT` strings cleanly using `America/New_York` rules. |
| `qmEarnings` (`444.9k`) | `66.94%` (`297,779`) have `announceTime="N/A"` (`80,481` `AMC`, `66,605` `BTO`); `consensusEps` is overwritten post-hoc. | Link to same-day `qmFilings` `8-K` / `News release` `timefiled`; if still unknown, set `known_at = reportDate 16:05 ET` (tradable `T+1` open). |
| `qmDividends` (`495.9k`), `qmSplits` (`18.8k`), `eodSymbolChange` (`230`) | `qmDividends`: `82.3%` have `declared < date`, bogus `usdFxRate: 1` on CAD rows. `qmSplits`: `30.1%` have `declared`, `258` have `splitratio == 1`; empirically across `16,892/16,892` rows with numeric `forfactor`/`tofactor` (`100%`), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g. `NVDA 2024-06-10`: `forfactor=1, tofactor=10, splitratio=0.1`; `GE 2021-08-02`: `forfactor=8, tofactor=1, splitratio=8`). `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; invert QuoteMedia `qmSplits` to canonical `new_shares / old_shares` via `tofactor / forfactor` when both are positive numbers (avoiding 6-decimal truncation like `0.142857` for 7:1) else `1 / splitratio`; never rely on `eodSymbolChange` for multi-year ticker history. |
| `qmDividends` (`495.9k`), `qmSplits` (`18.8k`), `eodSymbolChange` (`230`) | `qmDividends`: `82.3%` have `declared < date`, bogus `usdFxRate: 1` on CAD rows. `qmSplits`: `30.1%` have `declared`, `258` have `splitratio == 1`. `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; never rely on `eodSymbolChange` for multi-year ticker history. |
| `teData` (`14.8k`), `teMarketData` (`435`), `CAD.FOREX` | `teData` has `{d, v}` final-revised values only (no release dates/vintages). `CAD.FOREX` (`eodPrices` `12,109` 1d, `eodIntraday1M` `5.20M` 1m) + `teMarketData.USDCAD` (`2,865` 1d through Apr 2026) already provide complete USD/CAD history. | Lag `teData` (`+1d` central-bank rates, `+35d` monthly CPI/NFP, `+65d/+90d` GDP) for coarse regime filters only. Curate `CAD.FOREX` + `teMarketData.USDCAD` directly into `fx_1d` and `fx_1m`. |
---
@ -184,75 +184,6 @@ CREATE INDEX IF NOT EXISTS idx_instrument_identifier_history_instrument_id
`override` is keyed by `(source, source_id, valid_from)` and applied last with precedence `1.000`. The minimal definitions for `resolution_conflict`, `override`, and `golden_field_audit` above are open to revision as M1 Passes 1–6 are built.
### M1 `>= 95%` US/CA Equity Resolution Gate Denominator
The M1 exit gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered venues** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`). Every match report preserves raw catalog totals (`Total`, `Resolved %`) alongside explicit itemized exclusions:
- **`Excluded by Design`:** `excluded_fund` (`NMFQS`, `NMF`), `composite_venue` (`US`, `TSXC`, `TSXVC`), `ats_routing_venue` (`EDGX`), and `forex_venue` (`FOREX`).
- **`Out of Gate Scope`:**
1. `zero_bar_catalog_ghost` — secondary ticker-only rows (`qm`) with `missing_span` (`0` bars in `qmPrices`), which Stage B intentionally refuses to match to prevent ticker-reuse corruption (`FB`).
2. `uncovered_venue` — listings on exchanges absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`, `ceo`, and `ib:AEQLIT`, plus `ceo:NEOE` where EODHD carries only 19 of 587 listings).
3. `non_equity_instrument` — non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX inactive shells `.H`, TSXV CPCs `.P`, and exchange test symbols).
### Research Knowledge & Findings Schema (PostgreSQL, Append-Only)
Applied via `@stock-bot/postgres` (`research` migration track, `database/postgres/init/37-research-findings.sql`, immediately after `36-trial-ledger.sql`). Owned by Stock Bot research alongside `trial_ledger` and `vault_evaluations` (see [`design/VALIDATION-AND-RIGOR.md`](VALIDATION-AND-RIGOR.md) §2A and §3 for those tables).
- **Research-visible boundary:** `findings` and `provider_caveats` store research-visible empirical evidence only. Callers and MCP adapters (`file_finding`, `read_knowledge`) are responsible for verifying that every `trial_ref` belongs to the research-visible `trial_ledger` and for excluding Vault holdout observations or Vault-only evidence from stored text and opaque `evidence_refs`.
- **Append-only enforcement:** Both tables reuse `reject_research_evidence_mutation()` from `17-research-retention.sql` via row-level `BEFORE UPDATE OR DELETE` (`findings_retained`, `provider_caveats_retained`) and statement-level `BEFORE TRUNCATE` (`findings_no_truncate`, `provider_caveats_no_truncate`) triggers, raising SQLSTATE `23514` on any mutation attempt.
- **Character-length & whitespace convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). Nonblank and trimmed-length checks use `research_trim_ecmascript(...)`, which strips the explicit 25-character ECMAScript `WhiteSpace` + `LineTerminator` set (`U+0009`..`U+000D`, `U+0020`, `U+00A0`, `U+1680`, `U+2000`..`U+200A`, `U+2028`, `U+2029`, `U+202F`, `U+205F`, `U+3000`, `U+FEFF`) regardless of database collation. JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters.
```sql
CREATE TABLE IF NOT EXISTS findings (
id TEXT PRIMARY KEY
CHECK (research_trim_ecmascript(id) <> ''),
kind TEXT NOT NULL
CHECK (kind IN ('finding', 'dead_end')),
title TEXT NOT NULL
CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256),
summary TEXT NOT NULL
CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096),
status TEXT NOT NULL DEFAULT 'pending_review'
CHECK (research_trim_ecmascript(status) <> ''),
created_at TIMESTAMPTZ NOT NULL,
trial_refs TEXT[] NOT NULL
CHECK (cardinality(trial_refs) <= 32)
CHECK (COALESCE(array_ndims(trial_refs), 1) = 1)
CHECK (research_finding_refs_valid(trial_refs, 256)),
evidence_refs TEXT[] NOT NULL
CHECK (cardinality(evidence_refs) <= 32)
CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1)
CHECK (research_finding_refs_valid(evidence_refs, 256)),
idempotency_key TEXT
CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128))
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key
ON findings (idempotency_key)
WHERE idempotency_key IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_findings_created_at
ON findings (created_at);
CREATE TABLE IF NOT EXISTS provider_caveats (
id TEXT PRIMARY KEY
CHECK (research_trim_ecmascript(id) <> ''),
provider TEXT NOT NULL
CHECK (research_trim_ecmascript(provider) <> ''),
dataset TEXT NOT NULL
CHECK (research_trim_ecmascript(dataset) <> ''),
caveat TEXT NOT NULL
CHECK (research_trim_ecmascript(caveat) <> ''),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider
ON provider_caveats (lower(provider));
```
- **Reference arrays (`trial_refs`, `evidence_refs`):** Stored as opaque 1-dimensional `TEXT[]` arrays (empty arrays permitted via `COALESCE(array_ndims(...), 1) = 1`, max 32 entries each, no `NULL` elements, max 256 chars per entry enforced via `research_finding_refs_valid`). Reference normalization, deduplication, minimum `trial_refs` count, and research-visibility checks remain in the MCP tool/adapter layer.
- **Indexes:** `idx_findings_idempotency_key` (partial unique `WHERE idempotency_key IS NOT NULL`) supports atomic compare-and-append idempotency while allowing multiple `NULL` keys; `idx_findings_created_at` supports chronological listing; `idx_provider_caveats_lower_provider` supports case-insensitive provider filtering in `read_knowledge`.
---
## 3. Curated Storage Schemas
@ -276,9 +207,9 @@ Schemas:
- **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`.
- **`corporate_actions/part.parquet`**: `(listing_id INT32, ex_date DATE, declared_date DATE, kind VARCHAR, ratio DOUBLE, cash_amount DOUBLE, currency VARCHAR, successor_listing_id INT32, terminal_return DOUBLE, known_at TIMESTAMPTZ, known_at_source VARCHAR)`.
- **`fundamentals_bitemporal/part.parquet`**: `(listing_id INT32, period_end DATE, fiscal_period VARCHAR, currency VARCHAR, known_at TIMESTAMPTZ, known_at_source VARCHAR, <standardized statement columns...>)`.
- **`fundamentals_pit/year=YYYY/part.parquet`**: Pre-resolved point-in-time snapshots partitioned by the UTC year of `effective_known_at`, sorted and unique by `(listing_id, effective_known_at)`: `(listing_id INT32 NOT NULL, effective_known_at TIMESTAMPTZ NOT NULL, known_at_source VARCHAR NOT NULL, has_estimated_lag BOOLEAN NOT NULL, period_end DATE NOT NULL, fiscal_period VARCHAR NOT NULL, currency VARCHAR NOT NULL, period_known_at TIMESTAMPTZ NOT NULL, revenue DOUBLE, net_income DOUBLE, operating_cash_flow DOUBLE, total_assets DOUBLE, total_equity DOUBLE, shares_outstanding DOUBLE, ttm_period_end DATE, ttm_currency VARCHAR, ttm_revenue DOUBLE, ttm_net_income DOUBLE, ttm_operating_cash_flow DOUBLE, ttm_has_estimated_lag BOOLEAN)` (all `ttm_*` columns are `NULL` when 4 consecutive standalone quarters in one currency are unavailable). Each snapshot computes:
- **`fundamentals_pit/year=YYYY/part.parquet`**: Wide pre-resolved point-in-time snapshots keyed by `(listing_id INT32, effective_known_at TIMESTAMPTZ)` where each row computes:
$$\text{latest } k \text{ periods by } \texttt{period\_end} \text{ of } \left(\arg\max_{\texttt{known\_at} \le \texttt{effective\_known\_at}} \text{ per } (\texttt{listing\_id}, \texttt{period\_end})\right)$$
forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2; the physical Parquet row flattens the latest visible resolved period (`periods[0]`) alongside the precomputed `ttm_*` columns (lagged slots `periods[1..]` are omitted).
forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2.
- **`events/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, known_at_source VARCHAR, kind VARCHAR, subtype VARCHAR, payload_json VARCHAR)`.
- **`shorts/part.parquet`**: `(listing_id INT32, report_date DATE, known_at TIMESTAMPTZ, shares_short DOUBLE, net_change DOUBLE, pct_float DOUBLE, source VARCHAR)`.
- **`macro/part.parquet`**: `(country_iso VARCHAR, indicator VARCHAR, period_date DATE, known_at TIMESTAMPTZ, known_at_source VARCHAR, value DOUBLE)`.

View file

@ -13,9 +13,6 @@ Start here. Every document below has a single responsibility; historical sprint
| **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)** | Raw MongoDB provider quirks, PostgreSQL security-master DDL, split/volume un-adjustment rules, `known_at` derivation, DuckDB/Parquet & QuestDB `10.2.0` schemas, and `MarketDataStore` API | Before touching `data-pipeline`, `data-ingestion`, SQL migrations, or `MarketDataStore` |
| **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** | Canonical metric definitions, `trial_ledger` schema, effective-trials DSR ($\hat{N}$), CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, lifecycle gates, and Dual Live Drift + IB/TSX execution rules | Before touching `libs/calculations`, `libs/research`, validation workflows, or paper/live execution |
| **[servers.md](servers.md)** | Host roles (`quant` `12900K` research/data server, `9900K` isolated IB live/paper host, `TrueNAS` cold storage, dev workstation) and port/storage layout | Infrastructure, deployment, and worker sizing |
| **[data-pipeline/rust-migration-evaluation.md](data-pipeline/rust-migration-evaluation.md)** | Evidence-based evaluation of keeping `apps/stock/data-pipeline` in TypeScript vs. moving bulk MongoDB streaming or the full pipeline into Rust (`tools/curate-etl`) | Before `M2` adds PIT fundamentals, `ceoPosts`, or `bars_1m` QuestDB ingestion |
| **[m2-completion-audit.md](m2-completion-audit.md)** | Historical read-only Milestone `M2` completion audit prior to `T-205`–`T-207` (`T-204`; superseded by `m2-master-audit.md`) | Historical reference for pre-`T-205` M2 state |
| **[m2-master-audit.md](m2-master-audit.md)** | Current read-only Milestone `M2` audit against `master` (post-`T-205`/`T-206`/`T-207`), Done/Partial/Missing matrix, director trade-offs, and 7-task M2 closure backlog (`T-208`) | Before closing `M2`, queuing remaining `M2` tasks, or starting `M3` |
---

View file

@ -1,78 +0,0 @@
{
"summary": {
"adjustment": "total",
"ca_bars_rows": 8446226,
"ca_shorts_rows": 459930,
"ca_filings_rows": 725435,
"shorts_panel_rows": 4541173,
"vault_bar_leaks": 0
},
"shorts_trial": {
"trial_id": 1,
"created_at": "2026-11-30T15:16:14.251727+00:00",
"expression_hash": "b8d63783a3803087c922ce7fe332340264db340f8d7de1b78cfaab097c17e938",
"n_obs": 1983,
"sharpe_unann": 0.10055685659710986,
"skewness": -0.1559440430924711,
"kurtosis": 15.987384989738644
},
"shorts_dsr": {
"trial_id": 1,
"cluster_size": 1,
"effective_trials": 1.0,
"mean_correlation": null,
"pairs_used": 0,
"pairs_skipped": 0,
"sr0": 0.0,
"standard_error": 0.023055762683025283,
"dsr": 0.9999935402185955,
"passes_gate": true
},
"shorts_mean_rank_ic": 0.00694633488509233,
"shorts_rank_ic_nw_t": 2.7256714674429414,
"shorts_mean_spread": 0.010679776876364164,
"shorts_turnover": 0.40718536083796214,
"shorts_recency": {
"pass": true,
"reason": "passed",
"pre_n": 1456,
"post_n": 527,
"pre_mean": 0.006950115972062361,
"post_mean": 0.006935888466442682,
"ratio": 0.9979529110482659
},
"filings_trial": {
"trial_id": 2,
"created_at": "2026-11-30T15:16:17.977209+00:00",
"expression_hash": "c642ca87d95bb8436045ba34a231096d74df559f0e3baf91962ba0adbe3151da",
"n_obs": 885,
"sharpe_unann": -0.08030767099801248,
"skewness": -9.933468390420595,
"kurtosis": 115.43676350904063
},
"filings_dsr": {
"trial_id": 2,
"cluster_size": 2,
"effective_trials": 2.0,
"mean_correlation": null,
"pairs_used": 0,
"pairs_skipped": 1,
"sr0": 0.06647178849749248,
"standard_error": 0.02091720841503682,
"dsr": 1.1320926489926893e-12,
"passes_gate": false
},
"filings_events_used": 101522,
"filings_n_dates": 885,
"filings_car_mean": -0.022160113638103773,
"filings_car_nw_t": -1.1695875860209246,
"filings_recency": {
"pass": false,
"reason": "sign_flipped",
"pre_n": 615,
"post_n": 270,
"pre_mean": 0.002165839268979803,
"post_mean": -0.07756922859312747,
"ratio": -35.81485925761503
}
}

View file

@ -1,117 +0,0 @@
{
"host": "quant",
"curated_root": "/mnt/data/stockbot/m1-isolated/curated",
"duckdb_version": "1.5.6",
"polars_version": "1.44.2",
"duckdb_budget": {
"memory_limit": "6GB",
"threads": 4,
"temp_directory": "/mnt/data/stockbot/m1-isolated/tmp/duckdb"
},
"cache_state_note": "run1_fresh_conn runs on a brand-new DuckDB process/connection with no prior queries; run2_warm_conn reuses the warm DuckDB connection. Unprivileged execution does not drop Linux kernel OS page cache (/proc/sys/vm/drop_caches requires root).",
"vault_cutoff_date": "2025-02-13",
"vault_rows_on_disk": 3363755,
"total_rows_in_scan": 78588295,
"distinct_listings_in_scan": 59096,
"scan_date_min": "2005-01-03",
"scan_date_max": "2025-02-12",
"nvda_pre_split_check": {
"listing_id": 20815,
"pre_split_2024_06_07": {
"close": 1208.88,
"raw_volume": 41238577.6,
"dollar_volume": 49852491689.088005,
"currency": "USD"
},
"post_split_2024_06_10": {
"close": 121.79,
"raw_volume": 314162688.0,
"dollar_volume": 38261873771.520004,
"currency": "USD"
},
"qm_pre_split_dollar_volume": 49852494590.4,
"rel_diff": 5.81979301196025e-08,
"within_1pct": true
},
"parquet_scan_vault_audit": {
"explain_analyze_latency_secs": 4.2861,
"total_files_read": 21,
"parquet_scan_rows_emitted": 78592209,
"pushed_filters": [
"session_date>='2005-01-01'::DATE AND session_date<'2025-02-13'::DATE",
"ts<'2025-02-13 00:00:00+00'::TIMESTAMP WITH TIME ZONE",
"known_at<'2025-02-13 00:00:00+00'::TIMESTAMP WITH TIME ZONE",
"optional: currency IN ('USD', 'CAD')",
"close>0.0",
"volume>0.0"
],
"vault_session_date_pushed": true,
"vault_ts_pushed": true,
"vault_known_at_pushed": true
},
"poisoned_vault_canary": {
"overlay_files_on_disk": 22,
"overlay_files_read_by_parquet_scan": 21,
"year_2026_partition_pruned": true,
"poisoned_vault_rows_on_disk": 3373755,
"canary_parquet_scan_rows_emitted": 78592209,
"scan_cardinality_identical": true,
"signal_metrics_bit_identical": true,
"pass": true
},
"run1_fresh_conn": {
"wall_secs": 4.4122,
"sql_secs": 4.4088,
"post_secs": 0.0033,
"under_5s": true,
"min_date": "2005-02-01",
"max_date": "2025-02-05",
"vault_cutoff_date": "2025-02-13",
"n_sessions_evaluated": 5129,
"mean_ic": 0.018401,
"mean_q5_q1_spread": 0.001329,
"mean_q5_turnover": 0.23419,
"recency_gate": {
"pass": true,
"reason": "passed",
"pre_n": 4592,
"post_n": 537,
"pre_mean": 0.018166680678707872,
"post_mean": 0.020400683140664375,
"ratio": 1.1229725177354413
},
"sharpe_unann": 0.05117,
"sharpe_ann": 0.8123,
"newey_west_t_stat": 2.0292,
"newey_west_p_value": 0.042434,
"dsr": 0.999927
},
"run2_warm_conn": {
"wall_secs": 4.3086,
"sql_secs": 4.3071,
"post_secs": 0.0015,
"under_5s": true,
"min_date": "2005-02-01",
"max_date": "2025-02-05",
"vault_cutoff_date": "2025-02-13",
"n_sessions_evaluated": 5129,
"mean_ic": 0.018401,
"mean_q5_q1_spread": 0.001329,
"mean_q5_turnover": 0.23419,
"recency_gate": {
"pass": true,
"reason": "passed",
"pre_n": 4592,
"post_n": 537,
"pre_mean": 0.018166680678707872,
"post_mean": 0.02040068314066438,
"ratio": 1.1229725177354415
},
"sharpe_unann": 0.05117,
"sharpe_ann": 0.8123,
"newey_west_t_stat": 2.0292,
"newey_west_p_value": 0.042434,
"dsr": 0.999927
},
"both_runs_under_5s": true
}

View file

@ -1,167 +0,0 @@
# Source Field Shapes Report
- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`)
- **Sample limit per collection:** 1000
- **Collections probed:** 8
- **Total documents sampled:** 7435
## `ceoShorts` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-23T03:58:26.303Z`, `2025-06-23T03:58:27.035Z`, `2025-06-23T03:58:27.655Z` |
| `id` | 100.0% (1000/1000) | int: 1000 | — | `101986246`, `101986286`, `101986333` |
| `issue_name` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 18..37) | `AAJ CAPITAL 3 CORP.`, `ABERDEEN INTERNATIONAL INC. J`, `ADDED CAPITAL INC.` |
| `market` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..2) | `TO`, `V` |
| `net_change` | 100.0% (1000/1000) | int: 1000 | — | `-10`, `-100`, `-1000` |
| `number_of_shares` | 100.0% (1000/1000) | int: 1000 | — | `0`, `1`, `10` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..12) | `A.V`, `AA.V`, `AAA-P.V` |
| `timestamp` | 100.0% (1000/1000) | double: 1000 | — | `1492239600000`, `1493535600000`, `1494831600000` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-26T19:28:57.102Z`, `2025-06-26T19:28:57.127Z`, `2025-06-26T19:28:57.129Z` |
## `eodPrices` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `adjustedClose` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
| `close` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-07-11T02:13:56.412Z`, `2025-07-11T02:13:56.492Z`, `2025-07-11T02:13:56.694Z` |
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2020-12-19`, `2020-12-20`, `2020-12-21` |
| `eodSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 11..14) | `$ADS-USD.CC`, `$AFLOKI-USD.CC`, `$ANRX-USD.CC` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..2) | `CC` |
| `high` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
| `low` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
| `open` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 8..11) | `$ADS-USD`, `$AFLOKI-USD`, `$ANRX-USD` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-08-13T14:09:20.036Z`, `2025-08-13T14:09:20.106Z`, `2025-08-13T14:09:20.135Z` |
| `volume` | 100.0% (1000/1000) | int: 1000 | — | `0`, `1000242`, `1006139` |
## `qmDividends` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `amount` | 100.0% (1000/1000) | int: 10, double: 990 | — | `0`, `0.01`, `0.01167` |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.799Z`, `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.069Z` |
| `currency` | 92.8% (928/1000) | string: 928 | other: 928 (len 3..3) | `CAD`, `USD` |
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1987-03-31`, `1987-06-01`, `1987-06-25` |
| `declared` | 96.5% (965/1000) | string: 965 | ymd: 965 (len 10..10) | `1987-03-25`, `1987-05-21`, `1987-05-27` |
| `divflag` | 6.2% (62/1000) | string: 62 | other: 62 (len 2..2) | `EX`, `FI`, `SP` |
| `divtype` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `D`, `S` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `NGS`, `NSC`, `NSD` |
| `frequency` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `A`, `I`, `M` |
| `indicatedrate` | 66.0% (660/1000) | double: 660 | — | `0.01`, `0.01167`, `0.0125` |
| `payable` | 99.7% (997/1000) | string: 997 | ymd: 997 (len 10..10) | `1987-04-20`, `1987-07-01`, `1987-07-20` |
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..9) | `DBM:CA`, `DCM:CA`, `DHT.U:CA` |
| `qualified` | 22.6% (226/1000) | string: 226 | other: 226 (len 1..1) | `N`, `Q` |
| `record` | 99.6% (996/1000) | string: 996 | ymd: 996 (len 10..10) | `1987-04-06`, `1987-06-05`, `1987-07-01` |
| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1987-03-31T00:00:00.000Z`, `1987-06-01T00:00:00.000Z`, `1987-06-25T00:00:00.000Z` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..8) | `DBM`, `DCM`, `DHT.U` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.080Z`, `2025-06-29T22:25:29.146Z`, `2025-06-29T22:25:29.148Z` |
| `usdFxRate` | 25.6% (256/1000) | int: 253, double: 3 | — | `0.05`, `1`, `1.39556` |
## `qmEarnings` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `actualEps` | 100.0% (1000/1000) | string: 73, int: 34, double: 893 | other: 73 (len 3..3) | `-0.01`, `-0.02`, `-0.03` |
| `announceTime` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `AMC`, `BTO`, `N/A` |
| `consensusEps` | 100.0% (1000/1000) | string: 347, int: 12, double: 641 | other: 347 (len 3..3) | `-0.02`, `-0.03`, `-0.04` |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.864Z`, `2025-06-29T22:25:29.073Z`, `2025-06-29T22:25:29.087Z` |
| `epsSurpriseDollar` | 100.0% (1000/1000) | string: 359, int: 66, double: 575 | other: 359 (len 3..3) | `-0.0033`, `-0.005`, `-0.01` |
| `epsSurprisePercent` | 100.0% (1000/1000) | string: 366, int: 147, double: 487 | other: 366 (len 3..3) | `-0.6944`, `-0.7123`, `-0.8065` |
| `estimatedEps` | 100.0% (1000/1000) | string: 347, int: 12, double: 641 | other: 347 (len 3..3) | `-0.02`, `-0.03`, `-0.04` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `CDX`, `NGS`, `NSC` |
| `numOfEstimates` | 100.0% (1000/1000) | string: 42, int: 958 | other: 42 (len 3..3) | `0`, `1`, `10` |
| `period` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..7) | `N/A`, `Q1 1995`, `Q1 1996` |
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..8) | `DLCG:CA`, `DPM:CA`, `DSV:CA` |
| `quarterEnd` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1994-09-30`, `1994-12-31`, `1995-03-31` |
| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1994-10-26T00:00:00.000Z`, `1994-10-27T00:00:00.000Z`, `1994-11-02T00:00:00.000Z` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..5) | `DLCG`, `DPM`, `DSV` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.073Z`, `2025-06-29T22:25:29.087Z`, `2025-06-29T22:25:29.167Z` |
## `qmFilings` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `acc` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 36..151) | `01521843-00000001-00002586-s@#91#91761#SEDAR#...`, `01521972-00000001-00002586-s@#91#91761#SEDAR#...`, `01523099-00000001-00002586-s@#93#93810#SEDAR#...` |
| `datefiled` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2010-01-06`, `2010-01-07`, `2010-01-12` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `CDX` |
| `filingDate` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2010-01-06`, `2010-01-07`, `2010-01-12` |
| `filingId` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 24..24) | `5e6b93561f348f7b9159eb20`, `5e6b94221f348f7b9159fa0b`, `5e6b94221f348f7b9159fa0c` |
| `formdescription` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 4..72) | `52-109F2R - Certification of refiled interim ...`, `52-109FV1 - Certification of annual filings -...`, `52-109FV2 - Certification of interim filings ...` |
| `formgroup` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 19..38) | `Continuous Disclosure`, `Continuous disclosure`, `Exempt Market Offerings and Disclosure` |
| `formtype` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 21..21) | `002-001-001012-000052`, `002-001-001012-000054`, `002-001-001012-001002` |
| `htmllink` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 225..312) | `https://app.quotemedia.com/datatool/downloadF...` |
| `pages` | 100.0% (1000/1000) | int: 1000 | — | `1`, `10`, `11` |
| `pdflink` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 224..311) | `https://app.quotemedia.com/datatool/downloadF...` |
| `size` | 100.0% (1000/1000) | null: 1000 | — | — |
| `source` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..2) | `QM` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..6) | `AAC.P`, `ACAP.P`, `ACOP` |
| `timefiled` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 23..23) | `2010-01-06T03:00:00 EST`, `2010-01-07T03:00:00 EST`, `2010-01-12T03:00:00 EST` |
## `qmPrices` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `change` | 100.0% (1000/1000) | int: 8, double: 992 | — | `-0.001851`, `-0.001877`, `-0.003661` |
| `changepercent` | 100.0% (1000/1000) | int: 8, double: 992 | — | `-0.007`, `-0.008`, `-0.014` |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T18:05:12.787Z` |
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2021-07-06`, `2021-07-07`, `2021-07-08` |
| `dateTime` | 100.0% (1000/1000) | date: 1000 | — | `2021-07-06T00:00:00.000Z`, `2021-07-07T00:00:00.000Z`, `2021-07-08T00:00:00.000Z` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `TSX` |
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 4..4) | `X:CA` |
| `sharevolume` | 100.0% (1000/1000) | int: 1000 | — | `100159`, `100168`, `100494` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `X` |
| `unadjustedclose` | 100.0% (1000/1000) | int: 29, double: 971 | — | `122.8`, `123.04`, `123.11` |
| `unadjustedhigh` | 100.0% (1000/1000) | int: 30, double: 970 | — | `123.85`, `124.4`, `124.76` |
| `unadjustedlow` | 100.0% (1000/1000) | int: 29, double: 971 | — | `121.42`, `121.9`, `122.24` |
| `unadjustedopen` | 100.0% (1000/1000) | int: 38, double: 962 | — | `122.02`, `122.24`, `122.7` |
| `unadjustedvwap` | 100.0% (1000/1000) | double: 1000 | — | `122.6259`, `123.1946`, `123.6024` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T18:59:43.948Z` |
## `qmSplits` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.834Z`, `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.085Z` |
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1972-06-21`, `1973-04-23`, `1976-07-26` |
| `declared` | 40.8% (408/1000) | string: 408 | ymd: 408 (len 10..10) | `1978-11-29`, `1979-03-02`, `1979-04-16` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..5) | `CDX`, `CNQ`, `EXPM` |
| `forfactor` | 100.0% (1000/1000) | string: 114, int: 867, double: 19 | emptyOrWhitespace: 114 (len 0..0) | <code></code>, `1`, `1.024549` |
| `payment` | 38.2% (382/1000) | string: 382 | ymd: 382 (len 10..10) | `1969-12-31`, `1979-01-05`, `1979-04-06` |
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..12) | `A`, `AAUC:CA`, `ABRA:CA` |
| `record` | 38.1% (381/1000) | string: 381 | ymd: 381 (len 10..10) | `1969-12-31`, `1978-12-12`, `1979-03-15` |
| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1972-06-21T00:00:00.000Z`, `1973-04-23T00:00:00.000Z`, `1976-07-26T00:00:00.000Z` |
| `splitratio` | 100.0% (1000/1000) | int: 305, double: 695 | — | `0.005`, `0.01`, `0.029129` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..9) | `A`, `AAUC`, `ABRA` |
| `tofactor` | 100.0% (1000/1000) | string: 114, int: 745, double: 141 | emptyOrWhitespace: 114 (len 0..0) | <code></code>, `0.067967`, `0.3333` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.085Z`, `2025-06-29T22:25:29.147Z` |
## `teMarketData` (435 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (435/435) | objectId: 435 | — | — |
| `category` | 100.0% (435/435) | string: 435 | other: 435 (len 4..9) | `bond`, `commodity`, `currency` |
| `createdAt` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` |
| `daily` | 100.0% (435/435) | array: 435 | — | — |
| `frequency` | 100.0% (435/435) | string: 435 | other: 435 (len 5..8) | `daily`, `intraday` |
| `fullName` | 100.0% (435/435) | string: 435 | other: 435 (len 3..48) | `Abu Dhabi General`, `Aluminum`, `Amman Stock Exchange General Index` |
| `industry` | 100.0% (435/435) | null: 435 | — | — |
| `lastUpdated` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` |
| `monthly` | 100.0% (435/435) | array: 435 | — | — |
| `name` | 100.0% (435/435) | string: 435 | other: 435 (len 2..28) | `ADX General`, `ASE`, `ASPI` |
| `sector` | 100.0% (435/435) | null: 435 | — | — |
| `symbolType` | 100.0% (435/435) | string: 435 | other: 435 (len 3..3) | `com`, `cur`, `gov` |
| `teSymbol` | 100.0% (435/435) | string: 435 | other: 435 (len 2..11) | `ADSMI`, `AEX`, `AS51` |
| `ticker` | 100.0% (435/435) | null: 435 | — | — |
| `type` | 100.0% (435/435) | string: 435 | other: 435 (len 4..9) | `bond`, `commodity`, `currency` |
| `unit` | 100.0% (435/435) | string: 293, null: 142 | other: 293 (len 3..19) | `AUD/100Kg`, `BRL/Kgs`, `CNY/KG` |
| `updated_at` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` |

View file

@ -1,332 +0,0 @@
# Security Master Match & Conflict Report
## Exit Thresholds
| Criterion | Status | Target |
| --- | --- | --- |
| Exchanges Mapped | PASS | 100.00% |
| Equities Resolved (Eligible) | PASS | >= 95.00% |
## Exchange Coverage
| Mapped | Unresolved | Total | Mapped % |
| --- | --- | --- | --- |
| 95 | 0 | 95 | 100.00% |
## Gate Denominator Definition
The M1 `>= 95.00%` equity resolution gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered exchanges** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`).
All raw catalog rows remain visible in `Total` and `Resolved %`; non-matched records outside the gate denominator are transparently itemized under `Excluded by Design` (`excluded_fund`, `composite_venue`, `ats_routing_venue`, `forex_venue`) and `Out of Gate Scope`:
- `zero_bar_catalog_ghost`: secondary ticker-only rows (`qm`) with `missing_span` (zero price bars in `qmPrices`, intentionally refused by Stage B Tier 3/4 temporal-overlap safety to prevent ticker-reuse corruption such as `FB`).
- `uncovered_venue`: listings on venues absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`/`ceo`/`ib:AEQLIT`, and `ceo:NEOE` where EODHD carries only 19 of 587 listings).
- `non_equity_instrument`: non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX shells `.H`, TSXV CPCs `.P`, and exchange test symbols).
## Per-Source Resolution
| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Out of Gate Scope | Eligible Total | Resolved % | Eligible Resolved % |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| eod | 66258 | 65970 | 288 | 0 | 288 | 0 | 65970 | 99.57% | 100.00% |
| ib | 18402 | 16882 | 1449 | 71 | 0 | 1165 | 17237 | 91.74% | 97.94% |
| qm | 47140 | 23394 | 23724 | 22 | 11259 | 11790 | 24091 | 49.63% | 97.11% |
| ceo | 9072 | 4904 | 4158 | 10 | 0 | 3951 | 5121 | 54.06% | 95.76% |
## Out-of-Gate-Scope Breakdown
| Source | Reason | Count |
| --- | --- | --- |
| ceo | non_equity_instrument | 1950 |
| ceo | uncovered_venue | 2001 |
| ib | non_equity_instrument | 437 |
| ib | uncovered_venue | 728 |
| qm | non_equity_instrument | 851 |
| qm | uncovered_venue | 718 |
| qm | zero_bar_catalog_ghost | 10221 |
## Per-Country Resolution
| Country | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| AU | 3 | 0 | 3 | 0 | 0 | 3 | 0.00% | 0.00% |
| BM | 13 | 0 | 13 | 0 | 0 | 13 | 0.00% | 0.00% |
| CA | 25221 | 18044 | 7148 | 29 | 0 | 25221 | 71.54% | 71.54% |
| IE | 2 | 0 | 1 | 1 | 0 | 2 | 0.00% | 0.00% |
| IL | 4 | 0 | 4 | 0 | 0 | 4 | 0.00% | 0.00% |
| JE | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| JP | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| KY | 51 | 0 | 34 | 17 | 0 | 51 | 0.00% | 0.00% |
| MH | 6 | 0 | 5 | 1 | 0 | 6 | 0.00% | 0.00% |
| NL | 2 | 0 | 2 | 0 | 0 | 2 | 0.00% | 0.00% |
| SG | 1 | 0 | 0 | 1 | 0 | 1 | 0.00% | 0.00% |
| US | 104021 | 93106 | 10861 | 54 | 6 | 104015 | 89.51% | 89.51% |
| VI | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
## Unresolved by Reason
### Stage A
| Source | Reason | Count |
| --- | --- | --- |
| ib | missing_identifiers | 4 |
### Stage B
| Source | Reason | Count |
| --- | --- | --- |
| ceo | invalid_ticker | 17 |
| ceo | no_matching_listing | 4141 |
| eod | composite_venue | 288 |
| ib | invalid_currency | 24 |
| ib | no_listing_for_currency | 1421 |
| qm | ats_routing_venue | 8283 |
| qm | composite_venue | 2976 |
| qm | invalid_ticker | 1 |
| qm | missing_span | 10221 |
| qm | no_matching_listing | 2204 |
| qm | no_span_overlap | 39 |
## Conflicts by Pass & Kind
| Pass | Conflict Kind | Count |
| --- | --- | --- |
| pass4 | price_low_correlation | 197 |
| pass4 | price_ratio_mismatch | 312 |
| stage_a | isin_cusip_mismatch | 1 |
| stage_b | ambiguous_ib_listing | 30 |
| stage_b | ambiguous_ticker_span | 22 |
| stage_b | competing_ib_conid | 40 |
| stage_b | duplicate_source_id | 10 |
## Pass 4 Price Cross-Check Verdicts
- Pairs In: 65231
- Invalid Pairs: 0
- Conflicts Emitted: 509
| Verdict | Count |
| --- | --- |
| unsupported_currency_pair | 0 |
| insufficient_data | 60599 |
| ratio_mismatch | 312 |
| low_correlation | 197 |
| confirmed | 4123 |
## Pass 6 Delisting Chain Outcomes
- Total Input Listings: 65970
- Processed Listings: 65970
- Continuities Created: 95
- Conflicts Detected: 0
| Outcome | Count |
| --- | --- |
| active | 25956 |
| moved_to_otc | 95 |
| bankruptcy_cancelled | 590 |
| unknown_involuntary | 39329 |
## Conflict Sample
| Pass | Source | Source ID | Conflict Kind | Detail |
| --- | --- | --- | --- | --- |
| pass4 | eod | AAPL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AAPL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4923,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AAPL"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | ABLT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABLT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.9623,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABLT"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | ABM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2871,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABM"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | ABR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6267,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABR"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | ABT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABT.US"},"medianRatio":1.0000009402030838,"minCorrelation":0.9,"priceCorr":0.653,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABT"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | ACD.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ACD.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.768,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ACD:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | ADM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ADM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8875,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ADM"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | ADX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ADX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6527,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ADX"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | AFG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AFG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8974,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AFG"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | AG.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AG.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8279,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AG:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | AGFXF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AGFXF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3573,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AGFXF"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | ALXN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ALXN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4186,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ALXN"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | AMAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AMAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6599,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AMAT"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | AMGN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AMGN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8658,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AMGN"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | APD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"APD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7669,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"APD"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | ARX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ARX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8297,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ARX:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | ASG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ASG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8475,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ASG"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | AUQ.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AUQ.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5609,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AUQ:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | AVU.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AVU.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.415,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AVU:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | AVY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AVY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.888,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AVY"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | B.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"B.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8517,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"B"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | BCE.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BCE.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2712,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BCE:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | BEN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BEN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8754,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BEN"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | BKH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.829,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKH"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | BKT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5579,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKT"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | BKTI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKTI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8971,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKTI"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | BLM.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BLM.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8388,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BLM:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | BMGP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BMGP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.737,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BMGP"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | BN.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BN.TO"},"medianRatio":0.9924867905232657,"minCorrelation":0.9,"priceCorr":0.7976,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BN:CA"},"usableDates":9,"verdict":"low_correlation"} |
| pass4 | eod | BN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BN.US"},"medianRatio":0.9930629800660156,"minCorrelation":0.9,"priceCorr":0.8718,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BN"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | BNSOF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BNSOF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6784,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BNSOF"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | BOH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BOH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8681,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BOH"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | BTO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BTO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7832,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BTO"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | BYDDY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BYDDY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8275,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BYDDY"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | CAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8615,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CAT"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | CCK.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CCK.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8453,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CCK"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | CFW.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CFW.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7823,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CFW:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | CGNX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CGNX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8472,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CGNX"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | CINF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CINF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5966,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CINF"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | CIX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CIX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7309,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CIX:CA"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | CL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7174,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CL"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | CMT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CMT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8188,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CMT"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | COV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"COV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2511,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"COV:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | CRRX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CRRX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7485,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CRRX:CA"},"usableDates":8,"verdict":"low_correlation"} |
| pass4 | eod | CSCO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CSCO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5838,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CSCO"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | CTAS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CTAS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.833,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CTAS"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | DF.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DF.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8822,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DF:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | DGICB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DGICB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7254,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DGICB"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | DHR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DHR.US"},"medianRatio":1.0000008038585209,"minCorrelation":0.9,"priceCorr":0.7251,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DHR"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | DIS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DIS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6493,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DIS"},"usableDates":23,"verdict":"low_correlation"} |
| pass4 | eod | DMI.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DMI.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7968,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DMI:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | DOC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DOC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5946,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DOC"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | DS.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DS.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.4049,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DS:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | DTE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DTE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7957,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DTE"},"usableDates":20,"verdict":"low_correlation"} |
| pass4 | eod | DTRK.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DTRK.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7845,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DTRK"},"usableDates":9,"verdict":"low_correlation"} |
| pass4 | eod | EA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8582,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EA"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | EAPH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EAPH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0978,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EAPH"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | EBIXQ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EBIXQ.US"},"medianRatio":0.9984378853901176,"minCorrelation":0.9,"priceCorr":0.8049,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EBIXQ"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | EEA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EEA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8994,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EEA"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | EIT-UN.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EIT-UN.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2739,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EIT.UN:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | EIX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EIX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8568,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EIX"},"usableDates":19,"verdict":"low_correlation"} |
| pass4 | eod | EKG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EKG.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8466,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EKG:CA"},"usableDates":8,"verdict":"low_correlation"} |
| pass4 | eod | EMR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EMR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8167,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EMR"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | ENS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ENS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2394,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ENS"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | ERIC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ERIC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8581,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ERIC"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | ETR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ETR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8864,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ETR"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | EXC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EXC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6761,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EXC"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | EXG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EXG.V"},"medianRatio":1.0128205128205128,"minCorrelation":0.9,"priceCorr":0.8849,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EXG:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | FAST.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FAST.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7978,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FAST"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | FE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.638,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FE"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | FI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5734,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FI"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | FLO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FLO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6659,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FLO"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | FTFT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FTFT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8561,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FTFT"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | FTU.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"FTU.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.7131,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"FTU:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | GAB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GAB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7851,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GAB"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | GLW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GLW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5909,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GLW"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | GMGI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GMGI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1581,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GMGI"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | GPC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GPC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.893,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GPC"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | GR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GR.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0751,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GR:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | GSY.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GSY.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.821,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GSY:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | GWO.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GWO.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4038,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GWO:CA"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | GWW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GWW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8347,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GWW"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | HD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3437,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HD"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | HE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8973,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HE"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | HERC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HERC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.9709,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HERC"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | HMSY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HMSY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8013,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HMSY"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | HON.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HON.US"},"medianRatio":0.9985665897393179,"minCorrelation":0.9,"priceCorr":0.7848,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HON"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | HRB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HRB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7753,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HRB"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | IAF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IAF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8914,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IAF"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | IBM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IBM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8969,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IBM"},"usableDates":23,"verdict":"low_correlation"} |
| pass4 | eod | IDXX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IDXX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7758,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IDXX"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | INVI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"INVI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8356,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"INVI"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | INX.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"INX.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1372,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"INX:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | IP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IP.US"},"medianRatio":1.0000015837820717,"minCorrelation":0.9,"priceCorr":0.8714,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IP"},"usableDates":20,"verdict":"low_correlation"} |
| pass4 | eod | IPG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IPG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8854,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IPG"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | J.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"J.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8972,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"J"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | JHI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JHI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2883,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JHI"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | JHS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JHS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5039,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JHS"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | JNJ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JNJ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4784,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JNJ"},"usableDates":20,"verdict":"low_correlation"} |
| pass4 | eod | JPM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JPM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6225,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JPM"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | K.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"K.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7446,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"K"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | KNX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"KNX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.3071,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"KNX"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | KO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"KO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7972,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"KO"},"usableDates":23,"verdict":"low_correlation"} |
| pass4 | eod | KTN.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"KTN.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1622,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"KTN:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | LB.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"LB.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7835,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"LB:CA"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | LIN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LIN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8716,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LIN"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | LOW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LOW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.692,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LOW"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | LTTC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LTTC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7122,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LTTC"},"usableDates":9,"verdict":"low_correlation"} |
| pass4 | eod | MAG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5247,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAG"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | MAH.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"MAH.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8872,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"MAH:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | MAKOF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAKOF.US"},"medianRatio":1.0010373443983402,"minCorrelation":0.9,"priceCorr":-0.3094,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAKOF"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | MAR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAR.US"},"medianRatio":1.0000850013709899,"minCorrelation":0.9,"priceCorr":0.878,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAR"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | MAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8638,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAT"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | MCD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MCD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8111,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MCD"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | MCHP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MCHP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7736,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MCHP"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | MG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8326,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MG"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | MGF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MGF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3548,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MGF"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | MGRC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MGRC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8632,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MGRC"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | MIN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MIN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2315,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MIN"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | MMT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MMT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0508,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MMT"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | MRNJ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MRNJ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4307,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MRNJ"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | MU.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MU.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.887,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MU"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | NCA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NCA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6143,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NCA"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | NDSN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NDSN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8823,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NDSN"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | NEV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NEV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4241,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NEV:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | NEWH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NEWH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.3492,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NEWH"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | NGG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NGG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7031,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NGG"},"usableDates":9,"verdict":"low_correlation"} |
| pass4 | eod | NHC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NHC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7198,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NHC"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | NJR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NJR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7038,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NJR"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | NSC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NSC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8787,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NSC"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | NTRS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NTRS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8915,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NTRS"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | NUV.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NUV.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6387,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NUV"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | NVO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NVO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8002,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NVO"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | NWX.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NWX.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8847,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NWX:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | NZP.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NZP.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8469,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NZP:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | ODX-H.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ODX-H.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7014,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ODX.H:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | OMVKY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"OMVKY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7275,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"OMVKY"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | ORCL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORCL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8616,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORCL"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | ORI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8524,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORI"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | ORN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0519,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORN"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | PAYX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PAYX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8645,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PAYX"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PBI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PBI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8444,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PBI"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PCF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PCF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5439,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PCF"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PCH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PCH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8737,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PCH"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | PDLI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PDLI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.851,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PDLI"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | PDV.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PDV.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.7666,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PDV:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | PEG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PEG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.852,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PEG"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | PEO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PEO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8323,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PEO"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PFE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PFE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8302,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PFE"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.841,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PG"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PGR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PGR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7961,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PGR"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PIM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PIM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4549,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PIM"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PNC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PNC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7715,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PNC"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PPG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8466,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPG"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PPL.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PPL.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6331,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PPL:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | PPL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPL.US"},"medianRatio":0.9962860635696822,"minCorrelation":0.9,"priceCorr":0.7763,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPL"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PPT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5062,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPT"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PSHG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PSHG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.897,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PSHG"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | PSYC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PSYC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0099,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PSYC"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | PTE.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PTE.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7833,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PTE:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | PTVCB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PTVCB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.4213,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PTVCB"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | QNC.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"QNC.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2666,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"QNC:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | RDI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"RDI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8088,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"RDI"},"usableDates":8,"verdict":"low_correlation"} |
| pass4 | eod | RJF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"RJF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4954,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"RJF"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | ROG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ROG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8908,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ROG"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | SABA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SABA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5922,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SABA"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | SBR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SBR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4564,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SBR"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | SCL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SCL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6328,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SCL"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | SDR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SDR.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8406,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SDR:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | SGC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SGC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5532,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SGC"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | SHW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SHW.US"},"medianRatio":1.0000010134792743,"minCorrelation":0.9,"priceCorr":0.7152,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SHW"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | SIM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SIM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5561,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SIM"},"usableDates":9,"verdict":"low_correlation"} |
| pass4 | eod | SKT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SKT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8894,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SKT"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | SO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7559,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SO"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | SPH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SPH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0746,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SPH"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | SR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5368,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SR"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | SR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SR.V"},"medianRatio":1.0121951219512195,"minCorrelation":0.9,"priceCorr":0.4701,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SR:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | SRC.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SRC.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1692,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SRC:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | SRG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SRG.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7455,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SRG:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | SSV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SSV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6213,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SSV:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | SWZ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SWZ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7802,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SWZ"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | SYY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SYY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.446,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SYY"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | T.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"T.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7822,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"T"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | TCF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TCF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.836,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TCF"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | TCI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TCI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2847,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TCI"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | TFX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TFX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8388,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TFX"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | TIGO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TIGO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3913,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TIGO"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | TJX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TJX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8876,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TJX"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | TLGPY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TLGPY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6001,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TLGPY"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | TMBXF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TMBXF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7082,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TMBXF"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | UHT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UHT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8031,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UHT"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | UNM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UNM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8065,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UNM"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | UNP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UNP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7949,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UNP"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | URE.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"URE.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8376,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"URE:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | UVV.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UVV.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8327,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UVV"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | VQS.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"VQS.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7545,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"VQS:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | WAFD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"WAFD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8958,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"WAFD"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | ABBNY.US | price_ratio_mismatch | {"left":{"currency":"USD","source":"eod","sourceId":"ABBNY.US"},"medianRatio":0.9512875068194219,"minCorrelation":0.9,"priceCorr":0.9996,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABBNY"},"usableDates":9,"verdict":"ratio_mismatch"} |
| pass4 | eod | ACORQ.US | price_ratio_mismatch | {"left":{"currency":"USD","source":"eod","sourceId":"ACORQ.US"},"medianRatio":120,"minCorrelation":0.9,"priceCorr":0.5059,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ACORQ"},"usableDates":7,"verdict":"ratio_mismatch"} |
| pass4 | eod | AFCC-H.V | price_ratio_mismatch | {"left":{"currency":"CAD","source":"eod","sourceId":"AFCC-H.V"},"medianRatio":0.06666666666666667,"minCorrelation":0.9,"priceCorr":0.8612,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AFCC.H:CA"},"usableDates":7,"verdict":"ratio_mismatch"} |
Showing 200 of 612 conflicts (412 more in CSV).

View file

@ -1,294 +0,0 @@
# Evaluation: Moving `apps/stock/data-pipeline` into Rust
**Date:** 2026-11-29
**Status:** Decision brief for the director (docs-only spike; no code, crate, config, or milestone changes enacted)
**Scope:** Evaluate the second half of the settled Rust ETL decision — whether to keep `apps/stock/data-pipeline` in TypeScript, move bulk MongoDB streaming into `tools/curate-etl` (Rust), or port all of `apps/stock/data-pipeline` to Rust before Milestone `M2` adds PIT fundamentals, `ceoPosts`, and `bars_1m` intraday QuestDB ingestion.
## Bottom Line (Recommendation)
**Adopt Option B: keep `apps/stock/data-pipeline` in TypeScript for security-master resolution, TSV export, probes, and BullMQ/HTTP orchestration, and add direct read-only MongoDB `RawDocumentBuf` streaming (with Rust-side read-only safety guards) to `tools/curate-etl` for bulk curation.**
- **Why not full port (Option C):** 88.1% of `apps/stock/data-pipeline/src/` (`17,924` of `20,349` LOC, backed by `40` test files / `32,435` test LOC) is logic- and review-bound security-master code operating on `319` exchanges and `396k` symbol catalog rows that already runs in sub-second synthetic benchmarks (`479.6 ms` for `100k` records in `run.ts`, `402.8 ms` for `500k` TSV mappings in `export-curate-inputs.ts`). Porting it adds weeks of parity risk, requires re-implementing BullMQ/PostgreSQL/env-safety adapters, and reopens settled decision `D5` / §4 layer boundaries for negligible wall-time gain.
- **Why not keep the JS raw-BSON file bridge forever (Option A):** While `export-raw-bson.ts` avoids JS object decoding (`3.57M–3.83M docs/s` synthetic), staging `845.7M` `eodPrices` and `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` rows through intermediate `.bson` files forces an unnecessary full NVMe write + read of hundreds of GiB (synthetic estimate: ~127–225 GiB peak file capacity / ~255–450 GiB total write+read I/O for `eodPrices`; ~499–832 GiB peak capacity / ~998–1,664 GiB total write+read I/O for the two intraday collections) before Rust even begins curating. Streaming directly from read-only MongoDB cursors in `tools/curate-etl` eliminates that scratch hop without touching the TypeScript security master.
- **Decision ownership:** The final choice among Options A, B, and C belongs to the director. None of the follow-up tasks in Section 6 are queued or enacted by this document.
---
## 1. Current `apps/stock/data-pipeline` Inventory
Measured directly from the repository working tree (no database connections). Every production file under `apps/stock/data-pipeline/src/` is `.ts` (zero non-`.ts` files).
| Area under `apps/stock/data-pipeline/src/` | Prod Files | Non-Test LOC | Dedicated Test Files | Test LOC | Primary I/O & Role |
| --- | ---: | ---: | ---: | ---: | --- |
| `security-master/` | 21 | 17,924 | 40 | 32,435 | Pure in-memory Passes 1–6 + read-only MongoDB readers (`eodSymbols`, `ibSymbols`, `qmSymbols`, `ceoSymbols`, `eodSymbolChange`, `eodPrices`, `qmPrices`, exchanges, raw BSON, field-shape probe) + PostgreSQL master read/write (`persist.ts`, `export-curate-inputs.ts`) + local file output |
| `normalization/` | 4 | 1,318 | 6 | 2,468 | Pure in-memory (`identifiers.ts`, `provider-symbol.ts`, `ticker.ts`) + read-only MongoDB aggregation reader (`bar-spans.ts`: `$match`/`$group`/`$project`/`$sort` only, `$out`/`$merge` forbidden) |
| `handlers/` | 12 | 809 | 1* | 290* | BullMQ job handlers (`{data-pipeline_exchanges}`, `{data-pipeline_symbols}` queues via `getFullQueueName`), read-only MongoDB reads, PostgreSQL master reads/writes via `PipelineSyncRepository` |
| `repositories/` | 1 | 166 | (shared)* | (shared)* | PostgreSQL transactional sync/reset (`PipelineSyncRepository`, `pg_advisory_xact_lock(1937007472, 1)`) using `@stock-bot/types` `parseReferenceDataResetRequest` |
| `routes/` | 2 | 23 | 0 | 0 | HTTP `GET /health` via Hono (`create-routes.ts`, `health.routes.ts`) |
| `types/` | 1 | 21 | 0 | 0 | Pure in-memory TypeScript interfaces (`job-payloads.ts`: `JobPayload`, `SyncResult`, `SyncStatus`) |
| `index.ts` | 1 | 88 | 0 | 0 | Service bootstrap (`ServiceApplication`, `initializeStockConfig('dataPipeline', { mongoReadOnly: true })`, port `2002`, BullMQ + HTTP + Postgres + read-only Mongo) |
| **Total (`src/`)** | **42** | **20,349** | **47** | **35,193** | — |
*\*`test/postgres/pipeline-safety.test.ts` (1 file, 290 lines) exercises both `handlers/` operations and `PipelineSyncRepository`; it is counted once in the total. `routes/`, `types/`, and `index.ts` have no dedicated unit test files and are covered indirectly by `test/unit/environment-safety*.test.ts` and `test/unit/mongodb-read-only.test.ts`.*
Separately from production LOC, `apps/stock/data-pipeline/benchmarks/` holds **5 files / 1,144 LOC** of local synthetic benchmark scripts (`export-curate-inputs-benchmark.ts`, `export-raw-bson-benchmark.ts`, `run-security-master-pass4-benchmark.ts`, `sample-closes-benchmark.ts`, `source-field-shapes-benchmark.ts`).
### Key CLI & Exporter Subsystems Inside `security-master/`
- **`run-security-master.ts` (T-89 / T-105, `1,042` LOC) + `run.ts` (`1,345` LOC):** Runs the full read-only MongoDB security-master pipeline (`read-exchanges` → `read-sources` → `compute-bar-spans` → Pass 4 `readSampleCloses` + `crossCheckPrices` → `composeSecurityMasterRun`) and writes deterministic `match-report.md`, `conflicts.csv`, `override-template.sql`, and `run-stats.json`, with opt-in `--persist` to isolated dev PostgreSQL guarded by `assertSecurityMasterPersistSafety()`. **Source note:** Pass 4 is **wired and enabled by default** in `run-security-master.ts` (`--skip-price-cross-check`, `--sample-dates <n>`), even though `apps/stock/data-pipeline/README.md` line 201 still states it is not yet wired.
- **TSV Exporter (T-116, `export-curate-inputs.ts` `2,040` LOC + `run-export-curate-inputs.ts` `345` LOC = `2,385` LOC):** Reads PostgreSQL security-master tables inside a `REPEATABLE READ READ ONLY` transaction (server-side `NO SCROLL` cursor, chunk size `<= 5,000`) and atomically publishes `provider_mapping.tsv`, `listing_currencies.tsv`, and Pass 6 `delistings.tsv` into `<out-dir>/generations/<generationId>` behind `<out-dir>/.publish.lock` and a single `<out-dir>/current` symlink.
- **Raw-BSON Exporter (T-117, `export-raw-bson.ts` `670` LOC + `run-export-raw-bson.ts` `477` LOC = `1,147` LOC):** Streams 8 allowlisted M1 MongoDB collections (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`) via `find(filter, { raw: true, batchSize })` with zero per-document JS decoding, validating BSON frame lengths, coalescing through an `8 MiB` write buffer, computing SHA-256, and publishing `<collection>.bson` atomically.
- **Field-Shape Probe (`source-field-shapes.ts` `915` LOC + `probe-source-field-shapes.ts` `291` LOC = `1,206` LOC):** Bounded read-only `find({}, { limit <= 10_000, promoteValues: false, promoteLongs: false })` probe over the 8 M1 collections to confirm live BSON field names and types before curation runs.
### Cross-App Coupling & Safety Guards
- **Zero direct package imports:** No other app or library imports `@stock-bot/data-pipeline`.
- **`web-api` runtime contract:** `apps/stock/web-api/src/services/pipeline.service.ts` enqueues BullMQ jobs onto `{data-pipeline_exchanges}` and `{data-pipeline_symbols}` via `getFullQueueName` (`libs/core/queue/src/service-utils.ts`, re-exported by `@stock-bot/queue`; using shared `@stock-bot/types` `parseReferenceDataResetRequest` / `ReferenceDataResetScope` for reset confirmation), and `apps/stock/web-api/src/services/monitoring.service.ts` monitors those two queues and polls `GET /health` on port `2002`.
- **Safety guard stack:** Every service and CLI entrypoint calls `initializeStockConfig('dataPipeline', { mongoReadOnly: true })` and `assertEnvironmentSafety()` (`apps/stock/config/src/env-safety.ts`, `706` LOC), which resolves loopback/LAN/numeric IPv4 aliases and throws if `development` targets QA PostgreSQL (`localhost:5432/trading_bot`) or opens QA MongoDB (`localhost:27017`) without `mongoReadOnly: true` or with `trading_admin`. At the driver layer, `MongoDBClient` (`libs/data/mongodb/src/client.ts`) wraps databases, collections, and cursors in read-only proxies that reject all write, index, and collection-mutation operations.
### Reproducible Inventory Commands
Re-running these POSIX commands from the repository root at the same commit reproduces every count in the table above:
```bash
# 1. Production source file counts & non-test LOC per area
for area in security-master normalization handlers repositories routes types; do
files=$(find "apps/stock/data-pipeline/src/$area" -type f -name '*.ts' | sort)
count=$(printf '%s\n' "$files" | grep -c .)
lines=$(printf '%s\n' "$files" | xargs wc -l | tail -n 1 | awk '{print $1}')
printf '%-18s files=%2d loc=%5d\n' "$area/" "$count" "$lines"
done
printf '%-18s files=%2d loc=%5d\n' "index.ts" 1 "$(wc -l < apps/stock/data-pipeline/src/index.ts)"
total_files=$(find apps/stock/data-pipeline/src -type f -name '*.ts' | wc -l)
total_lines=$(find apps/stock/data-pipeline/src -type f -name '*.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')
printf '%-18s files=%2d loc=%5d\n' "TOTAL" "$total_files" "$total_lines"
# 2. Dedicated test files & benchmark scripts
printf 'data-pipeline/test: %2d files %5d lines\n' \
"$(find apps/stock/data-pipeline/test -type f -name '*.test.ts' | wc -l)" \
"$(find apps/stock/data-pipeline/test -type f -name '*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
printf 'unit security-master: %2d files %5d lines\n' \
"$(find test/unit -type f -name 'security-master-*.test.ts' | wc -l)" \
"$(find test/unit -type f -name 'security-master-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
printf 'postgres security-master: %2d files %5d lines\n' \
"$(find test/postgres -type f -name 'security-master-*.test.ts' | wc -l)" \
"$(find test/postgres -type f -name 'security-master-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
printf 'unit normalization: %2d files %5d lines\n' \
"$(find test/unit -type f -name 'normalization-*.test.ts' | wc -l)" \
"$(find test/unit -type f -name 'normalization-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
printf 'integration provider-symbol: %2d files %5d lines\n' \
1 "$(wc -l < test/integration/provider-symbol.test.ts)"
printf 'postgres pipeline-safety: %2d files %5d lines\n' \
1 "$(wc -l < test/postgres/pipeline-safety.test.ts)"
printf 'benchmarks (separate): %2d files %5d lines\n' \
"$(find apps/stock/data-pipeline/benchmarks -type f -name '*.ts' | wc -l)" \
"$(find apps/stock/data-pipeline/benchmarks -type f -name '*.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
```
---
## 2. What Already Lives in Rust (`tools/curate-etl`)
`tools/curate-etl` is a standalone Cargo workspace member with **three exact-pinned dependencies** (`bson = "=3.1.0"` with `compat-3-0-0`, `parquet = "=60.2.0"` Zstd-only, `rayon = "=1.12.0"`), **zero async runtime**, and **zero database clients**.
| Module Group under `tools/curate-etl/src/` | Files | LOC | Contents |
| --- | ---: | ---: | --- |
| Domain builders | 9 | 8,170 | `adj.rs`, `bars.rs`, `corporate_actions.rs`, `events.rs`, `fx.rs`, `provider_mapping.rs`, `session_close.rs`, `shorts.rs`, `split.rs` |
| Zero-copy BSON decoders & framing | 7 | 5,594 | `bson_ceo_shorts.rs`, `bson_eod_prices.rs`, `bson_qm_actions.rs`, `bson_qm_events.rs`, `bson_qm_prices.rs`, `bson_stream.rs`, `bson_te_market_data.rs` |
| Zstd Parquet writers & atomic publish | 7 | 9,841 | `parquet_adj.rs`, `parquet_bars.rs`, `parquet_corporate_actions.rs`, `parquet_events.rs`, `parquet_fx.rs`, `parquet_publish.rs`, `parquet_shorts.rs` |
| Curation stages | 6 | 3,726 | `curate_adj.rs`, `curate_bars.rs`, `curate_corporate_actions.rs`, `curate_events.rs`, `curate_fx.rs`, `curate_shorts.rs` |
| Runnable `curate-*` CLI runners | 6 | 5,202 | `run_curate_adj.rs`, `run_curate_bars.rs`, `run_curate_corporate_actions.rs`, `run_curate_events.rs`, `run_curate_fx.rs`, `run_curate_shorts.rs` |
| CLI, benchmarks, entrypoints | 4 | 16,884 | `bench.rs`, `cli.rs`, `lib.rs`, `main.rs` |
| Dedicated test modules (`*_tests.rs`) | 26 | 27,215 | Unit, property, parity, and TSV/BSON fixture tests |
| **Total (`tools/curate-etl/src/`)** | **65** | **76,632** | **39 non-test files (49,417 LOC) + 26 test files (27,215 LOC)** |
Reproducible command:
```bash
find tools/curate-etl/src -type f -name '*.rs' ! -name '*_tests.rs' | wc -l
find tools/curate-etl/src -type f -name '*.rs' ! -name '*_tests.rs' | sort | xargs wc -l | tail -n 1
find tools/curate-etl/src -type f -name '*_tests.rs' | wc -l
find tools/curate-etl/src -type f -name '*_tests.rs' | sort | xargs wc -l | tail -n 1
```
The binary already implements all **six M1 curation commands** (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, `curate-fx-1d`, `curate-shorts`, `curate-events`) reading local TSVs + concatenated raw-BSON files and atomically publishing Hive-partitioned Zstd Parquet.
### Measured Local Baselines (Synthetic / Offline — Zero Live QA MongoDB or `quant` Runs)
| Benchmark | Source & Date | Command | Workload & Measured Result |
| --- | --- | --- | --- |
| `curate-bars-1d` (1-thread baseline) | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000` | `1,000,000` EOD + `227,439` QM + `2,040` splits: `decode 234.63 ms` (`4.26M rows/s`), `curate 208.07 ms`, `write 456.39 ms` (`2.06M rows/s`), **total `899.09 ms` (`1.11M rows/s`, `193.78 MB/s`)** |
| `curate-bars-1d` (`rayon` parallel write, **local re-run**) | Local sandbox re-run (`2026-11-29`, 32-thread host, synthetic) | `CARGO_BUILD_JOBS=2 cargo run --release -p curate-etl --offline -- bench-curate-bars-cmd 1000000` | Same `1,000,000`-row synthetic input: `decode 233.19 ms` (`4.29M rows/s`), `curate 207.45 ms`, `write_1 (threads=1) 445.79 ms` (`2.10M rows/s`) vs **`write (threads=32) 94.42 ms` (`9.93M rows/s`, `259.56 MB/s`, `4.72x` speedup)**, **total `535.06 ms` (`1.87M rows/s`, `325.63 MB/s`)** |
| `curate-bars-1d` (5M rows, 1-thread) | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 5000000` | `5,000,000` EOD + `1.14M` QM + `4,080` splits: **total `3,525.02 ms` (`1.42M rows/s`, `247.01 MB/s`)** |
| `curate-adj-factors` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd` | `500,000` events + `62,720` `bars_1d`: **total `436.90–500.88 ms` (`998k–1.14M events/s`)** across 2 runs |
| `curate-corporate-actions` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 1000000` | `1,000,000` events (`39,186` splits, `950,896` divs, `9,918` delistings): **total `752.71–775.67 ms` (`1.29M–1.33M events/s`)** |
| `curate-fx-1d` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-fx-cmd` | `20,000` FX rows (`CAD.FOREX` + `USDCAD`): **total `20.19–29.97 ms` (`667k–990k rows/s`)** |
| `curate-shorts` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-shorts-command` | `700,000` `ceoShorts` docs (`64.78 MiB`): **total `365.73–369.48 ms` (`1.89M–1.91M rows/s`)**, `peak_chunk_bytes = 8 MiB` |
| `curate-events` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-events-cmd` | `500,000` rows (`492.5k` filings, `7.5k` earnings): **total `838.71–861.10 ms` (`581k–596k rows/s`)**; linear synthetic extrapolation to `30.96M` rows: `51.9–53.3 s` single-core |
| `bson_eod_prices` decode-only | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-bson-eod-prices` | `1,000,000` docs (`272.4 MiB`): **`217.38–221.82 ms` (`4.51M–4.60M rows/s`, `1.23–1.25 GB/s`)** |
| `bson_stream` short-read | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-bson-stream` | `2,000,000` docs (`544.8 MiB`): **`544.59 ms` (`3.67M rows/s`, `1.00 GiB/s`, `0.963x` vs in-memory buffer, `8 MiB` peak buffer)** |
| `parquet_bars` write-only | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-parquet-bars` | `5,000,000` rows, 20 year files: **`1,422.27 ms` (`3.52M rows/s`, `155.11 MB/s`, `1.82x` Zstd)** |
| `split` builder | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-split` | `10,000,000` synthetic rows: **`367.40 ms` (`27.22M rows/s`)** |
| `bars` builder | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-bars` | `10,000,000` synthetic rows: **`842.38 ms` (`11.87M rows/s`)** |
| `provider_mapping` lookup | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-provider-mapping` | `10,000,000` synthetic lookups: **`447.14 ms` (`22.36M lookups/s`)** |
| TS `export-raw-bson` | `apps/stock/data-pipeline/README.md` (`2026-11-29`) | `bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts` | `1,000,000` synthetic `eodPrices` frames (`123.9 B` avg): **`270.8–279.8 ms` (`3.57M–3.69M docs/s`, `422–436 MiB/s`, `peak_rss 150–151 MiB`)**; `2M` docs: `3.83M docs/s`, `peak_rss 146.88 MiB` |
| TS `export-curate-inputs` | `apps/stock/data-pipeline/README.md` (`2026-11-29`) | `bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts` | `500k` mappings + `100k` listings + `2k` OTC (`606,680` TSV rows, `17.2 MB`): **`402.8 ms` (`1.51M rows/s`, `277.01 MiB` peak RSS)** |
| TS `sample-closes` (Pass 4a) | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts` | `500,025` synthetic docs (25 dates × 20k IDs + FX): **`190.3 ms` (`2.63M docs/s`)** |
| TS `source-symbol-readers` | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-source-symbol-readers.test.ts` | `368,000` synthetic symbol docs: **`488.0 ms` (`754k docs/s`)** |
| TS `security-type` classifier | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-security-type.test.ts` | `300,000` synthetic EOD records (`100k` distinct ISIN buckets, `20` conflicting ISINs): **`70.1 ms` (`4.28M records/s`, floor `>= 100k records/s`)** |
| TS `run.ts` composer (Passes 3–6) | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-run.test.ts` | `100,000` synthetic source records end-to-end: **`479.6 ms` (`208.5k records/s`)** |
| TS `persistSecurityMaster` | `apps/stock/data-pipeline/README.md` (`2026-11-28`, host Postgres safety schema) | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts` | `20k` instruments + `20k` listings + `60k` mappings (`140k` total rows): **`2.36 s` full test wall time (`>= 59.3k total rows/s`)** |
| TS `source-field-shapes` probe | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts` | `80,000` synthetic docs (8 collections × 10k): **`218.7 ms` (`365.8k docs/s`)** |
---
## 3. Workload Classification by Area
Row volumes come from the measured 2026-11-26 QA MongoDB inventory in `design/data-pipeline/phase1-investigation.md` and `design/DATA-CONTRACTS.md` §1.
| Area / Pipeline Stage | Raw / Target Volume | Bottleneck Class | Run Cadence | Rust Value-Add |
| --- | --- | --- | --- | --- |
| Pass 1 Exchanges (`exchange-pass1.ts`, `generate-exchange-seed.ts`) | `319` rows (`eodExchanges` 76, `ibExchanges` 214, `qmExchanges` 25, `ceoExchanges` 4) | **Logic / human-review-bound** | Rare (initial seed + schema override migrations) | **None** |
| Pass 2–3–5–6 Security Master (`source-symbol-readers.ts`, `instrument-stage-a.ts`, `listing-stage-b.ts`, `delisting-chains.ts`, `match-report.ts`, `run.ts`, `persist.ts`) | `396,041` symbol docs (`eodSymbols` 317.8k, `qmSymbols` 47.2k, `ibSymbols` 18.4k, `ceoSymbols` 12.6k) + `230` `eodSymbolChange` | **Logic / edge-case / review-bound** (ISIN Luhn + CUSIP rescue, IB ATS venues, ticker-reuse spans, OTC delisting chains, override precedence) | Infrequent (initial US+CA build, then periodic delta refreshes) | **Negligible** (TS already does `100k` records in `0.48 s` and `140k` PG rows in `2.36 s`) |
| Pass 2 `bar-spans.ts` & Pass 4 `sample-closes.ts` | Server-side Mongo `$group` on `eodPrices`/`qmPrices` + 25-date `$in` slice (~500k docs) | **MongoDB index/server I/O-bound** | Same as security master | **Negligible** (MongoDB server does the scan; TS client processes 500k closes in `0.19 s`) |
| TSV Export (`export-curate-inputs.ts`) | ~100k–500k PostgreSQL rows (~17 MB) | **Small Postgres read** | Before each curation batch | **Negligible** (`0.40 s` synthetic; ~17 MB on disk) |
| Field-Shape Probe (`source-field-shapes.ts`) | `<= 80,000` sampled docs (`8 × 10k`) | **Diagnostic / interactive** | Occasional schema check | **None** |
| Service Control Plane (`handlers/`, `repositories/`, `routes/`, `index.ts`) | Legacy BullMQ sync jobs + `GET /health` | **Control-plane / queue glue** | Always-on daemon (low QPS) | **Negative** (BullMQ/DI/Hono already in TS) |
| **M1 Bulk Raw-BSON Export → Parquet (`eodPrices`, `qmPrices`, `qmFilings`, `qmDividends`, `qmSplits`, `ceoShorts`, `qmEarnings`, `teMarketData`)** | **`845.7M` `eodPrices` + `51.5M` `qmPrices` + `30.5M` `qmFilings` + `1.65M` others** | **CPU + NVMe-scratch / throughput-bound** | Full backfill + nightly/weekly incremental | **High — already in Rust for curation; JS file hop adds huge NVMe scratch write+read** |
| **M2 Bulk Raw-BSON → Parquet / QuestDB ILP v2 (`eodIntraday1M`, `qmIntraday`, `ceoPosts`, `qmFinancials`)** | **`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts` + `2.77M` `qmFinancials`/`-old`** | **CPU + NVMe-scratch + network/ILP throughput-bound** | Multi-billion-row backfill + incremental | **Critical — staging `3.57B` intraday docs through local `.bson` files is an estimated ~499–832 GiB peak capacity (~998–1,664 GiB total write+read I/O) NVMe bottleneck** |
### Why the Intermediate `.bson` File Hop Hurts at M1/M2 Scale
Even though `export-raw-bson.ts` avoids JS object deserialization (`3.57M–3.83M docs/s` synthetic), it writes every raw document to `<collection>.bson` on NVMe before `curate-etl` reads the file back (so total NVMe bytes moved is **2×** the peak file size, using binary `1 GiB = 2^30` bytes throughout):
- **M1 `eodPrices` (`845.7M` docs):** Under the synthetic average frame-size assumption of `161.7–285.6 B/doc` (`bench-curate-bars-cmd` / `bench-bson-eod-prices`), staging `eodPrices.bson` requires roughly **~127–225 GiB peak scratch file capacity** and **~255–450 GiB total NVMe I/O (write + read-back)** before `qmPrices` (`51.5M`) and `qmFilings` (`30.5M`).
- **M2 intraday (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` = `3.57B` docs):** Under an assumed synthetic `150–250 B/doc` average frame size, staging both intraday collections to `.bson` files requires roughly **~499–832 GiB peak scratch file capacity** and **~998–1,664 GiB total NVMe I/O (write + read-back)** on `quant`'s 4 TB SN850X NVMe (which also holds the `~638 GB` MongoDB corpus, PostgreSQL, QuestDB, and curated Parquet). Eliminating that intermediate file via direct Rust `RawDocumentBuf` cursors saves that entire scratch file footprint and extra NVMe write+read pass. *(All byte-size figures are extrapolated from synthetic documents; actual live BSON document sizes are unverified — see Section 7.)*
---
## 4. Options Comparison
| Dimension | Option A: Keep Current TS + File-Bridge Rust Split | Option B: Direct Read-Only MongoDB Streaming in `tools/curate-etl` (Recommended) | Option C: Full Port of `apps/stock/data-pipeline` to Rust |
| --- | --- | --- | --- |
| **Architecture** | Status quo (`PLATFORM-PLAN.md` §4): TS owns security master, TSV export, raw-BSON export, probes, BullMQ/HTTP; Rust `curate-etl` reads local TSV + `.bson` files | TS keeps security master (Passes 1–6), TSV export (`export-curate-inputs.ts`), probes, BullMQ/HTTP. Rust `curate-etl` gains a read-only MongoDB cursor adapter (`--mongo-uri` / `MONGODB_READ_URI`) feeding the existing `RawDocumentBuf` decoders directly, while **retaining** file-based CLI mode for offline/reproducible tests | Rewrite all 42 TS files (`20,349` LOC) + 47 test files (`35,193` LOC) in Rust (security master, Postgres persistence, TSV/direct PG read, probes, BullMQ worker, HTTP `/health`, plus direct Mongo cursors) |
| **Estimated Effort** | **0 new files/LOC** for M1 bridge; in M2 must extend `RAW_BSON_EXPORT_COLLECTIONS` and add scratch-space management / chunked export for `3.40B` `eodIntraday1M` | **Two-stage effort:**<br>1. **Cursor-only swap (~4–6 new `.rs` files, ~1,200–1,800 LOC + ~1,000–1,500 test LOC):** Rust `env-safety` URI/host/user read-only guard, sealed `mongodb` read-only `RawDocumentBuf` cursor adapter, and `--mongo-uri` / `--collection` CLI wiring alongside existing file mode.<br>2. **Bounded-memory partitioning & overlapped I/O (additional ~3–5 `.rs` files / runner refactors, ~1,500–2,500 LOC + ~1,500–2,000 test LOC):** Date/year or key-range partitioned streaming in `run_curate_bars.rs` and `run_curate_events.rs` (which currently accumulate all decoded rows in RAM before sorting/curation) plus bounded channel pipelining between MongoDB cursor reads and `rayon` Parquet / ILP writes.<br>**Combined:** ~7–11 files, ~2,700–4,300 LOC + ~2,500–3,500 test LOC | **Very large (~40+ `.rs` files, ~15,000–22,000 LOC + ~25,000–35,000 test LOC):** Re-implement Passes 1–6, `persist.ts`, `bar-spans.ts`, `sample-closes.ts`, `source-field-shapes.ts`, `PipelineSyncRepository`, BullMQ Redis protocol, Hono `/health`, and re-verify all 47 test suites (plus Option B's Stage 1+2 work) |
| **New Rust Crates Required** | None (`bson =3.1.0`, `parquet =60.2.0`, `rayon =1.12.0` stay unchanged) | `mongodb` (with `bson-3` feature matching `bson =3.1.0`), `tokio` (minimal `rt-multi-thread`/`net`/`time` for async driver), `url` (or strict custom URI parser for safety guard). *Note: keeps zero Postgres/HTTP/Redis crates in `curate-etl`.* | Everything in Option B **plus** `tokio-postgres` / `sqlx`, `axum` / `hyper` (HTTP `/health`), `redis` + custom BullMQ Lua/stream worker compatibility (no official Rust BullMQ crate), `serde` / `serde_json`, `chrono` / `time` |
| **Expected Runtime & NVMe Gain (Evidence-Backed)** | Baseline: TS `export-raw-bson` (`3.57M–3.83M docs/s` synthetic) + Rust `curate-bars-1d` (`1.87M rows/s` with `rayon` write). Pays full NVMe scratch footprint (~127–225 GiB peak / ~255–450 GiB write+read for M1 `eodPrices`; ~499–832 GiB peak / ~998–1,664 GiB write+read for M2 intraday, synthetic estimates) | **Stage 1 (cursor-only):** Eliminates intermediate `.bson` scratch files (~100% of bulk scratch NVMe capacity and the extra write+read pass) and removes the TS process hop, **without** reducing decoded-row RAM or overlapping curation/Parquet writes (since `run_curate_bars.rs` and `run_curate_events.rs` still buffer decoded rows before sorting).<br>**Stage 2 (partitioned streaming + pipelining):** Adds bounded-memory execution (needed for global `845.7M` `eodPrices` on `quant`'s `125 GiB` RAM) and overlaps MongoDB wire reads with Rust decode/Parquet/ILP writes.<br>**End-to-end wall-time speedup is unmeasured** (see Section 7). Zero change to sub-second security-master runs | Same bulk gain as Option B; **< 1–3 seconds saved** on security master (`run.ts` is already `479.6 ms` / `100k` records; `persist.ts` is `2.36 s` / `140k` rows, bound by Postgres `UNNEST` I/O; `export-curate-inputs.ts` is `402.8 ms` / `500k` rows) |
| **Key Risks** | 1. NVMe capacity/wear spike on `quant` when exporting `3.57B` intraday docs to `.bson` files.<br>2. Two-step manual/scripted orchestration per bulk collection | 1. **Safety-guard parity:** Bypassing TS `assertEnvironmentSafety()` and `MongoDBClient` `mongoReadOnly: true` requires a battle-tested Rust read-only guard (blocking `trading_admin`, loopback/LAN IPv4 variants, and any write command).<br>2. **Memory scope:** A cursor swap alone does not bound RAM on global `845.7M` `eodPrices` until Stage 2 partitioning lands.<br>3. **Crate/async footprint:** Adds `mongodb` + `tokio` to Cargo workspace (requires crates.io fetch and offline cache refresh). | 1. **Pass 1–6 parity risk:** Re-verifying 17,924 LOC of subtle ISIN/CUSIP/ATS/ticker-reuse/delisting-chain rules against 40 test suites.<br>2. **Shared TS contract loss:** Loses `@stock-bot/types` (`ReferenceDataResetRequest`), `@stock-bot/stock-config`, `@stock-bot/postgres` migrations, and BullMQ `{data-pipeline_exchanges}`/`{data-pipeline_symbols}` queue parity with `web-api`.<br>3. **Safety-guard duplication** for both MongoDB and PostgreSQL.<br>4. **Multi-week M2 delay** with no user-visible research value |
| **Impact on M2 Work Items** | Slows M2 `bars_1m` (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` → QuestDB ILP v2) because raw `.bson` staging doesn't scale cleanly to multi-billion-row streams; `ceoPosts` (`14.8M`) and `qmFinancials` (`2.77M`) remain workable | **Directly accelerates M2:** `tools/curate-etl` streams `eodIntraday1M` (`3.40B`, **split-unadjusting** retroactively adjusted OHLCV via `qmSplits`) and `qmIntraday` (`173.3M`, taking **already-raw** `open..close` and `sharevolume` directly — **no** split un-adjustment) into multi-socket QuestDB ILP v2 (`bars_1m`, `DEDUP UPSERT KEYS(ts, listing_id)`) with zero `.bson` scratch files, verified by the M2 split-boundary comparison (`NEXM.V` `1:20` and `NVDA.US` `10:1` `bars_1m` session closes within `0.5%` of raw `bars_1d` closes); same cursor adapter serves `ceoPosts` (`14.8M`) and `qmFinancials` | **Blocks M2** for weeks while porting already-working M1 security-master code instead of building MCP, PIT fundamentals, QuestDB `10.2.0` `bars_1m`, and Feature Library |
*Why Option B keeps `export-curate-inputs.ts` in TypeScript:* Exporting `500k` security-master mappings + `100k` listings takes `402.8 ms` (`17.2 MB`) synthetically and already ships with atomic `<out-dir>/current` generation pinning consumed by `curate-etl --curate-inputs`. Keeping it in TypeScript avoids pulling a PostgreSQL driver and `assertSecurityMasterPersistSafety()` duplication into `tools/curate-etl`.
---
## 5. Compliance Check (`D1`–`D12` & QA Database Safety Rules)
### Locked Decisions `D1`–`D12` (`design/PLATFORM-PLAN.md` §3)
| Decision | Option A | Option B (Recommended) | Option C |
| --- | --- | --- | --- |
| **D1** (Parquet+DuckDB daily/PIT; QuestDB `10.2.0` intraday) | Compliant | Compliant (directly enables M2 `3.40B` ILP v2 streaming to QuestDB) | Compliant |
| **D2** (Desktop copilot MCP; isolated campaign containers) | Compliant | Compliant | Compliant |
| **D3** (US+CA priority + FX; `ttFutures` out of scope) | Compliant | Compliant | Compliant |
| **D4** (Incremental `web-app` evolution; no rewrite) | Compliant | Compliant | Risk of `web-api` / `PipelinePage` BullMQ contract drift |
| **D5** (Cross-source entity resolution in `data-pipeline`) | Compliant | Compliant — matches `PLATFORM-PLAN.md` §4 (`data-pipeline` TS + `curate-etl` Rust) and `DATA-CONTRACTS.md` §3A (`mongodb::bson::RawDocumentBuf` cursors) | **Reopens §4 layer table** (moves TS entity resolution & orchestration out of TS `data-pipeline` into Rust; requires director sign-off to amend `PLATFORM-PLAN.md`) |
| **D6** (IB Margin `USD`/`CAD` on isolated `9900K`) | Compliant (no paper/live touch) | Compliant (no paper/live touch) | Compliant (no paper/live touch) |
| **D7** (Multi-strategy scope; no macro surprises / Form 4 $) | Compliant | Compliant | Compliant |
| **D8** (Incremental Research Playground) | Compliant | Compliant | Compliant (delays M2 timeline) |
| **D9** (`marimo` Python labs) | Compliant | Compliant | Compliant |
| **D10** (Rolling 6-month Air-Gapped Vault + Post-2023 Recency) | Compliant | Compliant | Compliant |
| **D11** (Materialized batch feature jobs; no Python→TS rewrites) | Compliant | Compliant | Compliant |
| **D12** (Read-only Studio `library.yml` + Postgres findings) | Compliant | Compliant | Compliant |
### QA Database Safety Rules (`AGENTS.md`)
| Safety Rule | Option A | Option B (Recommended) | Option C |
| --- | --- | --- | --- |
| **Never drop/reset/write QA MongoDB (`localhost:27017/stock`) from `dev` or tests** | Enforced by `assertEnvironmentSafety()` + `MongoDBClient` `mongoReadOnly: true` + `studio_stock_bot_read` | **Must implement Rust read-only guard parity** before enabling `--mongo-uri`: (1) connect strictly via `MONGODB_READ_URI` with server-side `read@stock` user (`studio_stock_bot_read`); (2) reject `trading_admin` and any non-read-only URI targeting loopback/local-LAN port `27017` (matching `env-safety.ts` IPv4/octal/hex/loopback rules); (3) expose **only** `find` / `RawDocumentBuf` cursor reads in a sealed Rust module with no `insert`/`update`/`delete`/`drop`/`create_index`/`run_command` surface; (4) unit-test all rejected URIs offline | Requires Option B's Rust Mongo guard **plus** full Rust parity for PostgreSQL dev-isolation guards (`assertSecurityMasterPersistSafety`, `NODE_ENV=development` blocking `localhost:5432/trading_bot`, `pg_advisory_xact_lock`, and `rejectDestructiveSync`) |
| **Tests never mutate QA Postgres (`trading_bot`) or QA Mongo (`stock`)** | Compliant (`stock_bot_safety*` + in-memory fakes) | Compliant — retain file-based CLI mode so all `cargo test --workspace --lib --offline` tests run with zero DB connections | Compliant only if every ported Postgres test preserves isolated `stock_bot_safety*` schema creation/teardown |
| **No `data-ingestion` or `9900K` live/paper side effects** | Compliant | Compliant | Compliant |
---
## 6. Recommendation, Implied Follow-Up Tasks & What Not to Port
### Recommendation
**Select Option B.** It captures virtually 100% of the real throughput and NVMe-storage benefit of Rust where the data is actually large (`845.7M` `eodPrices`, `51.5M` `qmPrices`, `30.5M` `qmFilings`, and M2's `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts`), aligns word-for-word with `design/PLATFORM-PLAN.md` §4 and `design/DATA-CONTRACTS.md` §3A, requires no reopened locked decisions, and avoids risking or delaying M2 to rewrite 20k LOC of already-fast, heavily-tested TypeScript security-master logic.
### Implied Follow-Up Tasks (Director-Gated — Not Yet Queued or Enacted)
If the director approves Option B, the concrete follow-up sequence is:
1. **Add Rust read-only MongoDB safety guard (`tools/curate-etl/src/mongo_safety.rs`):** Port the URI/host/loopback/IPv4-normalization and `trading_admin`-blocking rules from `apps/stock/config/src/env-safety.ts` with offline unit tests mirroring `test/unit/environment-safety*.test.ts`.
2. **Add sealed read-only MongoDB `RawDocumentBuf` cursor adapter (`tools/curate-etl/src/mongo_stream.rs`):** Add exact-pinned `mongodb` (`bson-3`) + minimal `tokio` to `tools/curate-etl/Cargo.toml`, exposing only allowlisted read-only `find` streams feeding the existing `bson_*` decoders (zero write/admin methods exposed).
3. **Wire `--mongo-uri` / `MONGODB_READ_URI` cursor mode into `curate-bars-1d` and `curate-events` (Stage 1 — cursor swap + adoption parity & provenance checks):** Allow bulk M1 commands to stream directly from read-only QA MongoDB without intermediate `.bson` files while preserving `--eod-prices <path>` file mode for offline fixture replay. **Adoption gate:** assert byte-identical file-versus-cursor output parity on pinned fixtures, and emit a per-run provenance manifest recording the source snapshot or retained input identifier, exact query bounds (`filter`/date bounds and run timestamp), and the pinned `curate-inputs` security-master `generationId` (so production datasets remain traceable even if a provider later corrects a bar or filing).
4. **Add partitioned bounded-memory streaming & overlapped read/write pipelining to `curate-bars-1d` and `curate-events` (Stage 2 — global-backfill RAM & I/O):** Partition MongoDB queries by calendar year or listing-key range and pipeline async cursor reads with `rayon` Parquet writes so global `845.7M` `eodPrices` and `30.5M` `qmFilings` runs fit comfortably inside `quant`'s `125 GiB` RAM instead of buffering all decoded rows in memory.
5. **Reuse the Rust cursor adapter for M2 `curate-bars-1m` (QuestDB `10.2.0` ILP v2) and `curate-ceo-posts`:** Stream `eodIntraday1M` (`3.40B`, **un-adjusting** retroactively split-adjusted OHLCV via `qmSplits`), `qmIntraday` (`173.3M`, ingesting **already-raw** `open..close` and `sharevolume` directly without split un-adjustment), `CAD.FOREX` `1m` (`5.2M`), and `ceoPosts` (`14.8M`) directly from read-only MongoDB with zero `.bson` scratch files; enforce the M2 exit-criterion split-boundary comparison on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirming `bars_1m` session closes match raw `bars_1d` closes within `0.5%`.
6. **Keep `run-export-raw-bson.ts` as a diagnostic/fixture tool (optional deprecation later):** Retain T-117 for bounded `--limit` fixture captures and offline debugging; remove it from the bulk production path once Step 3 (and Step 4 for global backfills) is verified on `quant`.
### What Should NOT Be Ported to Rust
- **Pass 1–6 Security Master (`apps/stock/data-pipeline/src/security-master/` — 17,924 LOC, 40 test files):** Logic- and review-bound, runs in sub-second synthetic time, and has complex domain heuristics (ISIN/CUSIP rescue, IB ATS routing, ticker-reuse spans, OTC delisting chains, override precedence) that are faster to inspect and iterate in TypeScript.
- **PostgreSQL Security-Master Persistence (`persist.ts`) & TSV Exporter (`export-curate-inputs.ts`):** Already batched via `UNNEST` / server-side `NO SCROLL` cursor (`2.36 s` / `140k` rows; `0.40 s` / `500k` mappings) and tightly integrated with `@stock-bot/postgres` migrations and `assertSecurityMasterPersistSafety()`.
- **Field-Shape Probe (`source-field-shapes.ts` / `probe-source-field-shapes.ts`):** Bounded `<= 10k`-doc diagnostic utility.
- **Service Control Plane (`handlers/`, `repositories/`, `routes/`, `index.ts`):** BullMQ `{data-pipeline_exchanges}`/`{data-pipeline_symbols}` queue consumers (`getFullQueueName` in `libs/core/queue/src/service-utils.ts`), `PipelineSyncRepository`, and Hono `GET /health` tightly integrated with `@stock-bot/di`, `@stock-bot/queue`, `@stock-bot/types`, and `web-api`.
---
## 7. Not Verified
The following items were **not measured** in this docs-only spike and can only be verified on the `quant` host (`10.0.0.51`) or against live read-only QA MongoDB / dev PostgreSQL:
1. **Live MongoDB cursor throughput, WiredTiger contention, and end-to-end Option B wall-time speedup:** All `export-raw-bson.ts` (`3.57M–3.83M docs/s`) and `curate-etl` (`1.87M rows/s` with `rayon` write) numbers are local synthetic benchmarks. Actual `quant` wall time and the net end-to-end speedup of Option B (both Stage 1 cursor-only and Stage 2 overlapped I/O) are **unmeasured** and depend on WiredTiger disk reads (`--wiredTigerCacheSizeGB 16`), localhost TCP framing, BSON wire overhead on `stock` (`~638 GB`), and NVMe contention.
2. **Real BSON document sizes & NVMe scratch footprint:** The intermediate `.bson` size estimates — **~127–225 GiB peak file capacity (~255–450 GiB total write+read I/O)** for `845.7M` `eodPrices` at synthetic `161.7–285.6 B/doc`, and **~499–832 GiB peak file capacity (~998–1,664 GiB total write+read I/O)** for `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` at assumed `150–250 B/doc` (binary `1 GiB = 2^30` bytes) — extrapolate from synthetic document byte sizes; actual uncompressed BSON sizes in QA MongoDB are unmeasured.
3. **`quant` 24-thread `rayon` scaling and peak RAM:** The `4.72x` parallel Parquet write speedup (`94.42 ms` vs `445.79 ms`) was measured locally on a 32-thread host on `1,000,000` synthetic rows. Peak RAM and scaling on `quant` (`12900K`, 24 threads, `125 GiB` RAM) for the US+CA subset (~100–150M `eodPrices` rows, estimated `20–30 GiB` peak RAM) vs. full `845.7M` global rows (`> 160 GiB` unsharded, requiring date/key sharding or `--threads 1`) remain unverified.
4. **Live `bar-spans.ts` and Pass 4 `sample-closes.ts` wall time:** MongoDB `$group` aggregation time on `845.7M` `eodPrices` and `51.5M` `qmPrices`, plus live 25-date `{ date: { $in: sampleDates } }` index selectivity, have not been timed against live QA MongoDB.
5. **Unverified live provider field shapes:** Exact field names and BSON types on live QA MongoDB for `ceoShorts` (`--shares-short-field`, `timestamp` unit), `qmFilings` (`--filings-form-type-field`, `symbol` vs `qmSearchCode`), `qmEarnings` optional fields, `qmDividends` (`amount`/`currency`), `teMarketData` (`t` epoch unit), and `qmPrices.date` string vs `DateTime` format remain pending the first host run of `probe-source-field-shapes.ts`.
6. **QuestDB `10.2.0` ILP v2 throughput (M2):** Multi-socket Rust ILP v2 ingestion rate into `bars_1m` (`PARTITION BY MONTH`, `DEDUP UPSERT KEYS(ts, listing_id)`) on `quant` has not been benchmarked.
7. **Rust `mongodb` crate compile time and transitive crate count:** Exact transitive dependency footprint and offline build time for `mongodb` (`bson-3`) + `tokio` inside this workspace have not been measured because this spike adds no crates.
---
## Addendum: M1 Live Verification & Final Option B Record (`2026-11-30`)
During Milestone `M1` closure on branch `m1-close-evidence`, the Option B Rust MongoDB driver and CLI wiring (`tools/curate-etl`) were implemented, compiled offline, unit/integration-tested, and executed end-to-end against live read-only QA MongoDB (`studio_stock_bot_read@stock`) on `quant` (`10.0.0.51`) into isolated output directory `/mnt/data/stockbot/m1-isolated/curated`. Every Section 7 unknown applicable to `M1` is now resolved empirically (item 6 — QuestDB `10.2.0` ILP v2 — remains scoped strictly to `M2`):
### A.1 Dependency Footprint & Offline Build/Test Verification (Resolves §7.7)
- **Driver pin (`tools/curate-etl/Cargo.toml`):** `mongodb = "=3.10.2"` (`default-features = false`, features `compat-3-3-0`, `bson-3`, `sync`, `rustls-tls`, `dns-resolver`).
- **Transitive crate delta:** `123` transitive crates added to `Cargo.lock` (all vendored/cached for `--offline` builds; zero OpenSSL system dependency).
- **Offline build & tests:**
- `CARGO_BUILD_JOBS=2 cargo build --release -p curate-etl --offline`: **PASSED** (`1m 00s` incremental, `0` compiler warnings, `13 MB` static-TLS release binary).
- `CARGO_BUILD_JOBS=2 bun run test:native`: **PASSED** (`150` `apps/stock/engine` lib tests + `582` `curate-etl` unit tests + all `45` `curate-etl` integration/contract suites including `mongo_driver_cli_contract.rs`, `0` failures).
- **Read-only safety parity:** `tools/curate-etl/src/mongo_safety.rs` and `tools/curate-etl/src/mongo_stream.rs` enforce `MONGODB_READ_URI`, reject `trading_admin` and writable loopback/LAN URIs, and expose a sealed `ReadOnlyMongoClient` with read-only raw-BSON cursors only (zero write/admin/drop/index methods).
### A.2 Live Provider Field Shapes & Empirical Findings (Resolves §7.5)
Measured by `apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts` (`7,435` docs across all `8` M1 collections in `0.7 s`, recorded in `design/data-pipeline/m1-source-field-shapes.md`) plus live curation verification:
- **`qmSplits` sign convention (critical empirical catch):** Across all `16,892 / 16,892` (`100.00%`) `qmSplits` documents with numeric `forfactor`/`tofactor` (out of `18,751` total), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g., `NVDA 2024-06-10`: `forfactor=1, tofactor=10, splitratio=0.1`; `GE 2021-08-02`: `forfactor=8, tofactor=1, splitratio=8`). `tools/curate-etl/src/bson_qm_actions.rs` now converts to canonical `new_shares / old_shares` via exact `tofactor / forfactor` (avoiding 6-decimal truncation like `0.142857` for 7:1) or `1.0 / splitratio` when `forfactor`/`tofactor` are blank.
- **`ceoShorts` mapping key:** `ceoShorts.symbol` uses exchange-suffixed tickers (`"A.V"`, `"ACB.TO"`) matching `provider_mapping(source='eod')`, with fields `number_of_shares` and `net_change`.
- **`qmFilings` Canadian keys:** `qmFilings` omits `:CA` on Canadian `symbol` rows (`symbol: "RY", exchange: "TSX"`); `bson_qm_events.rs` qualifies Canadian exchanges to `"{symbol}:CA"` during `provider_mapping(source='qm')` resolution.
- **`qmDividends`:** Confirmed `amount` (`100%` numeric) and `currency` (`92.8%` present; missing-currency rows cleanly counted as decode rejects).
### A.3 Live `quant` Curation & Security-Master Timings (Resolves §7.1–§7.4)
| Pipeline Stage | Runtime / Host | Input Streamed (Read-Only QA Mongo) | Curated Output (Isolated Path) | Wall Time |
| --- | --- | --- | --- | ---: |
| Security-Master Passes 1–6 + dev Postgres persist (`apps/stock/data-pipeline`, TS) | Workstation -> `localhost:5433/trading_bot_dev` | `317.8k` `eodSymbols`, `18.4k` `ibSymbols`, `47.2k` `qmSymbols`, `12.6k` `ceoSymbols`, `230` `eodSymbolChange` + bar-span aggregations + 25-date Pass 4 closes | `63,703` instruments, `64,804` listings, `109,194` mappings, `93` OTC continuities (`eod=100.0%`, `ib=97.9%`, `qm=97.1%`, `ceo=95.8%` gate-eligible) | `7m 23s` total (`2.86 s` idempotent Postgres persist) |
| `curate-fx-1d --from-mongo` | `quant` (`10.0.0.51`, Rust) | `CAD.FOREX` + `teMarketData.USDCAD` | `fx_1d/part.parquet`: `12,273` rows (`356 KB`, `2,701/2,701` overlap checks passed, max diff `0.386%`) | **`0.055 s`** |
| `curate-corporate-actions --from-mongo` | `quant` (Rust) | `18,751` `qmSplits` + `495,942` `qmDividends` + `1,573` delistings | `corporate_actions/part.parquet`: `355,718` rows (`13,877` listings, `2.47 MB`) | **`0.702 s`** |
| `curate-shorts --from-mongo` | `quant` (Rust) | `692,904` `ceoShorts` | `shorts/part.parquet`: `502,610` rows (`5,184` Canadian listings, `3.58 MB`) | **`0.831 s`** |
| `curate-adj-factors --from-mongo` (`point_in_time_fenced`, `--vault-cutoff 2025-02-13`, `--date-gte 1976-01-01`) | `quant` (Rust) | `18,738` `qmSplits` + `464,850` `qmDividends` + `103.38M` `bars_1d` `prev_close` index | `adj_factors/part.parquet`: `343,746` rows (`12,512` listings, `3.90 MB`; `443` splits + `9,817` divs fenced) | **`5.976 s`** |
| `curate-events --from-mongo --date-gte 2017-01-01` | `quant` (Rust) | `16,829,977` `qmFilings` (`27.06 GB` raw BSON, string `timefiled`) + `218,815` `qmEarnings` (`75.80 MB`, BSON `DateTime` `reportDate`; `8 MB` peak chunk) | `events/year=2017..2025/part.parquet`: `2,771,888` total events (`2,569,808` filings across `11,072` listings + `202,080` earnings across `8,348` listings; `17,284` linked to same-day filings + `201,531` lagged `16:05 ET`; `86.08 MB`) | **`76.466 s`** |
| `curate-bars-1d --from-mongo --with-qm-prices --date-gte 2005-01-01 --threads 8` | `quant` (Rust, indexed 250-key `$in` chunks) | `104,009,957` `eodPrices` (`24.63 GB`) + `40,052,628` `qmPrices` (`12.97 GB`) + `18,751` `qmSplits` | `bars_1d/year=2005..2025/part.parquet`: `103,381,236` rows (`60,848` listings, `21` files, `1.106 GB`; `33.50M/38.28M` QM volume checks within 1%; `NVDA 2024-06-07` rel diff `5.82e-8`) | **`492.550 s` (`8m 12s`)** |
*Index-selectivity finding:* Querying `eodPrices` with a bare `{ date: { $gte: "2005-01-01" } }` selects `date_1_eodSearchCode_1` and causes random WiredTiger seeks (~100 min). Streaming mapped US/CA `eodSearchCode`s in 250-key `$in` chunks (`ChunkedMongoRawDocumentSource`) hits `{"eodSearchCode": 1}` sequentially and streams `37.6 GB` of raw BSON (`144.06M` docs) + writes `1.106 GB` of Zstd Parquet with **zero intermediate `.bson` scratch files** in `8m 12s`.
### A.4 Final Recommendation (Confirmed)
**Do NOT move `apps/stock/data-pipeline` itself to Rust. Lock Option B permanently:**
1. **Keep `apps/stock/data-pipeline` in TypeScript** for security-master Passes 1–6 (`17.9k` LOC, `40` test files, complex issuer/ATS/delisting heuristics), PostgreSQL persistence, TSV generation (`export-curate-inputs.ts`), field probes, and BullMQ/Hono orchestration.
2. **Keep bulk curation in Rust (`tools/curate-etl` with `--from-mongo` raw-BSON cursors)** — now proven end-to-end on `quant` at `103.38M` daily bars (`8m 12s`, `0` scratch `.bson` bytes) and `16.83M` filings + `218.8k` earnings (`76.5 s`).
3. **Keep `M2` intraday QuestDB `10.2.0` ILP v2 ingestion (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts`) scoped to `M2`** inside `tools/curate-etl`, reusing the verified `ReadOnlyMongoClient` + `ChunkedMongoRawDocumentSource` infrastructure built in `M1`.

View file

@ -1,175 +0,0 @@
# Milestone M2 Baseline Verification Report (T-128 / M2.0)
**Verdict:** **GREEN — Baseline verified for M2 start (0 real failures).** All 7 sandbox-runnable gates passed on `master` (`56b73b7e663d293079ab7bac264950dfa7a68b00`), all 40 sandbox `bun test` failures are verified sandbox-boundary errors (38 worktree `.git` metadata + 2 `stock_bot_safety*` PostgreSQL env), and Studio's authoritative unsandboxed runs — **Build `#1027`** (`bun run build`) and **Test `#1028`** (`bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline`) — passed (exit `0`) on reviewed commit `904def37e2e9cff5dce538c3d1f61ffca3594e9d`.
---
## 1. Repository Provenance & Revision Mapping
### Revisions Checked
| Role | Full SHA | Notes |
| --- | --- | --- |
| Accepted M1 commit | `d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1` | Director-accepted M1 baseline |
| `master` baseline | `56b73b7e663d293079ab7bac264950dfa7a68b00` | Base revision where all sandbox gates and full sandbox `bun test` ran |
| Reviewed report commit (`feat/m2-baseline-gates`) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Adds only `design/m2-baseline-report.md` on top of `56b73b7e663d293079ab7bac264950dfa7a68b00`; revision tested by Studio Build `#1027` and Test `#1028` |
### Unsandboxed Ancestry Checks (Confirmed)
| Check | Target Revision | Exit Code | Confirmed By |
| --- | --- | --- | --- |
| `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 56b73b7e663d293079ab7bac264950dfa7a68b00` | `master` (`56b73b7e663d293079ab7bac264950dfa7a68b00`) | `0` | Producer (plan worktree) and Reviewer |
| `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Reviewed HEAD (`904def37e2e9cff5dce538c3d1f61ffca3594e9d`) | `0` | Reviewer |
### Sandbox `git` Boundary Errors (Preserved Verbatim)
Worktree `.git` file content:
```text
gitdir: /home/boki/repos/stock-bot/.git/worktrees/slot-1
```
Because `/home/boki/repos/stock-bot/.git/worktrees/slot-1` lies outside the agent sandbox boundary, `git` commands inside the sandbox exit `128` as expected (no exit `0` was fabricated inside the sandbox):
| Command (inside sandbox) | Exit Code | Output (verbatim) |
| --- | --- | --- |
| `git rev-parse HEAD` | `128` | `fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` |
| `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 HEAD` | `128` | `fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` |
### Which Checks Ran on Which Revision
| Verification Run | Revision | Environment | Outcome |
| --- | --- | --- | --- |
| 7 sequential sandbox-runnable gates (§2) | `56b73b7e663d293079ab7bac264950dfa7a68b00` | Agent sandbox | PASS (7/7 exit `0`) |
| Full unfiltered `bun test` triage (§3) | `56b73b7e663d293079ab7bac264950dfa7a68b00` | Agent sandbox | 3,498 pass, 125 skip, 40 fail (all sandbox-only), 0 real failures |
| Studio Build `#1027` (`bun run build`) (§4) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Studio unsandboxed | PASS (exit `0`) |
| Studio Test `#1028` (`bun --env-file=... test && cargo test ...`) (§4) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Studio unsandboxed | PASS (exit `0`) |
| Targeted 10-file sandbox re-run for individual failure names (§3) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Agent sandbox | Confirmed exact same 40 failures across the 10 files |
---
## 2. Sandbox-Runnable Gates (Sequential — Revision `56b73b7e663d293079ab7bac264950dfa7a68b00`)
All seven sandbox-runnable gates exited `0` with zero failures and zero warnings:
| Gate Command | Exit Code | Result / Counts |
| --- | --- | --- |
| `bun run typecheck` (`tsc --project tsconfig.check.json --noEmit`) | `0` | PASS (0 errors) |
| `bun run test:contracts` (`tsc --project tsconfig.contracts.json --noEmit`) | `0` | PASS (0 errors) |
| `bun run lint:check` (`eslint apps/stock libs tools test --ext .ts,.tsx --max-warnings 0`) | `0` | PASS (0 errors, 0 warnings) |
| `bun run test:utils` (`bun test libs/utils/test/ libs/core/handlers/test/base-handler-http.test.ts`) | `0` | PASS — 32 pass, 0 fail (59 `expect()` calls, 3 files) |
| `bun run test:calculations` (`bun test libs/calculations/test/`) | `0` | PASS — 144 pass, 0 fail (76,602 `expect()` calls, 12 files) |
| `CARGO_BUILD_JOBS=2 bun run test:native` (`cargo test -p engine --lib --offline && cargo test -p curate-etl --offline`) | `0` | PASS — 1,078 passed, 0 failed, 4 ignored across 49 test binaries/suites |
| `CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | `0` | PASS — 732 passed, 0 failed, 4 ignored across 2 lib suites |
---
## 3. Full Unfiltered Sandbox `bun test` Triage (Revision `56b73b7e663d293079ab7bac264950dfa7a68b00`)
- **Command:** `bun test` (complete unfiltered stdout/stderr captured and inspected from start to finish)
- **Exit Code:** `1`
- **Totals:** `3,498 pass`, `125 skip`, `40 fail`, `3 errors`, `885,783 expect() calls` across `282 files` (`57.36s`)
- **Skips note:** The `125 skip` count was reported by Bun from pre-existing conditional skips in the repository (e.g., suites that self-skip when PostgreSQL / service environment variables are absent in the sandbox). This task introduced **zero** test skips, mocks, or deletions.
- **Real failures:** **`0`** (all `40` failures and `3` `beforeAll` unhandled errors are expected sandbox-boundary failures).
### Failure Classification Summary (10 files, 40 failures, 3 unhandled `beforeAll` errors)
| Test File | Fails (+ Unhandled Errors) | Exact Error Text | Classification |
| --- | --- | --- | --- |
| `test/integration/retained-strategy-worker.test.ts` | 15 (+1 `beforeAll` error) | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox |
| `test/integration/chronological-validation-native.test.ts` | 2 | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox |
| `test/integration/reproduction-comparison.test.ts` | 4 (+1 `beforeAll` error) | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox |
| `test/postgres/security-master-run.test.ts` | 1 | `error: Dedicated stock_bot_safety database required` (`test/postgres/security-master-run.test.ts:37:11`) | **(a) Expected sandbox-only** — requires `PIPELINE_TEST_DATABASE_URL` (`/home/boki/.studio/test-env/stock-bot.env`) & host PostgreSQL `127.0.0.1:5432` |
| `test/postgres/security-master-export-curate-inputs.test.ts` | 1 | `error: Dedicated stock_bot_safety database required` (`test/postgres/security-master-export-curate-inputs.test.ts:35:11`) | **(a) Expected sandbox-only** — requires `PIPELINE_TEST_DATABASE_URL` (`/home/boki/.studio/test-env/stock-bot.env`) & host PostgreSQL `127.0.0.1:5432` |
| `scripts/test/strategy-packaging.test.ts` | 10 (+1 `beforeAll` error) | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox |
| `scripts/test/benchmark-sma.test.ts` | 1 | Child process exit `1`: `git failed: fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox |
| `scripts/test/benchmark-replay.test.ts` | 2 | Child process exit `1`: `git failed: fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox |
| `scripts/test/benchmark-research.test.ts` | 1 | Child process exit `1`: `git failed: fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox |
| `scripts/test/audit-secrets-repo.test.ts` | 3 | Child process exit `1`: `Cannot inspect tracked files for the secret audit` (`git ls-files` blocked by worktree `.git` outside sandbox) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox |
### Individual Failing Test Names (All 40 Accounted For)
1. **`test/integration/retained-strategy-worker.test.ts`** (15 fails; `beforeAll` failed on `git rev-parse`):
- `retained canonical strategy worker > sma_crossover exact packaged bytes match the native report and repeat identically`
- `retained canonical strategy worker > mean_reversion exact packaged bytes match the native report and repeat identically`
- `retained canonical strategy worker > a retained version executes its own bytes when the current constructor differs`
- `retained canonical strategy worker > build and retained hashes are checked before module or factory side effects`
- `retained canonical strategy worker > eligible exact single-series data and ownership are required before bundle import`
- `retained canonical strategy worker > factory identity, missing exports, thrown decisions and no-result exits fail closed`
- `retained canonical strategy worker > capture detaches all admitted inputs before the caller can mutate them`
- `retained canonical strategy worker > result parser rejects false identity, policy and statistical claims`
- `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.artifactHash = "f".repeat(64)`
- `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.build.workerSha256 = "f".repeat(64)`
- `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.financial.policy.matching.risk.feeRate = "0"`
- `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.analytics.metrics.exposureTime = null`
- `retained canonical strategy worker > typed retained results wait for successful child exit`
- `retained canonical strategy worker > alternate and source workers cannot claim the bundled worker identity`
- `retained canonical strategy worker > hard cancellation discards retained execution and the worker can be reused`
2. **`test/integration/chronological-validation-native.test.ts`** (2 fails; `git rev-parse` in strategy packaging):
- `chronological preflight slices on the authoritative native engine > each phase independently starts with initial cash, empty positions and fresh state; warmup cannot trade`
- `chronological preflight slices on the authoritative native engine > changing only the test suffix cannot change training or validation inputs, native economics or decisions`
3. **`test/integration/reproduction-comparison.test.ts`** (4 fails; `beforeAll` failed on `git rev-parse`):
- `economic_hash_parity: two actual replays ignore only admission identities and wall-clock metadata`
- `economic hash retains fees, ordered fills, decision ownership, risk, nulls and statistical facts`
- `economic hash preserves actual market-session identities and execution policy`
- `economic hash rejects mixed result/request/session identities rather than hiding them`
4. **`test/postgres/security-master-run.test.ts`** (1 fail; requires `PIPELINE_TEST_DATABASE_URL` pointing to `stock_bot_safety*`):
- `composeSecurityMasterRun -> persistSecurityMaster PostgreSQL integration > persists FB vs FB-ETF distinct listing_ids, SIVB -> SIVBQ continuity, Pass 4 conflicts (including shared left endpoint), and is idempotent on re-run`
5. **`test/postgres/security-master-export-curate-inputs.test.ts`** (1 fail; requires `PIPELINE_TEST_DATABASE_URL` pointing to `stock_bot_safety*`):
- `exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*) > exports exact TSV bytes read-only and matches across chunkSize=1 and chunkSize=5000`
6. **`scripts/test/strategy-packaging.test.ts`** (10 fails; `beforeAll` failed on `git rev-parse`):
- `offline reviewed strategy packaging > repeat packaging retains byte-identical self-contained bundles and lock bytes`
- `offline reviewed strategy packaging > source revision, dirty state, compiler and public descriptor identity are truthful`
- `offline reviewed strategy packaging > isolated bundles require no workspace, installed packages, native engine or service runtime`
- `offline reviewed strategy packaging > residual imports and require references reject instead of retaining incomplete bundles`
- `offline reviewed strategy packaging > packaging inspects generated text without importing or executing it`
- `offline reviewed strategy packaging > a bundle missing its declared factory cannot be published as a valid built-in package`
- `offline reviewed strategy packaging > sma_crossover: source and packaged decisions/checkpoints agree through entry, exit and restore`
- `offline reviewed strategy packaging > mean_reversion: source and packaged decisions/checkpoints agree through entry, exit and restore`
- `offline reviewed strategy packaging > packaged factories retain strict parameter validation and canonical aliases`
- `offline reviewed strategy packaging > CLI writes the retained package envelope and rejects unsupported options`
7. **`scripts/test/benchmark-sma.test.ts`** (1 fail; child `git` blocked by worktree `.git`):
- `sma_recorded_decision_parity verifies six shapes and actual financial/diagnostic identities`
8. **`scripts/test/benchmark-replay.test.ts`** (2 fails; child `git` blocked by worktree `.git`):
- `all tiny replay profiles pin financial expectations and distinct strategy identities`
- `canonical self-test measures real sessions and verifies repeated full-result hashes`
9. **`scripts/test/benchmark-research.test.ts`** (1 fail; child `git` blocked by worktree `.git`):
- `existing-path research benchmark > tiny native self-test records honest phases and pinned identities without timing thresholds`
10. **`scripts/test/audit-secrets-repo.test.ts`** (3 fails; `git ls-files` blocked by worktree `.git`):
- `audit:secrets passes on the real repository`
- `real-repository audit ignores inherited GIT_DIR, GIT_WORK_TREE and GIT_INDEX_FILE`
- `audit:secrets passes on the real repository when run from scripts subdirectory`
---
## 4. Authoritative Unsandboxed Gate (Studio Runner — Revision `904def37e2e9cff5dce538c3d1f61ffca3594e9d`)
Per `studio.config.json`, Studio executed both authoritative unsandboxed commands against reviewed commit `904def37e2e9cff5dce538c3d1f61ffca3594e9d` (which has identical code and tests to `master` `56b73b7e663d293079ab7bac264950dfa7a68b00`, differing only by adding `design/m2-baseline-report.md`):
| Studio Run | Revision | Exact Command | Exit Code | Result / Counts |
| --- | --- | --- | --- | --- |
| **Build `#1027`** | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | `bun run build` | `0` | **PASS** (reported passed by Studio; per-package counts not exposed in the Studio run summary) |
| **Test `#1028`** | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | `0` | **PASS** (reported passed by Studio, exercising all 38 `.git`-dependent tests, the 2 `stock_bot_safety*` PostgreSQL tests, and the Rust workspace lib tests; per-test Bun counts are not exposed in the Studio run summary, while the Rust half verified `732 passed, 0 failed, 4 ignored` on the same tree) |
This closes the authoritative gate for T-128: every failure observed in the sandbox (`40/40`) passed in Studio's unsandboxed test run `#1028`, and `bun run build` passed in Studio build `#1027`. Updating this report triggers a fresh Studio build and test run on the updated doc-only commit.
---
## 5. Read-Only M2 Planning Facts (No Config or Code Changes Made)
1. **`@modelcontextprotocol/sdk` availability and agent network allowlist:**
- `@modelcontextprotocol/sdk` is **not present** in `bun.lock` or any `package.json` (`package.json`, `apps/`, `libs/`, `tools/`).
- `studio.config.json` (`agentExecution.programmer.networkDomains` and `agentExecution.qa.networkDomains`, lines 3–19) allows only `crates.io`, `index.crates.io`, and `static.crates.io` (no npm registry access in agent sessions). Any M2 MCP server task that needs `@modelcontextprotocol/sdk` will either need a lightweight dependency-free JSON-RPC 2.0 / MCP stdio+SSE implementation or an explicit dependency install / networkDomain decision before implementation.
2. **Python test suite (`python/tests/test_stockbot_sdk.py`) coverage:**
- `python/tests/test_stockbot_sdk.py` exists under `python/tests/`, but **is not invoked** by any script in `package.json`, `scripts/check.ts`, or `studio.config.json` (`test.command`).
3. **`studio.config.json` `docs.*` path mismatch (left untouched):**
- `docs/` does not exist at the repository root.
- `studio.config.json` lines 43–55 still point `docs.index`, `docs.plan`, `docs.milestones`, `docs.dataContracts`, `docs.validation`, `docs.dataPipeline`, and `docs.servers` at `docs/...` paths, whereas the actual milestone and architecture documents live under `design/` (e.g., `design/MILESTONES.md` lines 83–103 contain the M2 checklist and exit criteria). `studio.config.json` was intentionally left untouched in this task.

View file

@ -1,122 +0,0 @@
# Milestone M2 Completion Audit & M3 Readiness Report (T-204)
**Verdict:** **HOLD M3 — M2 is ~70% complete on the audited `feat/audit-m2-completion-status-m3` checkout (branched from `master`; exact `master` commit SHA pending host-side `git` verification), with 7 concrete wiring/contract gaps remaining before M2 closure.**
All sandbox-runnable TypeScript, ESLint, contract, and Rust native gates passed in the programmer's sandboxed run on the review checkout (`0` errors, `0` warnings), and Studio's unsandboxed review-branch runs (`#1597` build and `#1598` test suite) passed. Core M2 building blocks — `send-ilp` (`T-190`), the 6-tool MCP copilot server, file-mode PIT fundamentals/`ceoPosts`/`teData` curaters, QuestDB `10.2.0` schemas, and the TypeScript Feature Library — are landed and tested. However, desktop Claude Code cannot launch the MCP server end-to-end (`T-196` entrypoint is absent from the checkout), `ceoPosts` writes `"post"` instead of `"ceo_post"`, `MarketDataStore` rejects `crossSection`/`macroAsOf`/`fx('1m')`, `curate-qm-bars-1m` has no CLI subcommand, Python `stockbot` lacks `register_signal` and M2 store methods, and the live `quant` QuestDB `10.2.0` preflight, observed split-boundary check, and latency gates remain unverified.
> **Scope & Provenance Notes**
> - **Audit-only:** Zero production code, build config, or CI changes (project CI is off).
> - **Audited checkout & `master` relationship:** Audited in the task worktree on branch `feat/audit-m2-completion-status-m3` (branched from `master` for `T-204`). Because worktree `.git` metadata lives outside the agent sandbox, the exact `master` commit SHA and `studio/auto-*` branch history could not be read here and remain **PENDING** host-side verification. Every deliverable below was verified directly from source files, exports, CLI parsers, and test execution in this checkout.
> - **Documentation path drift:** Milestone and contract docs moved from `docs/` to `design/`, while `AGENTS.md` (lines 43–48), `CLAUDE.md` (lines 3, 7–11), `README.md` (lines 7, 9, 11–13, 142, 264, 435), and `studio.config.json` still reference `docs/*.md`.
> - **Prior M1 deferral:** Per settled director decision (`d52aa20`), M1 equity eligibility classification and cutoff-separated Parquet benchmarking stay deferred in the backlog and do not block M2.
---
## 1. Verification Gate Results & Pending Host Checks
### 1.1 Programmer Sandbox Runs (Review Worktree `feat/audit-m2-completion-status-m3`)
Executed inside the agent sandbox (network disabled; zero contact with QA MongoDB `27017/stock` or QA PostgreSQL `5432/trading_bot`; counts below are attributed to the programmer's sandbox execution without retained log files on disk):
| Gate / Suite | Command | Exit | Programmer-Observed Outcome & Counts |
| --- | --- | :---: | --- |
| Typecheck | `bun run typecheck` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.check.json --noEmit`) |
| Contracts | `bun run test:contracts` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.contracts.json --noEmit`) |
| Lint | `bun run lint:check` | `0` | **PASS** — `0` errors, `0` warnings (`--max-warnings 0`) |
| Utils | `bun run test:utils` | `0` | **PASS** — `32` pass, `0` fail (`59` expects, `3` files) |
| Calculations | `bun run test:calculations` | `0` | **PASS** — `144` pass, `0` fail (`76,602` expects, `12` files) |
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PASS** — `1,548` passed, `0` failed, `4` ignored across `57` suites (`engine` + `curate-etl`, incl. `tcp_sends_separate_shards_and_half_closes`, `restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2`, and the synthetic `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` fixture) |
| M2 Research, DuckDB, QuestDB & Scripts | `bun test libs/research/ libs/data/duckdb/ libs/data/questdb/ scripts/test/security.test.ts scripts/test/workspace.test.ts` | `0` | **PASS** — `1,032` pass, `0` fail (`80,869` expects, `63` files; includes real-DuckDB `fundamentalsAsOf` restatement fixture and MCP Vault-fence suite) |
| Postgres Copilot Executor & Unit Suites | `bun test libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts test/unit/` | `0` | **PASS** — `640` pass, `0` fail (`734,988` expects, `44` files) |
| Python SDK (`python/tests/`) | `python3 -m pytest` | N/A | **SKIPPED (env)** — `pytest` / `python/.venv` not installed in the sandbox |
### 1.2 Studio Unsandboxed Runs & Remaining Host Verification
| Verification | Scope / Command | Status | Notes |
| --- | --- | :---: | --- |
| **Studio Build `#1597`** | `bun run build` on review branch `feat/audit-m2-completion-status-m3` | **PASS** | Reported green by Studio on the review branch. |
| **Studio Test Run `#1598`** | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` on review branch `feat/audit-m2-completion-status-m3` | **PASS** | Reported green by Studio on the review branch (covers Bun test suites including isolated `stock_bot_safety*` PostgreSQL tests, plus Rust workspace `--lib` tests). |
| **Full Host Check & `master` Provenance** | Record `master` SHA, inspect `studio/auto-*` branches, and run `CARGO_BUILD_JOBS=2 bun run check` (incl. `audit:secrets`, `test:tooling`, `test:integration`, `lint:check`) + `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` with retained logs | **PENDING** | Not covered by Studio runs `#1597`/`#1598`; must be executed on the host against the confirmed `master` revision before M2 closure (see `design/m2-gap-audit.md:118-122`). |
**Research & Financial Invariants Verified Across Passing Suites**
- **Economic ownership & durable inputs:** Quant data curation owns immutable Zstd Parquet partitions (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`, `macro`) and QuestDB ILP v2 shards; PostgreSQL owns append-only `trial_ledger`, `findings`, and `provider_caveats` (`database/postgres/init/37-research-findings.sql:81-99`).
- **Holdout Vault fence:** `createQueryDataTool` (`libs/research/src/mcp/tools/query-data.ts`) and `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:40`) hardcode `vaultOperatorAuthorized: false`, reject `scope`/`vault_evaluation_only` keys, clamp bounds strictly below `vaultCutoffTs`, and drop post-cutoff rows (`libs/research/test/mcp-query-data.test.ts`).
- **PIT & synthetic split conservation:** Both Rust (`tools/curate-etl/src/fundamentals_tests.rs:104`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251,601-626`) prove `known_at <= asOf` and Q1-after-Q2 restatement non-overwrite. **Synthetic** Rust fixtures (`tools/curate-etl/src/bars_1m_tests.rs:107,220` and `tools/curate-etl/src/run_curate_bars_1m_tests.rs:377-402`) prove `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split arithmetic and ex-date boundary handling within `0.5%`, while observed-data comparison against retained raw `bars_1d` closes remains open (`run_curate_bars_1m_tests.rs:396-400`).
- **Database & execution safety:** Read-only MongoDB/Postgres adapters verified; zero paper/live execution write access in research/MCP surfaces.
---
## 2. M2 Deliverables & Exit Criteria Matrix
### 2.1 Deliverables (`design/MILESTONES.md` lines 87–98)
| Area | Status | Landed in Checkout (Exact Evidence) | Concrete Gaps Remaining |
| --- | :---: | --- | --- |
| **M2.1** Research Copilot MCP & Notebook Snapshots | **PARTIAL** | All 6 tools wired in `createResearchCopilotMcpServer` (`libs/research/src/mcp/copilot-server.ts:13-20,48`); stdio host (`libs/research/src/mcp/host/stdio-host.ts`); Postgres adapters (`libs/research/src/mcp/adapters/postgres-copilot.ts`, `postgres-trial-ref.ts`, `library-cards.ts`, `exchange-calendars.ts`, `bar-session-dates.ts`); `openResearchCopilotExecutor` (`libs/data/postgres/src/research-copilot-executor.ts`); `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:33`); SQL schema (`database/postgres/init/37-research-findings.sql`); `exportNotebookSnapshot` (`libs/research/src/notebook-snapshot.ts:594`, `notebook-snapshot-node.ts:67`). | **(1)** `T-196` desktop entrypoint `scripts/research-copilot-mcp.ts` and `"mcp:research-copilot"` in `package.json` are missing; `apps/stock/web-api/src/` has no optional SSE wrapper. **(2)** `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:37`) opens daily DuckDB only instead of composing `createRoutedMarketDataStore` + `createQuestDbIntradayBarsReader` for `1m` queries. **(3)** `analyze_signal` (`libs/research/src/mcp/tools/analyze-signal.ts:121-123`) restricts `signal.source` to `'shorts' \| 'fundamentals'` (no `ceoPosts`, `macro`, or materialized `features`). **(4)** `exportNotebookSnapshot` has no CLI or MCP entrypoint and no end-to-end MCP study + `marimo check`-clean HTML + `file_finding` verification test. |
| **M2.2** PIT Fundamentals, `ceoPosts` & Lagged `teData` | **PARTIAL** | File-mode CLIs `curate-fundamentals`, `curate-posts`, and `curate-macro` wired in `tools/curate-etl/src/cli.rs:99-101,1295,1573,1684` and `main.rs:228,238,250`; Rust Q1-after-Q2 restatement test (`tools/curate-etl/src/fundamentals_tests.rs:104`); real-DuckDB TS `fundamentalsAsOf` implementation & restatement test (`libs/research/src/market-data-store-duckdb.ts:2287`, `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`). | **(1)** `EVENT_KIND_POST = "post"` (`tools/curate-etl/src/parquet_posts.rs:22`) mismatches `'ceo_post'` required by `libs/research/src/market-data-store-duckdb.ts:108`, `libs/research/src/event-panel.ts:63`, and `python/stockbot/data.py:21`, and `run_curate_posts` fails closed (`EventsDatasetExists`, `tools/curate-etl/src/run_curate_posts.rs:133,389`) if `<out>/events` already exists from `curate-events`; both TS (`market-data-store-duckdb.ts:1448`) and Python (`python/stockbot/data.py:71`) only glob `events/year=*/part.parquet`. **(2)** `createDuckDbMarketDataStore().macroAsOf` (`libs/research/src/market-data-store-duckdb.ts:2294-2296`) throws `MarketDataStoreNotImplementedError`, blocking read-back of `macro/part.parquet` (note: per `design/DATA-CONTRACTS.md:26`, `teData` holds final-revised values only and must remain restricted to coarse lagged regime filters, not historical release signals without vintage data). **(3)** `SourceCollection` (`tools/curate-etl/src/mongo_stream.rs:53-62`) allowlists only the 8 M1 collections — no `--from-mongo` streaming for `qmFinancials`, `qmFinancials-old`, `ceoPosts`, or `teData`, and `curate-fundamentals` lacks `--qm-financials-old` merging. **(4)** Python `stockbot.data.MarketDataStore` (`python/stockbot/data.py`) lacks `fundamentals_as_of` and `macro_as_of`. |
| **M2.3** QuestDB `10.2.0` Intraday & `send-ilp` (`T-190`) | **PARTIAL** | `T-190` `send-ilp` CLI landed (`tools/curate-etl/src/cli.rs:102,2290`, `main.rs:260`, `ilp_send.rs`, `ilp_send_tests.rs` loopback `TcpListener` tests); `curate-bars-1m` and `curate-fx-1m` CLIs wired (`cli.rs:97-98`, `main.rs:208,218`); `M2_INTRADAY_SCHEMAS` (`libs/data/questdb/src/schema.ts:13-63`) with `PARTITION BY MONTH`, `WAL`, `SYMBOL CAPACITY 65536 NOCACHE`, `DEDUP UPSERT KEYS`; `docker-compose.quant.yml:35-39,52-53` (`nofile: 1048576`, `QDB_RAM_USAGE_LIMIT_BYTES=21474836480`); synthetic `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split fixtures (`bars_1m_tests.rs:107,220`, `run_curate_bars_1m_tests.rs:377-402`). | **(1)** `run_curate_qm_bars_1m` (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`, `T-185`) is not wired into `cli.rs`/`main.rs` (no `curate-qm-bars-1m` subcommand). **(2)** `MarketDataStore.fx({ timeframe: '1m' })` throws `MarketDataStoreNotImplementedError` in TS (`libs/research/src/market-data-store-duckdb.ts:1529-1530`, delegated unchanged by `createRoutedMarketDataStore` at `libs/research/src/market-data-store-routed.ts:184-186`) and `NotImplementedError` in Python (`python/stockbot/data.py:259`). **(3)** No `--from-mongo` streaming for `eodIntraday1M` (`3.40B` docs) or `qmIntraday` (`173.3M` docs). **(4)** Live `quant` preflight (`vm.max_map_count >= 1048576`, effective container `nofile = 1048576`, WAL DDL), binary-double (`0x10`) TCP ILP v2 acceptance (`tools/curate-etl/src/ilp_send.rs:15-21`), observed `NEXM.V`/`NVDA.US` comparison against retained raw `bars_1d`, and pinned PGWire 1-year `1m` read benchmark (`< 250 ms` warm / `< 1 s` cold) are all unverified. |
| **M2.4** Versioned Feature Library (`D04` / `D11`) | **PARTIAL** | TS `registerSignal`, `runFeatureBatch`, and Zstd Parquet writer landed (`libs/research/src/feature-library.ts`); built-in `RET_1D_V1` (`feature-library.ts:2166`). | **(1)** `createDuckDbMarketDataStore().crossSection` (`libs/research/src/market-data-store-duckdb.ts:2283-2285`) throws `MarketDataStoreNotImplementedError`, blocking read-back of materialized `features/<name>/v<version>/` Parquet. **(2)** `FEATURE_INPUT_DATASETS` (`libs/research/src/feature-library.ts:61-68`) omits `'macro'` (coarse regime filters only per `DATA-CONTRACTS.md:26`) and `'corporate_actions'`, and registers only `'RET_1D_V1'`. **(3)** Python `stockbot` (`python/stockbot/__init__.py`, `data.py`, `signals.py`) lacks `cross_section` and `register_signal` (`D04`/`D11`). |
### 2.2 Exit Criteria (`design/MILESTONES.md` lines 100–103)
| Exit Criterion | Status | Evidence & Remaining Blocker |
| --- | :---: | --- |
| **EC-1:** Desktop Claude Code via MCP runs a fundamental + alt-data signal study and event study end-to-end, exports a `marimo check`-clean static HTML snapshot, and files a finding. | **OPEN** | All 6 MCP tools and `exportNotebookSnapshot` exist as libraries, but `scripts/research-copilot-mcp.ts` / `"mcp:research-copilot"` (`T-196`) is missing, `ceoPosts` cannot be read via `event_study` (`"post"` vs `"ceo_post"`), and no end-to-end MCP → HTML snapshot → `file_finding` verification exists. |
| **EC-2:** Restatement fixture test proves a restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`. | **SATISFIED (Offline Fixture)** | Proven in both Rust (`tools/curate-etl/src/fundamentals_tests.rs:104`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251,601-626`), both passing in sandbox and Studio test run `#1598`. |
| **EC-3:** Split-boundary test on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirms `bars_1m` session closes match raw `bars_1d` closes within `0.5%`, and 1y of `1m` bars loads in `< 250 ms` warm / `< 1 s` cold. | **OPEN (Synthetic Only)** | **Synthetic** Rust fixtures (`tools/curate-etl/src/bars_1m_tests.rs:107,220`, `run_curate_bars_1m_tests.rs:377-402`) pass for split arithmetic only and explicitly leave observed comparison against retained raw `bars_1d` open (`run_curate_bars_1m_tests.rs:396-400`). Still open on `quant`: (1) effective `vm.max_map_count >= 1048576` & container `nofile = 1048576` preflight before bulk load; (2) live QuestDB `10.2.0` binary-double (`0x10`) TCP ILP v2 acceptance; (3) observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` close check (`<= 0.5%`); and (4) pinned 1-year single-listing PGWire benchmark (`QuestDBClient.query` → `createQuestDbIntradayBarsReader`) recording listing ID, date range, cache conditions, and expected vs. actual row counts against `< 250 ms` warm / `< 1 s` cold. |
---
## 3. Candidate Causes: Why M2 Auto Mode May Have Parked 3 Consecutive Tasks
No parked task receipts or Auto Mode run logs are available inside the sandbox, so **none of the four items below can be attributed to a specific parked task yet**. Separating what is directly observed in the checkout from what remains inferred pending host history/log inspection:
1. **Missing `T-196` desktop MCP entrypoint *(observed in checkout; branch-reset cause inferred/unverified)*:** `scripts/research-copilot-mcp.ts` and `"mcp:research-copilot"` in `package.json` are absent from the checkout, whereas `T-190` (`send-ilp`) and `curate-macro` are present. Any Auto Mode task expecting a runnable desktop MCP entrypoint would hit an immediate blocker. Whether `T-196` was dropped during a `studio/auto-*` branch reset remains **unverified** until host-side branch history is inspected (`design/m2-gap-audit.md:119`).
2. **`docs/*` → `design/*` path drift *(observed in checkout; park attribution unverified)*:** `AGENTS.md` (L43–48), `CLAUDE.md` (L3, L7–11), `README.md` (L7, L9, L11–13, L142, L264, L435), `studio.config.json`, and older task prompts still point to `docs/*.md`, which can cause agents to fail path checks against the renamed `design/` directory.
3. **Sandbox boundary friction for `.git`, PostgreSQL, and `quant` *(observed environment constraint; park attribution unverified)*:** Running `bun run check`, `audit:secrets`, worktree-git tests (`scripts/test/`), `PIPELINE_TEST_DATABASE_URL` (`127.0.0.1:5432`) suites, or live `quant` QuestDB checks inside the agent sandbox fails by design; tasks without explicit host/sandbox separation can park on those expected errors.
4. **Unqueued Option B `--from-mongo` extension for M2 collections *(observed in checkout; park attribution unverified)*:** The `2026-11-30` addendum in `design/data-pipeline/rust-migration-evaluation.md` (lines 253–294) locked Option B (`tools/curate-etl --from-mongo`) for M1 and scoped M2's 6 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`) to M2, but `SourceCollection` (`tools/curate-etl/src/mongo_stream.rs:53-62`) still allowlists only the 8 M1 collections.
---
## 4. Concrete Blockers Needing Director Decisions
1. **Option B `--from-mongo` for M2 collections vs. `.bson` staging:** Should we extend `tools/curate-etl` `SourceCollection` with `--from-mongo` streaming for the 6 M2 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`), or close M2 in file-mode `.bson` staging?
- *Recommended:* Extend `--from-mongo` to the 6 M2 collections (reusing the M1 `ReadOnlyMongoClient` + `ChunkedMongoRawDocumentSource` pattern) so `3.40B` `eodIntraday1M` docs never require `~500–832 GiB` of intermediate `.bson` scratch files.
2. **Canonical `ceoPosts` event `kind` & `<out>/events` co-publishing:** Should `tools/curate-etl/src/parquet_posts.rs` switch `EVENT_KIND_POST` from `"post"` to `"ceo_post"` and co-publish alongside `curate-events` under `<out>/events/year=YYYY/` (either by writing `part-posts.parquet` **and updating both readers** — `libs/research/src/market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` — from `events/year=*/part.parquet` to `events/year=*/*.parquet`, or by merging posts into yearly `part.parquet`), or keep posts in a separate curated root?
- *Recommended:* Change `EVENT_KIND_POST` to `"ceo_post"`, write `events/year=YYYY/part-posts.parquet`, **and update both TS (`market-data-store-duckdb.ts:1448`) and Python (`python/stockbot/data.py:71`) readers to glob `events/year=*/*.parquet`** (verified by a combined read-back fixture with filings, earnings, and an edited CEO post in the same curated root) so `curate-events` and `curate-posts` remain independently re-runnable without hiding posts from either reader.
3. **Live `quant` QuestDB `10.2.0` preflight, observed split check & latency gate for M2 closure:** Should M2 closure require an operator-run `quant` QuestDB `10.2.0` verification covering host/container limits (`vm.max_map_count`, `nofile`), binary-double (`0x10`) TCP ILP v2 acceptance, observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` closes (`<= 0.5%`), and a pinned 1-year single-listing PGWire latency benchmark (`< 250 ms` warm / `< 1 s` cold), or accept synthetic-fixture closure and defer all live `quant` checks to an ops follow-up (matching the M1 `d52aa20` precedent)?
- *Recommended:* Require a small-slice (`NEXM.V` + `NVDA.US`, 1 year) operator verification on `quant` covering all four checks above before closing M2, while deferring full `3.40B`-row backfill to an ops runbook.
---
## 5. M3 Readiness Mapping & Recommended Task Order
**Verdict: Do not start M3 yet.** M2 must close first, and M3's core engine, screener, and validation deliverables are unstarted on this checkout.
### 5.1 M3 Deliverables & Exit Criteria Readiness Map (`design/MILESTONES.md` lines 111–128)
| M3 Item | Status | Target Files & Current Checkout Evidence |
| --- | :---: | --- |
| **Tier 1 Columnar Screener** (`MILESTONES.md:112-113`) | **NOT STARTED** | Append-only `trial_ledger` SQL exists (`database/postgres/init/36-trial-ledger.sql`), and `libs/calculations/src/index.ts` exports `deflatedSharpeRatio`, `effectiveIndependentTrials`, `analyzeSignalPanel`, `eventStudy`, `evaluateRecencyGate`. No Polars/DuckDB portfolio sweep, $M_{T \times N}$ writer, or CSCV `PBO` ($S = 16$) yet. |
| **Tier 2 Rust `financial/` Multi-Asset Upgrades** (`MILESTONES.md:114-119`) | **NOT STARTED** | `apps/stock/engine/Cargo.toml` has no `parquet`/`arrow-rs` crates yet; `apps/stock/orchestrator/src/backtest/{native-worker,candidate-sandbox}.ts` still use the single-series JSON/IPC path. Task 1 (retire `backtest_datasets` JSONB/IPC/N-API bar path), atomic timestamp-slice marks (`F06`), simultaneous `Target` sell-netting, feature side-channel, and `USD`/`CAD` Margin + corporate actions/delisting in `apps/stock/engine/src/financial/*` are all unstarted. |
| **Validation Suite & Engine Consolidation** (`MILESTONES.md:120-123`) | **PARTIAL (SQL only)** | `vault_evaluations` table with `<= 10/year` cap & append-only triggers exists (`database/postgres/init/36-trial-ledger.sql:44-138`), and `apps/stock/analytics` / `SimulationExecution` are already absent from the repo. Purged Walk-Forward/CPCV, stability surface, ADV capacity, US/CA factor exposure, human Vault Holdout Gate workflow, and retirement of legacy `f64` `BacktestEngine` (`apps/stock/engine/src/backtest/engine.rs:17`, `apps/stock/engine/src/api/backtest.rs:13`) remain **NOT STARTED**. |
| **M3 EC-1:** Rust unit + differential accounting fixtures (`MILESTONES.md:126`) | **OPEN** | Atomic hedged mark neutrality, 100%-invested `Sell A + Buy B` target rotation, split + dividend 8-decimal conservation, USD/CAD margin interest, TSX board-lot sizing, and `SIVB` delisting liquidation fixtures are not yet implemented. |
| **M3 EC-2:** 20y US+CA daily backtest (`~5,000+` listings) in `< 30 s` on `quant` (`MILESTONES.md:127`) | **OPEN** | Blocked on Tier 2 Parquet/Arrow-rs path + multi-asset engine upgrades. |
| **M3 EC-3:** Real M2 signal via `register_signal` end-to-end (`MILESTONES.md:128`) | **OPEN** | Blocked on M2 Python `register_signal` + `crossSection` read-back and M3 Tier 1/Tier 2/CPCV/Vault gate. |
### 5.2 Ordered Task List to Finish M2 (8 Tasks)
1. **Restore `T-196` desktop MCP entrypoint & wire routed intraday store:** Add `scripts/research-copilot-mcp.ts` + `"mcp:research-copilot"` in `package.json`, and update `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`) to compose `createRoutedMarketDataStore` + `createQuestDbIntradayBarsReader` when QuestDB config is present.
2. **Fix `ceoPosts` `kind = 'ceo_post'`, `<out>/events` co-publishing & reader globs:** Change `EVENT_KIND_POST` in `tools/curate-etl/src/parquet_posts.rs` to `"ceo_post"`, co-publish `ceoPosts` under `<out>/events/year=YYYY/` (either writing `part-posts.parquet` and updating both `libs/research/src/market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` to glob `events/year=*/*.parquet`, or merging into yearly `part.parquet`), and add a combined read-back fixture containing filings, earnings, and an edited CEO post in the same curated root.
3. **Implement `MarketDataStore.macroAsOf`, `crossSection`, and `fx('1m')`:** Implement DuckDB read-back for `macro/part.parquet` (`macroAsOf`, enforcing/documenting the `design/DATA-CONTRACTS.md:26` coarse lagged regime-filter-only limit since `teData` lacks release vintages) and versioned `features/<name>/v<version>/` (`crossSection`) in `libs/research/src/market-data-store-duckdb.ts`, and route `fx({ timeframe: '1m' })` to QuestDB `fx_1m` in `libs/research/src/market-data-store-routed.ts`.
4. **Wire `curate-qm-bars-1m` CLI & expand Feature Library inputs:** Expose `curate-qm-bars-1m` in `tools/curate-etl/src/{cli,main}.rs`, add `'macro'` (restricted to lagged regime filters per `DATA-CONTRACTS.md:26` until vintage data exists) and `'corporate_actions'` to `FEATURE_INPUT_DATASETS` in `libs/research/src/feature-library.ts`, and extend MCP `analyze_signal` to support materialized `features` (and `ceoPosts` / regime-only `macro` as needed).
5. **Add Python `stockbot` M2 parity & `register_signal` (`D04`/`D11`):** Expose `fundamentals_as_of`, `macro_as_of` (regime-only), `cross_section`, `fx(..., timeframe='1m')`, and `register_signal(...)` in `python/stockbot/` with offline `pytest` coverage.
6. **Extend `curate-etl --from-mongo` to the 6 M2 collections (subject to Director Decision 1):** Add `qmFinancials`, `qmFinancials-old` (with `--qm-financials-old` merge), `ceoPosts`, `teData`, `eodIntraday1M`, and `qmIntraday` to `SourceCollection` in `tools/curate-etl/src/mongo_stream.rs`.
7. **Add M2 Exit Criterion 1 end-to-end verification & doc path cleanup:** Add a CLI/MCP wrapper + end-to-end test covering MCP study → `marimo check`-clean HTML snapshot (`exportNotebookSnapshot`) → `file_finding`, and update stale `docs/` links in `AGENTS.md`, `CLAUDE.md`, `README.md`, and `studio.config.json` to `design/`.
8. **Operator `quant` QuestDB `10.2.0` preflight, observed split check & latency benchmark (Exit Criterion 3):** Before bulk load, verify on `quant` effective `vm.max_map_count >= 1048576`, container `ulimits.nofile = 1048576`, memory limits, and `getM2IntradayDDL()` WAL tables; run `send-ilp` on a small `NEXM.V` + `NVDA.US` 1-year slice to verify `0x10` binary-double acceptance and `wal_tables()` health via PGWire; compare observed `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) `bars_1m` session closes against retained raw `bars_1d` closes (`<= 0.5%`); and run a pinned 1-year single-listing `1m` benchmark through `QuestDBClient.query` → `createQuestDbIntradayBarsReader` (re-verifying via `createRoutedMarketDataStore` once wired) recording listing ID, date range, cache conditions, and expected vs. actual row counts against `< 250 ms` warm / `< 1 s` cold.
### 5.3 Initial M3 Prerequisite Sequence (Once M2 Closes)
1. **Retire JSON-over-Postgres/IPC/N-API bar path (M3 Task 1):** Add `parquet`/`arrow-rs` to `apps/stock/engine/Cargo.toml`, store `(hash, manifest, parquet_paths)` in `backtest_datasets`, and lift single-series TS gates in `native-worker.ts`.
2. **Tier 1 Columnar Screener & CSCV PBO (`S = 16`):** Implement CSCV `PBO` and Purged Walk-Forward/CPCV in `libs/calculations`, plus vectorized Polars/DuckDB portfolio sweeps logging $M_{T \times N}$ matrices to `trial_ledger`.
3. **Tier 2 Rust `financial/` multi-asset upgrades & legacy retirement:** Implement atomic timestamp-slice marks (`F06`), simultaneous `Target` sell-netting, feature side-channel, `USD`/`CAD` Margin + corporate-action/delisting accounting (with all 6 M3 EC-1 fixtures), human Vault Holdout Gate workflow, and retirement of legacy `f64` `BacktestEngine`.

View file

@ -1,133 +0,0 @@
# Milestone M2 Gap Audit Report (T-203)
**Verdict:** **OPEN — M2 is not ready for closure.** Core M2 libraries (`curate-macro`, `send-ilp`, MCP server/adapters with Vault-fenced `query_data`, `fundamentalsAsOf`, QuestDB `10.2.0` primitives, and TS Feature Library) are present in the checked-out worktree and are programmer-reported green in the provisioned sandbox, but six concrete code/wiring gaps remain (including the missing desktop MCP entry point, unwired equity `1m` QuestDB consumer routing, and a `ceo_post` vs `post` event-kind mismatch). Traceable gate verification (with confirmed checkout SHA and retained logs) and all host-only `master` / `quant` / desktop closure gates remain **PENDING**.
> **Scope & Provenance Notes:**
> - Milestone and contract documents live under `design/` (`design/MILESTONES.md`, `design/DATA-CONTRACTS.md`, `design/PLATFORM-PLAN.md`), not `docs/`.
> - **Revision status:** Worktree `.git` metadata lives outside the sandbox boundary, so the exact base `master` SHA and `studio/auto-*` branches could not be inspected inside the sandbox. All local checks below ran against the checked-out worktree on branch `feat/m2-gap-audit` (`/home/boki/.studio/worktrees/stock-bot/slot-1`); authoritative `master` verification remains **PENDING** until the host confirms the `master` SHA.
> - Per settled director decision, **T-127** (M1 equity eligibility / Vault file isolation) stays deferred in the backlog and does not block M2.
> - Project CI is off; no CI workflows were planned, added, or modified.
---
## 1. Verification History & Worktree Gate Results
### 1.1 Earlier Planning-Phase Setup Failures (Recorded in Approved Plan)
During the initial read-only planning pass (unprovisioned environment before worktree dependencies and writable Cargo target were available), all four requested local gates and supplemental tests failed during setup:
| Gate / Suite | Command | Exit Code | Planning-Phase Outcome |
| --- | --- | --- | --- |
| Typecheck | `bun run typecheck` | `2` | **FAIL** — `TS2688` missing `bun-types` |
| Contracts | `bun run test:contracts` | `2` | **FAIL** — `TS2688` missing `bun-types` |
| Lint | `bun run lint:check` | `127` | **FAIL** — `eslint: command not found` |
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `101` | **FAIL** — `Read-only file system (os error 30)` creating Cargo target path |
| Supplemental M2 `bun test` | copilot server, stdio, snapshot exporter, DuckDB store, ILP writer | `1` | **FAIL** — missing `zod` and `@stock-bot/logger` during import setup |
### 1.2 Programmer-Reported Worktree Sandbox Runs (Verification Pending)
Executed interactively in the provisioned worktree `/home/boki/.studio/worktrees/stock-bot/slot-1` (branch `feat/m2-gap-audit`, Linux sandbox, network disabled).
- **Tested checkout revision:** **Unavailable in sandbox** (worktree `.git` metadata lives outside the sandbox boundary).
- **Retained command log / run reference:** **None** (ephemeral sandbox terminal output only).
- **Verification status:** **PENDING.** Because neither a confirmed checkout SHA nor retained command logs/run IDs are available for these four gates and supplemental suites, the rows below are **programmer-reported** only and do not constitute verified passes on `master` or the audited revision.
| Gate / Suite | Command | Exit Code | Status (Programmer-Reported) |
| --- | --- | --- | --- |
| Typecheck | `bun run typecheck` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors reported |
| Contracts | `bun run test:contracts` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors reported |
| Lint | `bun run lint:check` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors, 0 warnings reported |
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PROGRAMMER-REPORTED (pending)** — `1,548` passed, `0` failed, `4` ignored across `57` suites |
| MCP `query_data` Vault Fence | `bun test libs/research/test/mcp-query-data.test.ts` | `0` | **PROGRAMMER-REPORTED (pending)** — `13` pass, `0` fail |
| Real-DuckDB M2 Fixtures | `bun test libs/data/duckdb/test/` | `0` | **PROGRAMMER-REPORTED (pending)** — `25` pass, `0` fail across `4` files; includes Exit 2 restatement fixture & `openResearchCopilotStore` |
| Research + QuestDB + Copilot Executor | `bun test libs/research/test/ libs/data/questdb/test/ libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts` | `0` | **PROGRAMMER-REPORTED (pending)** — `999` pass, `0` fail across `59` files |
| Exit 3 Split-Boundary Fixture | `CARGO_BUILD_JOBS=2 cargo test -p curate-etl --offline split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` | `0` | **PROGRAMMER-REPORTED (pending)** — `1` passed, `0` failed |
| Utils | `bun run test:utils` | `0` | **PROGRAMMER-REPORTED (pending)** — `32` pass, `0` fail across `3` files |
| Calculations | `bun run test:calculations` | `0` | **PROGRAMMER-REPORTED (pending)** — `144` pass, `0` fail across `12` files |
- **Prior Studio unsandboxed runs (review branch `feat/m2-gap-audit`):** Studio `build` (`#1589`, `#1591`) and `test` (`#1590`, `#1592`) passed on the review branch. These runs cover separate Studio `build` and `test` commands on the review branch—not the four individual requested gates (`typecheck`, `test:contracts`, `lint:check`, `test:native`)—and do not confirm the audited `master` revision.
- **Verification status:** **PENDING** host confirmation of the exact `master` SHA, retained logs for `CARGO_BUILD_JOBS=2 bun run check`, and the separate `test/postgres/` run (see Section 4.1).
---
## 2. Verified on `master` *(Source Inspection; Traceable Runtime Verification & Host `master` SHA Pending)*
- **PRESENT · MCP Copilot Libraries, Vault-Fenced `query_data` & Snapshot Exporter.**
- `libs/research/src/mcp/copilot-server.ts` exposes all six M2 tools (`search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`).
- `createQueryDataTool` (`libs/research/src/mcp/tools/query-data.ts`) enforces strict Vault fencing: its Zod schema omits `scope` and `vault_evaluation_only` (`.strict()` rejects them with zero store calls), calls `fenceVaultQueryBounds` before any `store.universe` or `store.bars` call (clamping `to`/`asOf` strictly below `vaultCutoffTs` and rejecting ranges starting at/after `vaultCutoffTs` with `VaultHoldoutFenceError`), always passes `scope: 'vault_fenced'`, and applies defense-in-depth row filtering dropping any row where `row.ts >= vaultCutoffTs || row.knownAt >= vaultCutoffTs` (lines 203–210).
- Boundary cases in `libs/research/test/mcp-query-data.test.ts` — rejecting `scope`/`vault_evaluation_only`/unknown keys (L303), rejecting ranges starting at/after `vaultCutoffTs` with `VaultHoldoutFenceError` (L342), clamping straddling `to`/`asOf` below cutoff (L359), dropping leaky post-cutoff `ts`/`knownAt` rows (L386), clamping universe date via `min(to, asOf)` (L508), and DuckDB microsecond-bound + `adj_factors` snapshot checks (L576) — are **programmer-reported passing** in the worktree (`13` pass, `0` fail; traceable verification & host `master` SHA pending).
- `libs/research/src/mcp/adapters/postgres-copilot.ts` (`createPostgresResearchCopilotServer`) wires the read-only Studio library reader, PostgreSQL findings/caveats, trial lookup, and exchange calendars.
- `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`, T-184) and `openResearchCopilotExecutor` (`libs/data/postgres/src/research-copilot-executor.ts`, T-189/T-200) are exported and programmer-reported passing in worktree unit tests (verification pending).
- `exportNotebookSnapshot` (`libs/research/src/notebook-snapshot.ts`) and its Node/Bun adapters (`libs/research/src/notebook-snapshot-node.ts`) implement the `marimo check` → static HTML export sequence.
- **PRESENT · `tools/curate-etl` CLI Subcommands.**
- `tools/curate-etl/src/cli.rs` and `tools/curate-etl/src/main.rs` wire `curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, `curate-fx-1d`, `curate-shorts`, `curate-events`, `curate-bars-1m`, `curate-fx-1m`, `curate-posts`, `curate-fundamentals`, `curate-macro`, and `send-ilp`.
- `curate-macro` (T-194/T-202) connects `run_curate_macro` to `curate_and_write_macro`; `send-ilp` (T-190) connects `run_send_ilp` to shard discovery and one TCP connection per shard. Both are programmer-reported passing in offline native tests in the worktree (verification pending).
- **PRESENT · Exit 2 (PIT Restatement) & Exit 3 (Split-Boundary) Fixtures.**
- `tools/curate-etl/src/fundamentals.rs` builds deduplicated 2D PIT snapshots and 4-quarter TTM with venue lag provenance.
- `libs/data/duckdb/test/duckdb-market-data-store.test.ts` contains the real-DuckDB `fundamentalsAsOf` restatement fixture proving a restated Q1 (`known_at > Q2`) never overwrites Q2 (programmer-reported passing in worktree; verification pending).
- `tools/curate-etl/src/run_curate_bars_1m_tests.rs` contains `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` with the `0.5%` threshold and negative controls (programmer-reported passing in worktree; verification pending).
- **PRESENT · QuestDB `10.2.0` Primitives & TS Feature Library.**
- `docker-compose.yml`, `docker-compose.dev.yml`, and `docker-compose.prod.yml` pin `questdb/questdb:10.2.0`.
- `libs/data/questdb/src/{schema,client,query-builder,ilp-v2-writer}.ts` provide monthly WAL DDL (`M2_INTRADAY_SCHEMAS`, `getM2IntradayDDL`), parameterized PGWire (`QuestDBClient.query`), `LATEST ON`, and the ILP v2 binary batch writer.
- `libs/research/src/feature-library.ts` implements `registerSignal`, `runFeatureBatch`, and Zstd Parquet writing for versioned DuckDB SQL features.
---
## 3. Remaining M2 Code Gaps
1. **FAIL · Desktop MCP Entry Point & Exit 1 Wiring**
- T-196 target `scripts/research-copilot-mcp.ts` and root `package.json` script `mcp:research-copilot` are absent.
- `runResearchCopilotStdioHost` (`libs/research/src/mcp/host/stdio-host.ts`) still requires caller-injected store/executor factories rather than a runnable default entrypoint.
- `apps/stock/web-api/src/` has no MCP/SSE route.
- Impact: Desktop Claude Code cannot yet launch the copilot end-to-end to satisfy M2 Exit Criterion 1.
2. **FAIL · `ceoPosts` Event-Kind & Output-Root Interoperability**
- `tools/curate-etl/src/parquet_posts.rs` emits `EVENT_KIND_POST = "post"`, whereas `libs/research/src/market-data-store.ts` (`EventKind`), `libs/research/src/market-data-store-duckdb.ts` (`EVENT_KINDS`), `libs/research/src/mcp/tools/event-study.ts`, and `python/stockbot/data.py` (`EventKind`) all expect `"ceo_post"`.
- `tools/curate-etl/src/run_curate_posts.rs` writes `<out_dir>/events/year=YYYY/part.parquet` and fails closed (`RunCuratePostsError::EventsDatasetExists`) if `<out_dir>/events` already has `year=*` partitions from `curate-events`, while the copilot store takes a single curated root.
- Impact: Published `ceoPosts` cannot be queried alongside filings and earnings through the DuckDB store or MCP `event_study` as shipped.
3. **PARTIAL · Fundamentals & Macro Contract Gaps**
- `build_fundamentals_rows` (`tools/curate-etl/src/fundamentals.rs`) links filings using listing/fiscal-class plus report-date or filing-window heuristics because sampled filings lack statement period, whereas `design/DATA-CONTRACTS.md` specifies a direct period-end join.
- `run_curate_fundamentals` (`tools/curate-etl/src/run_curate_fundamentals.rs`) takes one caller-prepared financials BSON dump and requires `listing_venues.tsv`, which `exportCurateInputs` (`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts`) does not emit. No physical `fundamentals_bitemporal` writer or `eodFinancialsOLD` backfill path exists.
- `createDuckDbMarketDataStore().macroAsOf` (`libs/research/src/market-data-store-duckdb.ts:2294`) still rejects with `MarketDataStoreNotImplementedError`, so curated `teData` Parquet (`macro/part.parquet`) has no DuckDB reader.
4. **PARTIAL · Intraday Operating Path**
- `run_curate_qm_bars_1m` (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`) is implemented as a library function but has no binary subcommand dispatch in `tools/curate-etl/src/{cli,main}.rs`.
- `curate-bars-1m` and `curate-fx-1m` operate in file-mode BSON only (no `--from-mongo` streaming).
- `tools/curate-etl/src/bars_1m.rs` applies fixed Eastern session tags (venue/date overrides exist in close validation, not curation), and loaders stamp caller-supplied `--known-at-micros` whose historical availability semantics must be defined before as-of studies.
5. **FAIL / PARTIAL · QuestDB Startup Wiring & Intraday Read Path (Equity `1m` + FX `1m`)**
- **Unwired equity `1m` consumer path:** No application entry point constructs `createRoutedMarketDataStore` (`libs/research/src/market-data-store-routed.ts`) with `createQuestDbIntradayBarsReader` (`libs/research/src/market-data-store-questdb.ts`). The documented copilot factory `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`) opens DuckDB alone (`openDuckDbMarketDataStore`), which rejects `timeframe: '1m'` queries with `MarketDataStoreNotImplementedError` before reaching QuestDB.
- **Unwired FX `1m` route:** Even when `createRoutedMarketDataStore` is constructed, `fx()` delegates to the daily store rather than QuestDB `fx_1m`.
- **Startup DDL & legacy writer:** `getM2IntradayDDL` (`libs/data/questdb/src/schema.ts:139`) is opt-in with no checked-in startup caller applying it, and `QuestDBClient` (`libs/data/questdb/src/client.ts:232`) still instantiates legacy `QuestDBInfluxWriter` (`libs/data/questdb/src/influx-writer.ts`).
- **Schema wording drift:** `M2_INTRADAY_SCHEMAS.fx_1m` matches `design/DATA-CONTRACTS.md` (`DEDUP UPSERT KEYS(ts, pair)`), while `design/MILESTONES.md:96` wording can be read as `(ts, listing_id)` for both `bars_1m` and `fx_1m`.
6. **PARTIAL · Feature Library & Documentation Drift**
- `python/stockbot/__init__.py` and `python/stockbot/signals.py` do not expose `register_signal(...)` (only TS `libs/research/src/feature-library.ts` has `registerSignal`).
- `createDuckDbMarketDataStore().crossSection` (`libs/research/src/market-data-store-duckdb.ts:2283`) still rejects with `MarketDataStoreNotImplementedError`.
- `tools/curate-etl/README.md` still describes landed `curate-fundamentals` and `curate-macro` CLI wiring as deferred/follow-up in older stage sections (e.g., lines 1697, 1744, 1752, 1836, 1859).
- `AGENTS.md` and `studio.config.json` still reference `docs/` paths instead of `design/`.
- `design/MILESTONES.md:97` labels the Feature Library `D04` reopened, whereas `design/PLATFORM-PLAN.md` assigns the `register_signal` promotion bridge to `D11`.
---
## 4. Manual Host-Only Closure Gates
These checks cannot run inside the sandbox and must be executed on the host / `quant` before closing M2:
1. **Host Git Revision, Unmerged Branches, Full Check Gate & PostgreSQL Safety Suite**
- Record the exact audited `master` SHA and inspect `studio/auto-*` branches for any unmerged M2 commits (in particular T-196 desktop MCP wiring).
- Run `CARGO_BUILD_JOBS=2 bun run check` outside the sandbox on the confirmed `master` revision (covers `audit:secrets`, `build`, `typecheck`, `test:contracts`, `test:tooling`, `test:utils`, `test:calculations`, `test:integration`, `test:native`, and `lint:check`) and retain the command output/log alongside the `master` SHA.
- Because `scripts/check.ts` (`bun run check`) does **not** invoke `test:postgres` or discover `test/postgres/`, run the fixture-backed PostgreSQL safety suite separately using `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` (against isolated `stock_bot_safety*`) and record its result and log alongside `bun run check`.
- Never mutate QA MongoDB (`localhost:27017/stock`) or QA PostgreSQL (`localhost:5432/trading_bot`).
2. **Desktop Claude Code End-to-End Verification (Exit 1)**
- After runnable MCP entry-point wiring lands, connect desktop Claude Code against the read-only Studio library (`~/repos/studio/catalog/quant/library/library.yml`) and isolated PostgreSQL.
- Exercise all six MCP tools: run a PIT fundamentals + alt-data signal study and an event study, verify actual `marimo check`-clean static HTML export, and retrieve the filed finding with its trial and artifact references.
3. **Live `quant` QuestDB `10.2.0` Preflight, Load & Latency Verification (Exit 3)**
- **Host & schema precheck:** Verify on `quant`: QuestDB `10.2.0` image, `vm.max_map_count >= 1048576`, container `ulimits.nofile = 1048576`, memory limits, and pre-created `PARTITION BY MONTH` WAL tables with documented dedup keys (`(ts, listing_id)` for `bars_1m`, `(ts, pair)` for `fx_1m`).
- **Small live preflight per shard type (before bulk load):** Because `tools/curate-etl/src/cli.rs:175` documents that ILP v2 binary double encoding over TCP on QuestDB `10.2.0` is still unverified live, send one small sample shard for each shard type (`bars_1m`, `bars_1m_qm`, `fx_1m`) via `send-ilp` first. Confirm committed row counts, decoded OHLCV/FX numeric values and timestamps, and healthy WAL state (`wal_tables()`) through PGWire before starting the bulk load.
- **Full bulk load & reconciliation:** Run `send-ilp` for `bars_1m`, `bars_1m_qm`, and `fx_1m`; reconcile source counts vs. QuestDB PGWire row counts and WAL state (TCP `send-ilp` success confirms socket delivery only, not committed rows), and verify overlapping EOD/QM bar dedup and repeat-load idempotency.
- **Split-boundary verification:** Compare `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split-boundary `bars_1m` session closes against independently sourced raw `bars_1d` closes (`<= 0.5%`).
- **Read latency benchmark & explicit scope:** Benchmark a pinned 1-year single-listing `1m` read (`adjustment: 'raw'`) at **`< 250 ms` warm / `< 1 s` cold** using the real PGWire-backed reader path: `QuestDBClient.query(sql, params)` (`libs/data/questdb/src/client.ts`) injected as `QuestDbQueryExecutor` into `createQuestDbIntradayBarsReader` (`libs/research/src/market-data-store-questdb.ts`), optionally composed via `createRoutedMarketDataStore({ daily, intraday })`. Record listing ID, date range, row count, elapsed times, and cache conditions. **Scope note:** Until equity `1m` routing is wired into `openResearchCopilotStore` and the desktop MCP entrypoint (Section 3, item 5), this benchmark measures the **standalone PGWire-backed reader path**, not a running copilot application; re-verify through the running application once consumer wiring lands.

View file

@ -1,127 +0,0 @@
# Milestone M2 Master Audit & Closure Plan (T-208)
**Bottom Line:** **HOLD M2 CLOSURE / HOLD M3 — Core M2 infrastructure is ~80% landed on current `master` (including `T-190` `send-ilp`, `T-205` `mcp:research-copilot`, `T-206` `curate-qm-bars-1m`, and `T-207` `curate-macro`), with 6 concrete code/wiring gaps and 1 host/`quant` verification gate remaining before M2 can close.**
All sandbox-runnable TypeScript, ESLint, contract, and Rust native gates passed on local fixtures (including loopback TCP, with zero external network or QA DB contact; `0` errors, `0` warnings; `1,563` Rust tests across `58` suites and `1,050` targeted M2 Bun tests across `65` files). Exit Criterion 2 (2D PIT Q1-after-Q2 restatement non-overwrite) is **Done** in both Rust and real-DuckDB TypeScript fixtures; Exit Criteria 1 and 3 remain **Partial** pending event-kind/glob alignment, `MarketDataStore` read-path completions (`macroAsOf`, `crossSection`, `fx('1m')`), Python `stockbot` M2 parity, `notebook:snapshot` CLI + E2E test, and operator-run host/`quant` QuestDB `10.2.0` verification.
> **Scope, Provenance & Constraints**
> - **Read-only, docs-only audit:** Only `design/m2-master-audit.md` and `design/README.md` are modified. Zero production code, schema, test, build config, or CI changes (project CI is off; zero CI workflows proposed).
> - **Audited `master` baseline vs. review branch:** Audited against `master` and `dev` at verified commit `d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52` (with accepted M1 `d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1` confirmed as an ancestor). The review branch is `feat/m2-audit` (prior review HEAD `efd73bda3b9937274be6a47663ac20010922cfbd`, superseded by this revision). When checking the audited baseline outside the sandbox, run `git rev-parse master` — not `git rev-parse HEAD` (which returns the `feat/m2-audit` documentation commit).
> - **Supersedes prior T-203/T-204 snapshots:** Unlike `design/m2-completion-audit.md` (T-204), current `master` (`d45014a1`) now includes `T-190` (`send-ilp`), `T-205` (`scripts/research-copilot-mcp.ts` + `"mcp:research-copilot"`), `T-206` (`curate-qm-bars-1m` CLI), and `T-207` (`curate-macro` CLI). Every status below was re-verified from current source files and test runs.
> - **Documentation path drift:** Canonical specs reside under `design/*.md`, while `AGENTS.md` (lines 43–48), `CLAUDE.md` (lines 3, 7–11), `README.md` (lines 7, 9, 11–13, 142, 264, 435), and `studio.config.json` (lines 46–54) still reference `docs/*.md`. Cleanup is queued in `m2-ec1-snapshot-cli-and-doc-paths`.
> - **Strict database safety:** Zero connections to QA MongoDB (`27017/stock`) or QA PostgreSQL (`5432/trading_bot`).
---
## 1. Baseline Verification: M1 (`d52aa20`), `T-127` & Option B Rust Architecture
| Baseline Item | Verified State on `master` | Impact on M2 |
| --- | --- | --- |
| **Accepted M1 (`d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1`)** | Landed and intact: security-master & research SQL schemas (`database/postgres/init/34-security-master.sql`, `35-security-master-exchange-seed.sql`, `36-trial-ledger.sql`, `37-research-findings.sql`), Rust Option B `--from-mongo` runners for all 6 M1 commands (`tools/curate-etl/src/run_mongo.rs:1-100`, `mongo_stream.rs`, `mongo_safety.rs`), and Python `stockbot` M1 SDK (`python/stockbot/{__init__,calculations,data,ledger,signals,vault}.py`). | Solid foundation; M2 builds directly on these schemas, adapters, and `ReadOnlyMongoClient`. |
| **`T-127` (Deferred M1 Equity Eligibility & Vault File Isolation)** | Explicitly accepted as deferred in backlog per settled director decision (`d52aa20`). | **Non-blocking for M2.** Does not block EC-1, EC-2, or EC-3. |
| **Settled Rust ETL / `data-pipeline` Decision (Option B)** | Confirmed in `design/data-pipeline/rust-migration-evaluation.md` (including `2026-11-30` Addendum §§A.1–A.4): keep `apps/stock/data-pipeline` in TypeScript (`42` files, `20,349` LOC) for security master Passes 1–6, TSV export, probes, and BullMQ/Hono; keep bulk curation in Rust `tools/curate-etl` (`mongodb = "=3.10.2"` sync `RawDocumentBuf` cursors). | M2's 6 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`) still lack `--from-mongo` wiring in `tools/curate-etl/src/mongo_stream.rs:53-62` (currently 8 M1 collections only). |
| **Post-T-204 Merges (`T-190`, `T-205`, `T-206`, `T-207`)** | All four verified landed: `T-190` `send-ilp` (`tools/curate-etl/src/{ilp_send,cli,main}.rs`), `T-205` desktop MCP stdio entrypoint (`scripts/research-copilot-mcp.ts`, `package.json:56`, `scripts/test/research-copilot-mcp.test.ts`), `T-206` `curate-qm-bars-1m` (`tools/curate-etl/src/{run_curate_qm_bars_1m,cli,main}.rs`), and `T-207` `curate-macro` (`tools/curate-etl/src/{run_curate_macro,cli,main}.rs`). | Removes the T-204 desktop-launch and `curate-qm-bars-1m` CLI blockers. |
---
## 2. Verification Gate Evidence & Research Governance
### 2.1 Sandbox Local Fixture Runs (Programmer-Reported on `feat/m2-audit`, Including Loopback TCP — Zero External Network or QA DB Contact)
| Gate / Suite | Command | Exit | Observed Outcome & Counts |
| --- | --- | :---: | --- |
| **Typecheck** | `bun run typecheck` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.check.json --noEmit`) |
| **Contracts** | `bun run test:contracts` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.contracts.json --noEmit`) |
| **Lint** | `bun run lint:check` | `0` | **PASS** — `0` errors, `0` warnings (`--max-warnings 0`) |
| **Utils** | `bun run test:utils` | `0` | **PASS** — `32` pass, `0` fail (`59` expects, `3` files) |
| **Calculations** | `bun run test:calculations` | `0` | **PASS** — `144` pass, `0` fail (`76,602` expects, `12` files) |
| **Native Rust** | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PASS** — `1,563` passed, `0` failed, `4` ignored across `58` suites (`engine` `150` passed + `curate-etl` unit & integration suites using local fixtures, including loopback TCP in `tools/curate-etl/tests/cli.rs:1787` for `send-ilp`, plus binary tests in `curate_qm_bars_1m.rs` and `curate_macro.rs`, `fundamentals_tests.rs`, `parquet_fundamentals_tests.rs`, and `run_curate_bars_1m_tests.rs`) |
| **Targeted M2 Suites** | `bun test scripts/test/research-copilot-mcp.test.ts scripts/test/security.test.ts libs/research/test/ libs/data/duckdb/test/ libs/data/questdb/test/ libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts` | `0` | **PASS** — `1,050` pass, `0` fail (`80,699` expects, `65` files; includes `7/7` pass in `scripts/test/research-copilot-mcp.test.ts`, real-DuckDB `fundamentalsAsOf` restatement suite, and MCP Vault-fence suite) |
| **Python SDK** | `python3 -m pytest python/tests` | `1` | **SKIPPED (env)** — `/usr/bin/python3: No module named pytest` in sandbox |
### 2.2 Audited Baseline, Studio Unsandboxed & Host-Only Verification Boundary
| Verification Layer | Command / Scope | Status | Notes |
| --- | --- | :---: | --- |
| **Audited `master` Baseline Check** | `git rev-parse master` / `git rev-parse dev` | **Verified (`d45014a1`)** | Reviewer verified `master` and `dev` both at `d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52` with accepted M1 (`d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1`) as an ancestor; `feat/m2-audit` review HEAD is tracked separately. |
| **Studio Unsandboxed Runner (Audit Revision)** | `bun run build` and `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | **Authoritative post-handoff** | Prior revision passed Studio build `#1621` and test run `#1622`; Studio re-runs authoritatively on this revision covering workspace build, `audit:secrets`, worktree-git tooling tests (`scripts/test/`), integration tests, and isolated `stock_bot_safety*` PostgreSQL suites unreachable inside the sandbox. |
| **Future Host M2 Closure Revision** | `git rev-parse master` (at M2 closure), `CARGO_BUILD_JOBS=2 bun run check`, `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` | **PENDING (host closure)** | Future closure commit after M2 code tasks merge; required with retained logs in `design/m2-close-evidence.md` before M2 closure. |
| **`quant` (`10.0.0.51`) & Workstation Live Gates** | Read-only QA Mongo M2 field-shape probe, Quant Research-approved `curate-macro` `--series-map`, QuestDB `10.2.0` preflight (`vm.max_map_count`, `nofile`), bulk 3-feed intraday load + read-back reconciliation (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX`), `0x10` TCP ILP v2 commit, observed `NEXM.V`/`NVDA.US` split check, 1y `1m` PGWire latency, and desktop Claude Code + real `marimo` EC-1 receipt | **PENDING (host/`quant`)** | Tracked in `m2-host-quant-verification-and-closure` (with director replan flag in §4–§5). |
### 2.3 Research Governance & Replay / Financial Invariants Verified
- **Economic owner & durable inputs:** Quant data curation owns immutable Zstd Parquet partitions (`bars_1d`, `adj_factors`, `corporate_actions`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`, `macro`, `features/<name>/v<version>`) and published QuestDB ILP v2 shard files; Quant Research owns the `curate-macro` `--series-map` series and lag-class selections (the approved TSV and its identifier must be retained with macro curation evidence); PostgreSQL owns append-only `trial_ledger`, `vault_evaluations`, `findings`, and `provider_caveats` (`database/postgres/init/36-trial-ledger.sql`, `37-research-findings.sql`, protected by `reject_research_evidence_mutation()`).
- **Holdout Vault & `known_at` boundaries:** Verified by `libs/research/test/mcp-query-data.test.ts` (rejects `scope`/`vault_evaluation_only`, clamps bounds strictly `< vaultCutoffTs`, drops leaky post-cutoff rows) and `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:40`, hardcoding `vaultOperatorAuthorized: false`). **Open FX `1m` availability gap:** `tools/curate-etl/src/run_curate_fx_1m.rs:24-26` preserves bar-start `ts` and `libs/data/questdb/src/schema.ts:33-47` defines `fx_1m` without `known_at`, so filtering on `ts` alone can leak an unclosed bar's close across a cutoff (director confirmation required in §4).
- **Baselines & single-source metrics:** `@stock-bot/calculations` (`144/144` tests passing) remains the sole authority for Sharpe/Sortino/IC/Newey-West/DSR/event-study/recency math; `RET_1D_V1` in `libs/research/src/feature-library.ts:29` documents its zero-return comparison baseline and zero-cost assumption.
- **2D PIT restatement & synthetic split-boundary conservation:**
- Q1 restated after Q2 never overwrites Q2 and updates TTM: verified in Rust (`tools/curate-etl/src/fundamentals_tests.rs:104` `restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2`, `parquet_fundamentals_tests.rs:1107` `restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`).
- `NVDA.US` (`10:1`) and `NEXM.V` (`1:20`) split-unadjustment conservation within `0.5%`: verified on **synthetic** fixtures (`tools/curate-etl/src/run_curate_bars_1m_tests.rs:402` `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`); observed comparison against retained raw `bars_1d` closes remains open on `quant`.
- **Database safety & execution boundary:** Read-only MongoDB/PostgreSQL guards (`assertEnvironmentSafety()`, `MongoDBClient` `mongoReadOnly: true`, Rust `mongo_safety.rs` + sealed `ReadOnlyMongoClient`) remain intact. **Paper and live execution write access is strictly absent from all M2 MCP/research surfaces and remains out of scope until M5.**
---
## 3. Milestone M2 Deliverables & Exit Criteria Matrix
### 3.1 Deliverables (`design/MILESTONES.md` lines 87–98)
| Deliverable | Status | Landed on `master` (Exact Paths, Symbols & Tests) | Missing / Remaining Gaps |
| --- | :---: | --- | --- |
| **M2.1** MCP Server & Notebook Snapshots | **Partial** | - **T-205 landed:** Runnable stdio entrypoint `runResearchCopilotMcp` in `scripts/research-copilot-mcp.ts:77`, `"mcp:research-copilot"` in `package.json:56`, `7/7` tests in `scripts/test/research-copilot-mcp.test.ts`.<br>- All 6 MCP tools (`search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`) in `libs/research/src/mcp/tools/` + `createResearchCopilotMcpServer` (`libs/research/src/mcp/copilot-server.ts`) + `parseResearchCopilotHostConfig` / `runResearchCopilotStdioHost` (`libs/research/src/mcp/host/stdio-host.ts`).<br>- Real Postgres executor (`openResearchCopilotExecutor` in `libs/data/postgres/src/research-copilot-executor.ts`) + real DuckDB store (`openResearchCopilotStore` in `libs/data/duckdb/src/research-copilot-store.ts:33`) + read-only `library.yml` card reader (`libs/research/src/mcp/adapters/library-cards.ts`) + `database/postgres/init/37-research-findings.sql`.<br>- `exportNotebookSnapshot` & Node subprocess adapter (`libs/research/src/notebook-snapshot.ts`, `libs/research/src/notebook-snapshot-node.ts:67`, `libs/research/test/notebook-snapshot*.test.ts`). | 1. `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:37`) and `stdio-host.ts:49-79` open DuckDB-only; optional `RESEARCH_MCP_QUESTDB_*` config + `createRoutedMarketDataStore` composition is missing.<br>2. `analyze_signal` (`libs/research/src/mcp/tools/analyze-signal.ts:121-123`) supports only `source: 'shorts' \| 'fundamentals'` (no `source: 'feature'` for versioned Feature Library signals).<br>3. No runnable `scripts/export-notebook-snapshot.ts` / `"notebook:snapshot"` CLI wrapping `@stock-bot/research/notebook-snapshot-node`.<br>4. No automated E2E stdio test covering `search_symbols` → `query_data` → `analyze_signal` → `event_study` (with `ceo_post`) → `exportNotebookSnapshot` → `file_finding` → `read_knowledge`.<br>5. No `apps/stock/web-api` SSE wrapper (recommended deferred to M4; see §4). |
| **M2.2** PIT Fundamentals, `ceoPosts` & Lagged `teData` | **Partial** | - File-mode Rust CLIs wired in `tools/curate-etl/src/cli.rs` & `main.rs`: `curate-fundamentals` (`cli.rs:102,1636`, `run_curate_fundamentals.rs`), `curate-posts` (`cli.rs:101,1317`, `run_curate_posts.rs`), and **T-207** `curate-macro` (`cli.rs:103,1689`, `run_curate_macro.rs`; binary tests in `tools/curate-etl/tests/curate_macro.rs:178` `cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage`, `:471` `cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel`, `:709` `cli_rerun_on_same_inputs_is_byte_deterministic`).<br>- Real-DuckDB `fundamentalsAsOf` (`libs/research/src/market-data-store-duckdb.ts:2287`, `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`).<br>- 2D PIT restatement tests (`fundamentals_tests.rs:104`, `parquet_fundamentals_tests.rs:1107`). | 1. **`ceoPosts` event-kind & partition mismatch:** `EVENT_KIND_POST = "post"` (`tools/curate-etl/src/parquet_posts.rs:22`) mismatches `'ceo_post'` expected by `market-data-store-duckdb.ts` and `python/stockbot/data.py:21`; `run_curate_posts.rs:133` fails with `EventsDatasetExists` when `<out>/events` exists from `curate-events`; both `market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` glob only `events/year=*/part.parquet` instead of `events/year=*/*.parquet`.<br>2. `MarketDataStore.macroAsOf` throws `MarketDataStoreNotImplementedError` (`libs/research/src/market-data-store-duckdb.ts:2294-2296`).<br>3. `CurateFundamentalsArgs` (`tools/curate-etl/src/run_curate_fundamentals.rs:113-118`) accepts only a single `--qm-financials` path (no `--qm-financials-old` merge or `--curate-inputs` resolution).<br>4. `export-curate-inputs.ts:20-24` does not emit `listing_venues.tsv` (`us_tsx` / `tsxv_cse`).<br>5. `SourceCollection` (`mongo_stream.rs:53-62`), `RAW_BSON_EXPORT_COLLECTIONS` (`export-raw-bson.ts:11-20`), and `FIELD_SHAPE_PROBE_COLLECTIONS` (`source-field-shapes.ts:8-17`) allowlist only the 8 M1 collections (missing `qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`).<br>6. `python/stockbot/data.py` lacks `fundamentals_as_of` and `macro_as_of`. |
| **M2.3** QuestDB `10.2.0` Intraday & `send-ilp` | **Partial** | - **T-190 landed:** `send-ilp` multi-socket TCP sender (`tools/curate-etl/src/ilp_send.rs`, `cli.rs:104,2461`, `main.rs:22`, `ilp_send_tests.rs`; binary tests in `tools/curate-etl/tests/cli.rs:1747` `send_ilp_cli_help_missing_flag_success_and_partial_error_routing`, `:1877` `send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage`, `:1939` `send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr`).<br>- **T-206 landed:** `curate-qm-bars-1m` CLI (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`, `cli.rs:99,2277`, `main.rs:39`; binary tests in `tools/curate-etl/tests/curate_qm_bars_1m.rs:336` `curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants`, `:527` `curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards`, `:622` `curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped`) alongside `curate-bars-1m` (`cli.rs:98,2110`) and `curate-fx-1m` (`cli.rs:100,2381`).<br>- QuestDB `10.2.0` query layer, ILP v2 writer, and opt-in `M2_INTRADAY_SCHEMAS` / `getM2IntradayDDL()` (`libs/data/questdb/src/schema.ts:13-63,139`, `libs/data/questdb/test/`).<br>- Vault-fenced QuestDB `bars('1m')` reader (`libs/research/src/market-data-store-questdb.ts`) + `createRoutedMarketDataStore` (`libs/research/src/market-data-store-routed.ts`).<br>- `docker-compose.quant.yml:30-45` (`nofile: 1048576`, `QDB_RAM_USAGE_LIMIT_BYTES=21474836480`, `mem_limit: 28g`). | 1. `fx({ timeframe: '1m' })` throws `MarketDataStoreNotImplementedError` in TS (`libs/research/src/market-data-store-duckdb.ts:1529-1534`, delegated unchanged by `market-data-store-routed.ts:184-186`) and `NotImplementedError` in Python (`python/stockbot/data.py:258-259`); `market-data-store-questdb.ts` reads `bars_1m` only (no `fx_1m` reader). Moreover, `run_curate_fx_1m.rs:24-26` preserves bar-start `ts` and `fx_1m` (`schema.ts:33-47`) has no `known_at` column, so Vault fencing for both FX adapters requires a confirmed bar-close availability rule (see §4).<br>2. `getM2IntradayDDL()` (`libs/data/questdb/src/schema.ts:139`) is pure/opt-in with no runnable initializer script/helper wired to apply it.<br>3. No `--from-mongo` streaming in `mongo_stream.rs` / `run_mongo.rs` (and no allowlist entries in `export-raw-bson.ts` / `source-field-shapes.ts`) for `eodIntraday1M` (`3.40B`) or `qmIntraday` (`173.3M`).<br>4. Live `quant` preflight (`vm.max_map_count`, `nofile`), `0x10` binary-double TCP ILP acceptance (`ilp_send.rs:15-21`), bulk load & PGWire read-back reconciliation of all three approved feeds (`eodIntraday1M` US 2003–2025, `qmIntraday` CA/US 2024–2025, `CAD.FOREX` `1m` ~5.2M bars, including EOD/QM `(ts, listing_id)` overlap reconciliation), observed `NEXM.V`/`NVDA.US` split check, and 1y `1m` PGWire latency benchmark are unverified. |
| **M2.4** Versioned Feature Library (`D04` / `D11`) | **Partial** | - Declarative DuckDB SQL feature definitions, immutable `registerSignal`, Vault-fenced yearly Zstd Parquet `runFeatureBatch`, and built-in `RET_1D_V1` in `libs/research/src/feature-library.ts` (`libs/research/test/feature-library.test.ts`). | 1. `MarketDataStore.crossSection` throws `MarketDataStoreNotImplementedError` (`libs/research/src/market-data-store-duckdb.ts:2283-2285`), blocking read-back of `features/<name>/v<version>/year=*/part.parquet`.<br>2. `FEATURE_INPUT_DATASETS` (`libs/research/src/feature-library.ts:61-68`) omits `'macro'` and `'corporate_actions'`.<br>3. Python `stockbot` (`python/stockbot/{__init__,data,signals}.py`) lacks `register_signal(...)`, batch feature materialization, and `cross_section(...)`. |
### 3.2 Exit Criteria (`design/MILESTONES.md` lines 100–103)
| Exit Criterion | Status | Verified Evidence & Remaining Work |
| --- | :---: | --- |
| **EC-1:** Desktop Claude Code via MCP executes a fundamental + alt-data signal study and event study end-to-end, exports a `marimo check`-clean static HTML snapshot, and files a finding. | **Partial** | **Landed:** `scripts/research-copilot-mcp.ts` (`mcp:research-copilot`) + all 6 MCP tools + `exportNotebookSnapshot`.<br>**Missing:** `ceo_post` event compatibility (`m2-ceo-posts-events-compat`), `notebook:snapshot` CLI + automated E2E stdio test (`m2-ec1-snapshot-cli-and-doc-paths`), and desktop Claude Code + real `marimo` session receipt (`m2-host-quant-verification-and-closure`). |
| **EC-2:** Restatement fixture test proves a restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`. | **Done (Offline Rust + Real-DuckDB)** | Proven offline in `tools/curate-etl/src/fundamentals_tests.rs:104`, `tools/curate-etl/src/parquet_fundamentals_tests.rs:1107`, and real-DuckDB `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`. Python `fundamentals_as_of` parity is tracked in `m2-python-sdk-m2-parity`. |
| **EC-3:** Split-boundary test on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirms `bars_1m` session closes match raw `bars_1d` closes within `0.5%`, and 1y of `1m` bars for one listing loads in `< 250 ms` warm / `< 1 s` cold. | **Partial (Synthetic Done; Live `quant` Missing)** | **Done (synthetic):** `tools/curate-etl/src/run_curate_bars_1m_tests.rs:402` (`split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`).<br>**Missing (live `quant`):** Host/container `vm.max_map_count`/`nofile` preflight, `getM2IntradayDDL()` execution, QuestDB `10.2.0` `0x10` TCP ILP v2 commit check, bulk 3-feed load & PGWire read-back reconciliation (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX` + EOD/QM `(ts, listing_id)` overlap rule), observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` close check (`<= 0.5%`), and pinned 1-year single-listing PGWire latency benchmark (`< 250 ms` warm / `< 1 s` cold). |
---
## 4. Concrete Blockers, Director Trade-Offs & Backlog Replan Flags
Confirm these seven items (4 design trade-offs + 3 operational/environment prerequisites) and the **three backlog replan adjustments** below before coding/closing M2:
### 4.1 Design Trade-Offs Requiring Director Confirmation
1. **Option B `--from-mongo` for the 6 M2 collections vs. `.bson` staging:** Extend `tools/curate-etl` `SourceCollection` + `run_mongo.rs` with direct read-only MongoDB streaming for `qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, and `qmIntraday`, or stay on `.bson` staging files for M2?
- *Recommended:* Extend Option B `--from-mongo` to all 6 M2 collections (`m2-curate-etl-mongo-and-financials-old`) so `3.40B` `eodIntraday1M` rows never require `~500–832 GiB` of NVMe scratch space, while keeping file mode for offline tests.
2. **MCP stdio-only for M2 vs. `web-api` SSE wrapper:** Close M2 with the landed desktop stdio server (`bun run mcp:research-copilot`), or also add an HTTP/SSE wrapper inside `apps/stock/web-api` now?
- *Recommended:* Keep M2 stdio-only for desktop Claude Code (EC-1) and defer the network-isolated HTTP/SSE MCP endpoint to M4 containerized campaigns.
3. **`fundamentals_pit`-only vs. physical `fundamentals_bitemporal/part.parquet`:** Keep `curate-fundamentals` writing pre-resolved 2D PIT snapshots (`fundamentals_pit/year=YYYY/part.parquet`), or also materialize a separate raw `fundamentals_bitemporal/part.parquet` table in M2?
- *Recommended:* Keep `fundamentals_pit`-only for M2 (`DATA-CONTRACTS.md` §3A and EC-2 both target `fundamentalsAsOf` over `fundamentals_pit`), and materialize `fundamentals_bitemporal` only if a downstream M3/M4 use case requires unflattened multi-period history.
4. **`fx_1m` bar-close availability & Vault fencing rule *(Unresolved — blocks both TS & Python FX adapters)*:** `tools/curate-etl/src/run_curate_fx_1m.rs:24-26` preserves EODHD bar-start `ts` and `libs/data/questdb/src/schema.ts:33-47` defines `fx_1m` without a `known_at` column. Filtering on `ts` alone can return a bar whose start is before `vaultCutoffTs` (or `asOf`) while its close is at or after the cutoff, leaking an unobservable FX close.
- *Recommended:* Enforce bar-close availability in both TypeScript (`m2-store-macro-cross-section-fx1m`) and Python (`m2-python-sdk-m2-parity`) FX adapters (`bar_close = ts + 60s` strictly `< vaultCutoffTs` and `<= asOf`), backed by a boundary fixture proving a bar spanning or ending at `vaultCutoffTs` is excluded — keeping the `fx_1m` schema unchanged. (Alternative: add a `known_at` `TIMESTAMP` column to `fx_1m` DDL + ILP writer set to `ts + 60s`.)
### 4.2 Operational & Environment Prerequisites
5. **Live read-only QA MongoDB M2 field-shape probe & `curate-macro` `--series-map` ownership:** Run `probe-source-field-shapes.ts` read-only (`studio_stock_bot_read@stock`) once `m2-data-pipeline-m2-inputs-and-probes` allowlists the 6 M2 collections, to confirm live `ceoPosts` numeric timestamp unit (`Seconds` vs `Millis`), `qmFinancials`/`qmFinancials-old` metric paths, and `teData` labels before production curation. **Quant Research** owns the `teData` series selection and lag-class choices in the caller-supplied `--series-map` TSV; retain the approved mapping TSV and its version/hash identifier alongside the macro curation evidence in `design/m2-close-evidence.md`.
6. **`quant` (`10.0.0.51`) QuestDB `10.2.0` operator access:** Required for sysctl (`vm.max_map_count >= 1048576`) & container `nofile = 1048576` preflight, applying `getM2IntradayDDL()`, verifying `0x10` binary-double TCP ILP v2 commits via PGWire `wal_tables()`, loading and reconciling all three approved intraday feeds (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX`), running the observed `NEXM.V`/`NVDA.US` split check, and timing the 1-year `1m` PGWire latency gate.
7. **Workstation `marimo` + desktop Claude Code setup:** Required on the operator workstation with `bun run mcp:research-copilot`, Studio `library.yml`, real `marimo`, and isolated PostgreSQL to record the EC-1 sign-off receipt.
### 4.3 Substantive Backlog Replan Flags for Director (Before Merging Follow-Ups)
The approved 7-key implementation backlog has three gaps discovered during audit review that should be replanned within the existing keys before scheduling:
- **`m2-store-macro-cross-section-fx1m` & `m2-python-sdk-m2-parity` (FX `1m` availability boundary):** Add the confirmed `fx_1m` bar-close availability rule (item 4 above) and a boundary fixture in both TS and Python tests verifying bar-close observability and Vault exclusion for a minute bar spanning or ending at `vaultCutoffTs`.
- **`m2-ec1-snapshot-cli-and-doc-paths` (missing prerequisite):** Add `m2-ceo-posts-events-compat` to `dependsOn` (currently only `m2-store-macro-cross-section-fx1m`). Without it, the EC-1 integration task can start before `curate-posts` emits `'ceo_post'` and co-publishes alongside `curate-events`; require the E2E stdio test to consume co-published `curate-events` + `curate-posts` fixture output so `event_study` proves it reaches the curated CEO post.
- **`m2-host-quant-verification-and-closure` (bulk 3-feed intraday coverage & reconciliation):** Add acceptance requiring retained bulk load and PGWire read-back evidence in QuestDB for all three approved feeds from `design/MILESTONES.md:96` — `eodIntraday1M` (US equity 2003–2025), `qmIntraday` (CA/US equity 2024–2025), and `CAD.FOREX` `1m` (~5.2M bars) — recording source/date coverage, row counts, skipped/dropped counts, and the explicit reconciliation/precedence rule where EOD and QM share a `(ts, listing_id)` dedup key in `bars_1m`.
---
## 5. Ordered M2 Closure Backlog (7 Tasks)
Aligned 1-to-1 with the approved implementation backlog keys (with the three director replan flags marked inline):
| Order | Key | Task | Depends On | Primary Acceptance |
| :---: | --- | --- | --- | --- |
| **1** | `m2-ceo-posts-events-compat` | **M2.2u** — Fix `ceoPosts` event kind (`'ceo_post'`) and co-publish under `<curatedRoot>/events` | *(none)* | `EVENT_KIND_POST = "ceo_post"`; non-clobbering `events/year=YYYY/part-posts.parquet`; TS (`market-data-store-duckdb.ts`) & Python (`data.py`) glob `events/year=*/*.parquet` verified in real-DuckDB combined filing/earnings/`ceo_post` test. |
| **2** | `m2-store-macro-cross-section-fx1m` | **M2.3s** — Implement `MarketDataStore.macroAsOf`, `crossSection`, QuestDB `fx('1m')`, and copilot `1m` routing | *(none)* | Vault-fenced DuckDB `macroAsOf` & `crossSection` tests; QuestDB `fx_1m` reader + `createRoutedMarketDataStore` `fx('1m')` routing + `getM2IntradayDDL()` initializer; optional `RESEARCH_MCP_QUESTDB_*` in `stdio-host.ts`/`openResearchCopilotStore`; `analyze_signal` `source: 'feature'` + `FEATURE_INPUT_DATASETS` (`'macro'`, `'corporate_actions'`). **[Director replan §4.3: confirm `fx_1m` bar-close availability rule + add cutoff-spanning/ending boundary fixture.]** |
| **3** | `m2-data-pipeline-m2-inputs-and-probes` | **M2.2v** — Export `listing_venues.tsv` and extend field-shape probe & BSON fixture exporter for M2 collections | *(none)* | Atomic `listing_venues.tsv` (`us_tsx` / `tsxv_cse`) in `export-curate-inputs.ts`; all 14 M1+M2 collections allowlisted in `source-field-shapes.ts` & `export-raw-bson.ts` with `mongoReadOnly: true`. |
| **4** | `m2-curate-etl-mongo-and-financials-old` | **M2.3t** — Add `--qm-financials-old` merge and Option B `--from-mongo` streaming for M2 collections in `curate-etl` | `m2-ceo-posts-events-compat`, `m2-data-pipeline-m2-inputs-and-probes` | `curate-fundamentals` `--qm-financials-old` + `--curate-inputs`; sealed read-only `--from-mongo` streaming for all 6 M2 collections with byte-identical offline parity tests and zero new crates. |
| **5** | `m2-python-sdk-m2-parity` | **M2.4b** — Add Python `stockbot` `register_signal`, batch feature runner, and M2 `MarketDataStore` methods | `m2-ceo-posts-events-compat`, `m2-store-macro-cross-section-fx1m` | Vault-fenced `fundamentals_as_of`, `macro_as_of`, `cross_section`, optional QuestDB `1m` `bars`/`fx`, and `register_signal(...)` writing contract Zstd Parquet readable identically by TS and Python. **[Director replan §4.3: enforce confirmed `fx_1m` bar-close availability rule + cutoff-spanning/ending boundary fixture.]** |
| **6** | `m2-ec1-snapshot-cli-and-doc-paths` | **M2.1w** — Add notebook snapshot CLI, MCP E2E study+snapshot+finding test, and fix `docs/` → `design/` path drift | `m2-store-macro-cross-section-fx1m`, **`m2-ceo-posts-events-compat` *(replan §4.3)*** | Fail-closed `scripts/export-notebook-snapshot.ts` (`"notebook:snapshot"`); E2E stdio MCP test (`search_symbols` → `file_finding` + snapshot) consuming **co-published `curate-events` + `curate-posts` fixture output** so `event_study` reaches the curated `ceo_post`; `docs/*.md` → `design/*.md` updated in `AGENTS.md`, `CLAUDE.md`, `README.md`, `studio.config.json`, `tools/curate-etl/README.md`. |
| **7** | `m2-host-quant-verification-and-closure` | **M2.5** — Execute host/`quant` M2 preflight, bulk 3-feed intraday load, observed split-boundary & latency checks, and desktop Claude Code EC-1 sign-off | `m2-curate-etl-mongo-and-financials-old`, `m2-python-sdk-m2-parity`, `m2-ec1-snapshot-cli-and-doc-paths` | Retained host `git rev-parse master`, `CARGO_BUILD_JOBS=2 bun run check` + `test/postgres/` + live read-only M2 probe + Quant Research-approved `curate-macro` `--series-map` TSV/ID + `quant` QuestDB `10.2.0` preflight/`0x10` ILP/observed `NEXM.V` & `NVDA.US` split/latency checks + desktop Claude Code EC-1 receipt in `design/m2-close-evidence.md`, marking M2 closed in `design/MILESTONES.md`. **[Director replan §4.3: require retained bulk load + PGWire read-back reconciliation for EOD equity, QM equity, and `CAD.FOREX` FX — source/date coverage, row counts, skips, and EOD/QM `(ts, listing_id)` overlap precedence rule.]** |

View file

@ -1,23 +0,0 @@
{
"name": "@stock-bot/duckdb",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "Server-side DuckDB executor and MarketDataStore wiring for curated Hive Parquet datasets",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"build": "tsc",
"test": "bun test"
},
"dependencies": {
"@duckdb/node-api": "^1.4.4-r.1",
"@stock-bot/research": "workspace:*"
},
"devDependencies": {
"@types/node": "^20.11.0"
}
}

View file

@ -1,276 +0,0 @@
/**
* Concrete server-side DuckDB executor and `MarketDataStore` wiring over
* curated Hive-partitioned Parquet datasets (`design/DATA-CONTRACTS.md` §3.A & §4).
*
* Uses `@duckdb/node-api` (native N-API bindings, works in both Bun and Node)
* while keeping `@stock-bot/research` browser-safe and dependency-free.
*/
import { copyFile, link, mkdir, mkdtemp, open, rm, type FileHandle } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DuckDBInstance, type DuckDBConnection, type DuckDBValue } from '@duckdb/node-api';
import type { MarketDataStore, TableCell, TableRow } from '@stock-bot/research/market-data-store';
import {
createDuckDbMarketDataStore,
type AdjFactorsArtifactPinner,
type DuckDbExecutor,
type DuckDbMarketDataStoreOptions,
type DuckDbParam,
type PinnedAdjFactorsArtifact,
} from '@stock-bot/research/market-data-store-duckdb';
const UTF8_DECODER = new TextDecoder('utf-8', { fatal: false });
const MS_PER_DAY = 86_400_000;
export interface CreateNodeDuckDbExecutorOptions {
/** Optional DuckDB file path; defaults to `':memory:'` for read-only Parquet scans. */
readonly databasePath?: string;
}
export interface ClosableDuckDbExecutor extends DuckDbExecutor {
close(): Promise<void>;
}
export interface OpenDuckDbMarketDataStoreOptions
extends Omit<DuckDbMarketDataStoreOptions, 'executor'> {
/** Optional DuckDB database path; defaults to `':memory:'`. */
readonly databasePath?: string;
}
export interface OpenedDuckDbMarketDataStore {
readonly store: MarketDataStore;
readonly executor: ClosableDuckDbExecutor;
close(): Promise<void>;
}
function formatEpochDaysIso(days: number): string {
const date = new Date(days * MS_PER_DAY);
const y = String(date.getUTCFullYear()).padStart(4, '0');
const m = String(date.getUTCMonth() + 1).padStart(2, '0');
const d = String(date.getUTCDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object';
}
/**
* Normalizes a `@duckdb/node-api` cell value into `@stock-bot/research`'s
* strict `TableCell` (`string | number | boolean | null`) contract.
*/
export function normalizeDuckDbCell(value: unknown): TableCell {
if (value === null || value === undefined) {
return null;
}
if (typeof value === 'string' || typeof value === 'boolean') {
return value;
}
if (typeof value === 'number') {
return Object.is(value, -0) ? 0 : value;
}
if (typeof value === 'bigint') {
const asNumber = Number(value);
if (!Number.isSafeInteger(asNumber)) {
throw new RangeError(
`DuckDB BIGINT value ${value.toString()} exceeds JavaScript safe integer range.`
);
}
return asNumber;
}
if (value instanceof Uint8Array) {
return UTF8_DECODER.decode(value);
}
if (value instanceof Date) {
return value.getTime();
}
if (isRecord(value)) {
// DuckDBBlobValue / DuckDBBitValue expose `{ bytes: Uint8Array }` (e.g. parquet_kv_metadata)
if (value.bytes instanceof Uint8Array) {
return UTF8_DECODER.decode(value.bytes);
}
// DuckDBDateValue exposes `{ days: number }`
if (typeof value.days === 'number' && Number.isFinite(value.days)) {
return formatEpochDaysIso(value.days);
}
// DuckDBTimestampValue / DuckDBTimestampTZValue expose `{ micros: bigint }`
if (typeof value.micros === 'bigint') {
const ms = Number(value.micros / 1000n);
if (!Number.isSafeInteger(ms)) {
throw new RangeError(
`DuckDB timestamp micros ${value.micros.toString()} exceeds safe millisecond range.`
);
}
return ms;
}
// DuckDBDecimalValue exposes `{ value: bigint, scale: number }`
if (typeof value.value === 'bigint' && typeof value.scale === 'number') {
return Number(value.value) / 10 ** value.scale;
}
}
return String(value);
}
/**
* Opens an in-process `@duckdb/node-api` connection and adapts it to
* {@link DuckDbExecutor}.
*/
export async function createNodeDuckDbExecutor(
options: CreateNodeDuckDbExecutorOptions = {}
): Promise<ClosableDuckDbExecutor> {
const databasePath = options.databasePath ?? ':memory:';
const instance = await DuckDBInstance.create(databasePath);
let connection: DuckDBConnection;
try {
connection = await instance.connect();
} catch (err) {
instance.closeSync();
throw err;
}
let closed = false;
const assertOpen = (): void => {
if (closed) {
throw new Error('DuckDbExecutor connection has already been closed.');
}
};
return {
async run(sql: string): Promise<void> {
assertOpen();
await connection.run(sql);
},
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
assertOpen();
const values: DuckDBValue[] = params.map(param => param as DuckDBValue);
const reader =
values.length > 0
? await connection.runAndReadAll(sql, values)
: await connection.runAndReadAll(sql);
const rawRows = reader.getRowObjects();
const rows: TableRow[] = new Array(rawRows.length);
for (let i = 0; i < rawRows.length; i += 1) {
const raw = rawRows[i];
const clean: Record<string, TableCell> = {};
if (raw !== undefined) {
for (const [col, cell] of Object.entries(raw)) {
clean[col] = normalizeDuckDbCell(cell);
}
}
rows[i] = clean;
}
return rows;
},
async close(): Promise<void> {
if (closed) {
return;
}
closed = true;
connection.closeSync();
instance.closeSync();
},
};
}
/**
* Pins a mutable `<curatedRoot>/adj_factors/part.parquet` path to a single
* inode/snapshot across footer verification and factor scan so concurrent
* atomic replacements by `curate-etl` cannot introduce TOCTOU drift.
*
* On Linux, opens a read-only file descriptor and exposes `/proc/self/fd/<fd>`.
* On platforms without `/proc/self/fd`, falls back to a private hardlink (or
* copy across filesystems) inside a temporary directory cleaned up in `release()`.
*/
export function createFsAdjFactorsPinner(): AdjFactorsArtifactPinner {
return async (sourcePath: string): Promise<PinnedAdjFactorsArtifact> => {
if (process.platform === 'linux') {
const handle: FileHandle = await open(sourcePath, 'r');
let released = false;
return {
pinnedPath: `/proc/self/fd/${handle.fd}`,
async release(): Promise<void> {
if (released) {
return;
}
released = true;
await handle.close();
},
};
}
const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-adj-pin-'));
const pinnedPath = join(tempDir, 'adj_factors.parquet');
try {
await link(sourcePath, pinnedPath);
} catch {
await copyFile(sourcePath, pinnedPath);
}
let released = false;
return {
pinnedPath,
async release(): Promise<void> {
if (released) {
return;
}
released = true;
await rm(tempDir, { recursive: true, force: true });
},
};
};
}
/**
* Opens a ready-to-use DuckDB-backed {@link MarketDataStore} wired with
* `@duckdb/node-api` and a filesystem `adj_factors` artifact pinner.
*/
export async function openDuckDbMarketDataStore(
options: OpenDuckDbMarketDataStoreOptions
): Promise<OpenedDuckDbMarketDataStore> {
const tempDir = options.env?.STOCK_BOT_DUCKDB_TEMP_DIR;
if (typeof tempDir === 'string' && tempDir.trim().length > 0) {
await mkdir(tempDir, { recursive: true });
}
const executor = await createNodeDuckDbExecutor({
databasePath: options.databasePath,
});
const pinAdjFactorsArtifact =
options.pinAdjFactorsArtifact ??
(options.immutableAdjFactorsPath === undefined ? createFsAdjFactorsPinner() : undefined);
try {
const store = createDuckDbMarketDataStore({
...options,
executor,
...(pinAdjFactorsArtifact !== undefined ? { pinAdjFactorsArtifact } : {}),
});
return {
store,
executor,
async close(): Promise<void> {
await executor.close();
},
};
} catch (err) {
await executor.close();
throw err;
}
}
export {
createDuckDbMarketDataStore,
type AdjFactorsArtifactPinner,
type DuckDbExecutor,
type DuckDbMarketDataStoreOptions,
type DuckDbParam,
type PinnedAdjFactorsArtifact,
};
export {
openResearchCopilotStore,
type OpenResearchCopilotStoreOptions,
} from './research-copilot-store';

View file

@ -1,49 +0,0 @@
/**
* Real DuckDB `MarketDataStore` factory for the MCP research copilot stdio host
* (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`).
*
* - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff shared
* between the host and the underlying DuckDB store, and hardcodes
* `vaultOperatorAuthorized: false` so every query remains strictly
* `'vault_fenced'`.
* - Returns a {@link ManagedMarketDataStore} (`{ store, close }`) whose
* `close()` releases the underlying DuckDB connection and instance.
* - Any failure during open (native connection creation or store validation)
* releases already-acquired DuckDB resources before rejecting.
*/
import type {
ManagedMarketDataStore,
ResearchCopilotHostConfig,
ResearchCopilotStdioHostDeps,
} from '@stock-bot/research/mcp';
import { openDuckDbMarketDataStore } from './index';
export interface OpenResearchCopilotStoreOptions {
/** Optional DuckDB database path; defaults to `':memory:'`. */
readonly databasePath?: string;
/** Optional environment overrides for DuckDB connection budget (`STOCKBOT_DUCKDB_*`). */
readonly env?: Readonly<Record<string, string | undefined>>;
}
/**
* Opens a Vault-fenced DuckDB-backed {@link ManagedMarketDataStore} from a
* validated {@link ResearchCopilotHostConfig} for `ResearchCopilotStdioHostDeps.openStore`.
*/
export const openResearchCopilotStore = (async (
config: ResearchCopilotHostConfig,
options?: OpenResearchCopilotStoreOptions
): Promise<ManagedMarketDataStore> => {
const opened = await openDuckDbMarketDataStore({
curatedRoot: config.curatedRoot,
vaultCutoffTs: config.vaultCutoffTs,
vaultOperatorAuthorized: false,
...(options?.databasePath !== undefined ? { databasePath: options.databasePath } : {}),
...(options?.env !== undefined ? { env: options.env } : {}),
});
return {
store: opened.store,
close: opened.close,
};
}) satisfies ResearchCopilotStdioHostDeps['openStore'];

View file

@ -1,522 +0,0 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { MarketDataStore } from '@stock-bot/research/market-data-store';
import type { FundamentalsAsOfQuery } from '@stock-bot/research/market-data-store-duckdb';
import { createAnalyzeSignalTool, createMcpServer } from '@stock-bot/research/mcp';
import { type SignalObservation, buildForwardReturnPanel, collectBars } from '@stock-bot/research/signal-panel';
import { analyzeSignal } from '@stock-bot/research/signal-study';
import type { TrialLedgerExecutor } from '@stock-bot/research/trial-ledger';
import { createNodeDuckDbExecutor, openDuckDbMarketDataStore } from '../src/index';
// QA end-to-end evidence for T-149: MCP `analyze_signal` (source = fundamentals)
// driven against the REAL DuckDB `fundamentalsAsOf` over Hive Parquet files.
// - Dataset ID: `synthetic:qa-analyze-signal-fundamentals-real-duckdb:seed-20261206:v1`
// - Tool version: `mcp:analyze_signal:v1`; adjustment `raw`; horizon 3 sessions; modeled costs 0
// - Pre-Vault window 2023-03-01..2023-05-12; Vault cutoff 2023-05-15T00:00:00.000Z
// - Bars: 6 listings (101..106), 20:00 UTC closes; 5 post-cutoff bars must be fenced out.
// - Fundamentals (ttm_revenue), all 13:00 UTC:
// 2023-03-10 verified (101..105), 2023-04-05 verified Q2 (all),
// 2023-04-18 same-month restatement (101..103, verified),
// 2023-04-18 estimated-lag update (104) -> omitted by DuckDB under default lag,
// 2023-04-20 verified row with NULL ttm_revenue (105) -> must not displace 2023-04-05.
// - Baseline: direct `buildForwardReturnPanel` + `analyzeSignal` over independently listed
// expected observations.
const VAULT_CUTOFF_TS = Date.UTC(2023, 4, 15);
const VAULT_CUTOFF_DATE = '2023-05-15';
const PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
const LISTING_IDS = [101, 102, 103, 104, 105, 106] as const;
const HORIZON = 3;
// Listing with bars but no fundamentals rows at all (sparse coverage probe).
const UNCOVERED_LISTING_ID = 107;
const BAR_LISTING_IDS = [...LISTING_IDS, UNCOVERED_LISTING_ID] as const;
const tempDirs: string[] = [];
afterEach(async () => {
while (tempDirs.length > 0) {
const dir = tempDirs.pop();
if (dir !== undefined) {
await rm(dir, { recursive: true, force: true });
}
}
});
function createSeededRng(seed: number): () => number {
let s = seed >>> 0;
return () => {
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;
};
}
function businessDates(start: string, count: number): string[] {
const out: string[] = [];
const d = new Date(`${start}T00:00:00Z`);
while (out.length < count) {
const dow = d.getUTCDay();
if (dow !== 0 && dow !== 6) {
out.push(d.toISOString().slice(0, 10));
}
d.setUTCDate(d.getUTCDate() + 1);
}
return out;
}
function ms(date: string, hour: number): number {
return Date.parse(`${date}T${String(hour).padStart(2, '0')}:00:00.000Z`);
}
interface PitRow {
readonly listingId: number;
readonly knownAt: string; // YYYY-MM-DD
readonly hour?: number; // UTC hour, default 13
readonly ttm: number | null;
readonly estimated?: boolean;
}
const BASE_PIT_ROWS: readonly PitRow[] = [
...[101, 102, 103, 104, 105].map((lid, l) => ({
listingId: lid,
knownAt: '2023-03-10',
ttm: 200 + ((l * 3) % 5) * 25,
})),
...LISTING_IDS.map((lid, l) => ({ listingId: lid, knownAt: '2023-04-05', ttm: 100 + l * 40 })),
...[101, 102, 103].map((lid, l) => ({ listingId: lid, knownAt: '2023-04-18', ttm: 400 - l * 90 })),
{ listingId: 104, knownAt: '2023-04-18', ttm: 999, estimated: true },
{ listingId: 105, knownAt: '2023-04-20', ttm: null },
];
function pitRowSql(r: PitRow): string {
const est = r.estimated === true ? 'TRUE' : 'FALSE';
const ttm = r.ttm === null ? 'NULL::DOUBLE' : `${r.ttm}::DOUBLE`;
const ttmMeta =
r.ttm === null ? 'NULL::DATE, NULL::VARCHAR' : `DATE '2023-03-31', 'USD'::VARCHAR`;
const ts = `${r.knownAt} ${String(r.hour ?? 13).padStart(2, '0')}:00:00+00`;
return `(${r.listingId}::INTEGER, TIMESTAMPTZ '${ts}', 'filing_date'::VARCHAR, ${est}::BOOLEAN,
DATE '2023-03-31', 'Q1'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${ts}',
1.0::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE,
${ttmMeta}, ${ttm}, NULL::DOUBLE, NULL::DOUBLE, ${est}::BOOLEAN)`;
}
async function writeCurated(
curatedRoot: string,
pitPartitions: Readonly<Record<string, readonly PitRow[]>>
): Promise<void> {
const rand = createSeededRng(20261206);
const dates = businessDates('2023-03-01', 58); // 53 pre-cutoff + 5 Vault sessions
const prices = BAR_LISTING_IDS.map(() => 40);
const barValues: string[] = [];
for (const date of dates) {
for (let l = 0; l < BAR_LISTING_IDS.length; l += 1) {
const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009;
prices[l] = Math.max(1, prices[l]! * (1 + ret));
const close = Number(prices[l]!.toFixed(6));
const ts = `TIMESTAMPTZ '${date} 20:00:00+00'`;
barValues.push(
`(${BAR_LISTING_IDS[l]}::INTEGER, DATE '${date}', ${ts}, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, 50000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, ${ts})`
);
}
}
await mkdir(join(curatedRoot, 'bars_1d', 'year=2023'), { recursive: true });
const writer = await createNodeDuckDbExecutor();
try {
await writer.run(`
COPY (
SELECT * FROM (VALUES ${barValues.join(', ')})
AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
) TO '${join(curatedRoot, 'bars_1d', 'year=2023', 'part.parquet')}' (FORMAT PARQUET)
`);
for (const [year, rows] of Object.entries(pitPartitions)) {
const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`);
await mkdir(dir, { recursive: true });
await writer.run(`
COPY (
SELECT * FROM (VALUES ${rows.map(pitRowSql).join(', ')}) AS t(
listing_id, effective_known_at, known_at_source, has_estimated_lag,
period_end, fiscal_period, currency, period_known_at,
revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding,
ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag
)
) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET)
`);
}
} finally {
await writer.close();
}
}
interface LedgerRow {
readonly trial_id: string;
readonly created_at: Date;
readonly principal_id: string;
readonly campaign_id: string | null;
readonly stage: string;
readonly universe_market: string;
readonly horizon_bucket: string;
readonly hypothesis_id: string | null;
readonly expression_hash: string;
readonly sample_start: string;
readonly sample_end: string;
readonly n_obs: number;
readonly sharpe_unann: number;
readonly skewness: number;
readonly kurtosis: number;
readonly daily_series: number[];
}
// Deterministic in-memory trial_ledger port (fixed created_at, sequential ids).
function createLedger(): { executor: TrialLedgerExecutor; rows: LedgerRow[] } {
const rows: LedgerRow[] = [];
let nextId = 1;
const executor: TrialLedgerExecutor = {
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
const p = params ?? [];
const trimmed = text.trimStart();
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
const id = nextId++;
const row: LedgerRow = {
trial_id: String(id),
created_at: new Date(Date.UTC(2024, 0, 1, 0, 0, id)),
principal_id: p[0] as string,
campaign_id: (p[1] as string | null) ?? null,
stage: p[2] as string,
universe_market: p[3] as string,
horizon_bucket: p[4] as string,
hypothesis_id: (p[5] as string | null) ?? null,
expression_hash: p[6] as string,
sample_start: p[7] as string,
sample_end: p[8] as string,
n_obs: p[9] as number,
sharpe_unann: p[10] as number,
skewness: p[11] as number,
kurtosis: p[12] as number,
daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)),
};
rows.push(row);
return {
rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row],
rowCount: 1,
};
}
if (trimmed.startsWith('SELECT')) {
if (text.includes('WHERE trial_id = $1::bigint')) {
const matched = rows.filter(r => r.trial_id === String(p[0]));
return { rows: matched as unknown as Row[], rowCount: matched.length };
}
if (text.includes('WHERE universe_market = $1')) {
const matched = rows.filter(
r => r.universe_market === p[0] && r.horizon_bucket === p[1]
);
return { rows: matched as unknown as Row[], rowCount: matched.length };
}
}
return { rows: [], rowCount: 0 };
},
};
return { executor, rows };
}
async function openStore(
pitPartitions: Readonly<Record<string, readonly PitRow[]>>
): Promise<{
store: MarketDataStore;
calls: FundamentalsAsOfQuery[];
close: () => Promise<void>;
}> {
const root = await mkdtemp(join(tmpdir(), 'stockbot-qa-as-fnd-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(duckTempDir, { recursive: true });
await writeCurated(curatedRoot, pitPartitions);
const opened = await openDuckDbMarketDataStore({
curatedRoot,
vaultCutoffTs: VAULT_CUTOFF_TS,
env: {
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '1GB',
STOCK_BOT_DUCKDB_THREADS: '2',
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
},
});
const calls: FundamentalsAsOfQuery[] = [];
const inner = opened.store;
const store: MarketDataStore = {
...inner,
bars: q => inner.bars(q),
shortsAsOf: q => inner.shortsAsOf(q),
universe: q => inner.universe(q),
fundamentalsAsOf: q => {
calls.push(q);
return inner.fundamentalsAsOf(q);
},
};
return { store, calls, close: () => opened.close() };
}
async function runTool(
store: MarketDataStore,
ledger: TrialLedgerExecutor,
allowEstimatedLag?: boolean,
listingIds: readonly number[] = LISTING_IDS
): Promise<{ isError: boolean; text: string }> {
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createAnalyzeSignalTool({
store,
ledger,
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
principalId: PRINCIPAL,
}),
],
});
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 'qa-1',
method: 'tools/call',
params: {
name: 'analyze_signal',
arguments: {
listingIds: [...listingIds],
from: '2023-03-01',
to: '2023-05-19', // straddles the Vault cutoff; must be clamped
signal: {
source: 'fundamentals',
field: 'ttm_revenue',
...(allowEstimatedLag === undefined ? {} : { allowEstimatedLag }),
},
horizonSessions: HORIZON,
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
},
},
})
);
const parsed = JSON.parse(raw as string) as {
result: { isError?: boolean; content: { text: string }[] };
};
return { isError: parsed.result.isError === true, text: parsed.result.content[0]?.text ?? '' };
}
function expectedObservations(
includeEstimated: boolean,
rows: readonly PitRow[] = BASE_PIT_ROWS
): SignalObservation[] {
const out: SignalObservation[] = [];
for (const r of rows) {
if (r.ttm === null || (r.estimated === true && !includeEstimated)) {
continue;
}
out.push({ listingId: r.listingId, knownAt: ms(r.knownAt, r.hour ?? 13), value: r.ttm });
}
return out;
}
async function directBaseline(
store: MarketDataStore,
signals: SignalObservation[],
listingIds: readonly number[] = LISTING_IDS
): Promise<{ rankIc: unknown; series: number[]; sampleStart: string; sampleEnd: string }> {
const bars = await collectBars(store.bars({
listingIds: [...listingIds],
from: '2023-03-01',
to: '2023-05-12',
timeframe: '1d',
adjustment: 'raw',
}));
const built = buildForwardReturnPanel({
bars,
signals,
horizonSessions: HORIZON,
vaultCutoffDate: VAULT_CUTOFF_DATE,
});
const ledger = createLedger();
const study = await analyzeSignal(ledger.executor, {
principalId: PRINCIPAL,
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
expression: {
expression: 'qa_direct_baseline',
params: { field: 'ttm_revenue' },
universe: [...listingIds],
horizon: `${HORIZON}d`,
},
panel: built.panel,
vaultCutoffDate: VAULT_CUTOFF_DATE,
});
if (study.status !== 'ok') {
throw new Error(`baseline study not ok: ${study.status}`);
}
return {
rankIc: study.analysis.rankIc,
series: ledger.rows[0]!.daily_series,
sampleStart: study.trial.sampleStart,
sampleEnd: study.trial.sampleEnd,
};
}
interface OkPayload {
status: 'ok';
signal: unknown;
analysis: { rankIc: unknown };
trial: { sampleStart: string; sampleEnd: string; expressionHash: string };
}
describe('analyze_signal fundamentals over real DuckDB fundamentalsAsOf (QA)', () => {
test('default lag: same-month restatement, estimated-lag omission and null-field rows replay exactly like the verified-only baseline', async () => {
const s = await openStore({ '2023': BASE_PIT_ROWS });
try {
const ledger = createLedger();
const res = await runTool(s.store, ledger.executor);
expect(res.isError).toBe(false);
const payload = JSON.parse(res.text) as OkPayload;
expect(payload.status).toBe('ok');
expect(payload.signal).toEqual({
source: 'fundamentals',
field: 'ttm_revenue',
allowEstimatedLag: false,
});
const baseline = await directBaseline(s.store, expectedObservations(false));
expect(payload.analysis.rankIc).toEqual(baseline.rankIc);
expect(ledger.rows).toHaveLength(1);
expect(ledger.rows[0]!.daily_series).toEqual(baseline.series);
expect(payload.trial.sampleStart).toBe(baseline.sampleStart);
expect(payload.trial.sampleEnd).toBe(baseline.sampleEnd);
expect(payload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true);
// Every real-store read is strictly pre-Vault and forwards the lag flag verbatim.
expect(s.calls.length).toBeGreaterThan(0);
for (const call of s.calls) {
expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS);
expect(call.allowEstimatedLag).toBe(false);
expect(call.fields).toEqual(['ttm_revenue']);
}
// Fan-out bound: month-end snapshots (3) + at most one probe per eligible session (53).
expect(s.calls.length).toBeLessThanOrEqual(3 + 53);
} finally {
await s.close();
}
});
test('allowEstimatedLag true includes the estimated update and matches its own baseline', async () => {
const s = await openStore({ '2023': BASE_PIT_ROWS });
try {
const ledger = createLedger();
const res = await runTool(s.store, ledger.executor, true);
const payload = JSON.parse(res.text) as OkPayload;
expect(payload.status).toBe('ok');
const baseline = await directBaseline(s.store, expectedObservations(true));
expect(payload.analysis.rankIc).toEqual(baseline.rankIc);
expect(ledger.rows[0]!.daily_series).toEqual(baseline.series);
expect(s.calls.every(c => c.allowEstimatedLag === true)).toBe(true);
const defaultLedger = createLedger();
const defaultRes = await runTool(s.store, defaultLedger.executor);
const defaultPayload = JSON.parse(defaultRes.text) as OkPayload;
expect(defaultPayload.trial.expressionHash).not.toBe(payload.trial.expressionHash);
expect(defaultLedger.rows[0]!.daily_series).not.toEqual(ledger.rows[0]!.daily_series);
} finally {
await s.close();
}
});
test('appending Vault-window and post-cutoff revisions in another Parquet partition leaves payload and ledger rows byte-identical', async () => {
const clean = await openStore({ '2023': BASE_PIT_ROWS });
const poisoned = await openStore({
'2023': BASE_PIT_ROWS,
'2099': [
// Exactly at the Vault cutoff, inside the Vault, and long after.
...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-15', ttm: 5_000 + lid })),
...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-17', ttm: 7_000 - lid })),
...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2024-01-02', ttm: 9_000 + lid })),
],
});
try {
const cleanLedger = createLedger();
const poisonedLedger = createLedger();
const cleanRes = await runTool(clean.store, cleanLedger.executor);
const poisonedRes = await runTool(poisoned.store, poisonedLedger.executor);
expect(cleanRes.isError).toBe(false);
expect(poisonedRes.text).toBe(cleanRes.text);
expect(poisonedLedger.rows).toEqual(cleanLedger.rows);
expect(poisoned.calls.map(c => c.asOf)).toEqual(clean.calls.map(c => c.asOf));
} finally {
await clean.close();
await poisoned.close();
}
});
test('a release stamped exactly at a bar close and superseded next morning is replayed at that close', async () => {
// 106 files at 2023-04-12 20:00:00Z (== bar close ts) and restates at 2023-04-13 13:00Z.
// A month-end-only read would only see the 04-13 vintage; the 04-12 close must use 50.
const rows: readonly PitRow[] = [
...BASE_PIT_ROWS,
{ listingId: 106, knownAt: '2023-04-12', hour: 20, ttm: 50 },
{ listingId: 106, knownAt: '2023-04-13', ttm: 900 },
];
const s = await openStore({ '2023': rows });
try {
const ledger = createLedger();
const res = await runTool(s.store, ledger.executor);
const payload = JSON.parse(res.text) as OkPayload;
expect(payload.status).toBe('ok');
const baseline = await directBaseline(s.store, expectedObservations(false, rows));
expect(payload.analysis.rankIc).toEqual(baseline.rankIc);
expect(ledger.rows[0]!.daily_series).toEqual(baseline.series);
// Probe at the exact close timestamp is issued (store compares effective_known_at <= asOf).
expect(s.calls.some(c => Date.parse(c.asOf) === ms('2023-04-12', 20))).toBe(true);
} finally {
await s.close();
}
});
test('sparse coverage: a listing with bars but no fundamentals stays bounded and does not change the study', async () => {
// Measurement for the reviewer's non-blocking fan-out note. The uncovered listing is
// probed at each eligible session, so calls grow with sessions, not with listings.
const covered = await openStore({ '2023': BASE_PIT_ROWS });
const sparse = await openStore({ '2023': BASE_PIT_ROWS });
try {
const coveredLedger = createLedger();
const sparseLedger = createLedger();
const coveredRes = await runTool(covered.store, coveredLedger.executor);
const sparseRes = await runTool(sparse.store, sparseLedger.executor, undefined, [
...LISTING_IDS,
UNCOVERED_LISTING_ID,
]);
const coveredPayload = JSON.parse(coveredRes.text) as OkPayload;
const sparsePayload = JSON.parse(sparseRes.text) as OkPayload;
expect(coveredPayload.status).toBe('ok');
expect(sparsePayload.status).toBe('ok');
// No signal for 107 -> same cross-sectional series as the covered-only study.
const baseline = await directBaseline(sparse.store, expectedObservations(false), [
...LISTING_IDS,
UNCOVERED_LISTING_ID,
]);
expect(sparseLedger.rows[0]!.daily_series).toEqual(baseline.series);
// 53 eligible sessions over 3 UTC months: <= 3 month-end snapshots + 53 probes.
expect(sparse.calls.length).toBeLessThanOrEqual(3 + 53);
expect(sparse.calls.length).toBeGreaterThan(covered.calls.length);
// Each session timestamp is probed at most once.
const asOfs = sparse.calls.map(c => c.asOf);
expect(new Set(asOfs).size).toBe(asOfs.length);
for (const call of sparse.calls) {
expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS);
}
} finally {
await covered.close();
await sparse.close();
}
});
});

View file

@ -1,931 +0,0 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
computeVaultCutoffTs,
VaultHoldoutFenceError,
type BarRecord,
} from '@stock-bot/research/market-data-store';
import {
createNodeDuckDbExecutor,
openDuckDbMarketDataStore,
} from '../src/index';
const tempDirs: string[] = [];
afterEach(async () => {
while (tempDirs.length > 0) {
const dir = tempDirs.pop();
if (dir !== undefined) {
await rm(dir, { recursive: true, force: true });
}
}
});
async function buildCuratedFixture(): Promise<{
curatedRoot: string;
duckTempDir: string;
vaultCutoffTs: number;
}> {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-mds-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(join(curatedRoot, 'bars_1d', 'year=2024'), { recursive: true });
await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true });
await mkdir(join(curatedRoot, 'adj_factors'), { recursive: true });
await mkdir(join(curatedRoot, 'events', 'year=2024'), { recursive: true });
await mkdir(join(curatedRoot, 'shorts'), { recursive: true });
await mkdir(join(curatedRoot, 'fx_1d'), { recursive: true });
await mkdir(duckTempDir, { recursive: true });
// Max ingested = 2025-08-13 -> Vault cutoff = 2025-02-13T00:00:00.000Z
const vaultCutoffTs = computeVaultCutoffTs('2025-08-13');
const vaultCutoffMicros = vaultCutoffTs * 1000;
const asOfMicros = vaultCutoffMicros - 1;
const writer = await createNodeDuckDbExecutor();
try {
// 2024 bars (pre-Vault): listing 101 (USD, NVDA 10:1 split on 2024-06-10) + listing 202 (CAD)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, DATE '2024-06-07', TIMESTAMPTZ '2024-06-07 20:00:00+00', 1200.0::DOUBLE, 1220.0::DOUBLE, 1190.0::DOUBLE, 1208.88::DOUBLE, 41238600.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-07 20:00:00+00'),
(101::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 120.37::DOUBLE, 123.10::DOUBLE, 117.01::DOUBLE, 121.79::DOUBLE, 314162700.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00'),
(202::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 140.0::DOUBLE, 142.0::DOUBLE, 139.0::DOUBLE, 141.5::DOUBLE, 1200000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00')
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
) TO '${join(curatedRoot, 'bars_1d', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
`);
// 2025 bars: one pre-Vault bar (2025-02-12) and one Vault bar (2025-02-14)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, DATE '2025-02-12', TIMESTAMPTZ '2025-02-12 20:00:00+00', 130.0::DOUBLE, 132.0::DOUBLE, 129.0::DOUBLE, 131.0::DOUBLE, 200000000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-12 20:00:00+00'),
(101::INTEGER, DATE '2025-02-14', TIMESTAMPTZ '2025-02-14 20:00:00+00', 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 1.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-14 20:00:00+00')
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
`);
// Point-in-time fenced adj_factors snapshot (10:1 split on 2024-06-10)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, DATE '2024-06-10', 10.0::DOUBLE, 10.05::DOUBLE, TIMESTAMPTZ '2024-06-10 00:00:00+00')
) AS t(listing_id, ex_date, cum_split_factor, cum_total_factor, known_at)
) TO '${join(curatedRoot, 'adj_factors', 'part.parquet')}' (
FORMAT PARQUET,
KV_METADATA {
'stock_bot.adj_factors.format_version': '1',
'stock_bot.adj_factors.snapshot_kind': 'point_in_time_fenced',
'stock_bot.adj_factors.as_of_micros': '${asOfMicros}',
'stock_bot.adj_factors.vault_cutoff_micros': '${vaultCutoffMicros}',
'stock_bot.adj_factors.rows_written': '1',
'stock_bot.adj_factors.snapshot_checksum': '0x0123456789abcdef'
}
)
`);
// Events (2024 filing)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(202::INTEGER, TIMESTAMPTZ '2024-06-05 14:30:00+00', TIMESTAMPTZ '2024-06-05 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, 'MD&A'::VARCHAR, '{"filing_id":"f1"}'::VARCHAR)
) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json)
) TO '${join(curatedRoot, 'events', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
`);
// Canadian shorts (+4 biz day known_at)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(202::INTEGER, DATE '2024-06-15', TIMESTAMPTZ '2024-06-21 21:00:00+00', 500000.0::DOUBLE, 25000.0::DOUBLE, NULL::DOUBLE, 'ceo_shorts'::VARCHAR)
) AS t(listing_id, report_date, known_at, shares_short, net_change, pct_float, source)
) TO '${join(curatedRoot, 'shorts', 'part.parquet')}' (FORMAT PARQUET)
`);
// FX 1d (USDCAD)
await writer.run(`
COPY (
SELECT * FROM (VALUES
('USDCAD'::VARCHAR, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 23:59:59.999999+00', 1.375::DOUBLE, 1.378::DOUBLE, 1.372::DOUBLE, 1.376::DOUBLE, 'eod_forex'::VARCHAR, TIMESTAMPTZ '2024-06-10 23:59:59.999999+00')
) AS t(pair, session_date, ts, open, high, low, close, source, known_at)
) TO '${join(curatedRoot, 'fx_1d', 'part.parquet')}' (FORMAT PARQUET)
`);
} finally {
await writer.close();
}
return { curatedRoot, duckTempDir, vaultCutoffTs };
}
describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => {
test('reads real Parquet bars (raw, split, total), events, shorts, fx, universe and enforces Vault fence', async () => {
const { curatedRoot, duckTempDir, vaultCutoffTs } = await buildCuratedFixture();
const opened = await openDuckDbMarketDataStore({
curatedRoot,
vaultCutoffTs,
env: {
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
STOCK_BOT_DUCKDB_THREADS: '2',
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
},
});
try {
// 1. Raw bars: request through 2025-12-31 must clamp before Vault cutoff (2025-02-13) and never return 2025-02-14!
const rawBars: BarRecord[] = [];
for await (const batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2024-06-01',
to: '2025-12-31',
adjustment: 'raw',
})) {
rawBars.push(...batch.rows);
}
expect(rawBars.length).toBe(3);
expect(rawBars.every(r => r.ts < vaultCutoffTs)).toBe(true);
expect(rawBars[0]!.close).toBeCloseTo(1208.88, 6);
expect(rawBars[0]!.volume).toBeCloseTo(41_238_600, 1);
// 2. Vault rejection when from >= vaultCutoffTs
let rejected = false;
try {
for await (const _batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2025-02-13',
to: '2025-08-01',
adjustment: 'raw',
})) {
// should not yield
}
} catch (err) {
rejected = err instanceof VaultHoldoutFenceError;
}
expect(rejected).toBe(true);
// 3. Split-adjusted bars via pinned point_in_time_fenced adj_factors snapshot
const splitBars: BarRecord[] = [];
for await (const batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})) {
splitBars.push(...batch.rows);
}
expect(splitBars.length).toBe(2);
expect(splitBars[0]!.close).toBeCloseTo(120.888, 6);
expect(splitBars[0]!.volume).toBeCloseTo(412_386_000, 1);
expect(splitBars[1]!.close).toBeCloseTo(121.79, 6);
// 4. Total-return-adjusted bars (price divided by cum_total_factor, volume scaled by cum_split_factor)
const totalBars: BarRecord[] = [];
for await (const batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'total',
})) {
totalBars.push(...batch.rows);
}
expect(totalBars.length).toBe(2);
expect(totalBars[0]!.close).toBeCloseTo(1208.88 / 10.05, 6);
expect(totalBars[0]!.volume).toBeCloseTo(412_386_000, 1);
// 5. Events
const events = await opened.store.events({
kinds: ['filing'],
listingIds: [202],
from: '2024-06-01',
to: '2024-06-30',
});
expect(events.rows.length).toBe(1);
expect(events.rows[0]!.subtype).toBe('MD&A');
// 6. Shorts (known_at fence)
const shortsBeforeKnown = await opened.store.shortsAsOf({
listingIds: [202],
from: '2024-06-01',
to: '2024-06-30',
asOf: '2024-06-18',
});
expect(shortsBeforeKnown.rows.length).toBe(0);
const shortsAfterKnown = await opened.store.shortsAsOf({
listingIds: [202],
from: '2024-06-01',
to: '2024-06-30',
asOf: '2024-06-25',
});
expect(shortsAfterKnown.rows.length).toBe(1);
expect(shortsAfterKnown.rows[0]!.shares_short).toBe(500_000);
// 7. FX
const fx = await opened.store.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-30',
});
expect(fx.rows.length).toBe(1);
expect(fx.rows[0]!.close).toBeCloseTo(1.376, 6);
// 8. Universe
expect(await opened.store.universe({ ref: 'US_EQ', date: '2024-06-10' })).toEqual([101]);
expect(await opened.store.universe({ ref: 'CA_EQ', date: '2024-06-10' })).toEqual([202]);
expect(await opened.store.universe({ ref: 'US_CA_EQ', date: '2024-06-10' })).toEqual([
101, 202,
]);
} finally {
await opened.close();
}
});
test('fundamentalsAsOf enforces restatement non-overwrite, multi-year Hive glob, Vault microsecond fence, and allowEstimatedLag semantics', async () => {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2023'), { recursive: true });
await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2024'), { recursive: true });
await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2025'), { recursive: true });
await mkdir(duckTempDir, { recursive: true });
// Vault cutoff = 2025-02-13T00:00:00.000Z
const vaultCutoffTs = computeVaultCutoffTs('2025-08-13');
const s1KnownMs = Date.UTC(2024, 4, 1, 20, 0, 0, 0); // 2024-05-01T20:00:00Z
const s2KnownMs = Date.UTC(2024, 7, 1, 20, 0, 0, 0); // 2024-08-01T20:00:00Z
const s3KnownMs = Date.UTC(2024, 8, 15, 20, 0, 0, 0); // 2024-09-15T20:00:00Z
const writer = await createNodeDuckDbExecutor();
try {
// year=2023 partition: listing 50 (only exists in 2023 partition)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(
50::INTEGER,
TIMESTAMPTZ '2023-11-05 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2023-09-30',
'Q3'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2023-11-05 20:00:00+00',
80.0::DOUBLE,
8.0::DOUBLE,
12.0::DOUBLE,
500.0::DOUBLE,
250.0::DOUBLE,
10.0::DOUBLE,
DATE '2023-09-30',
'USD'::VARCHAR,
310.0::DOUBLE,
31.0::DOUBLE,
46.0::DOUBLE,
FALSE::BOOLEAN
)
) AS t(
listing_id, effective_known_at, known_at_source, has_estimated_lag,
period_end, fiscal_period, currency, period_known_at,
revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding,
ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag
)
) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2023', 'part.parquet')}' (FORMAT PARQUET)
`);
// year=2024 partition:
// - listing 101: S1 (Q1), S2 (Q2), S3 (Q1 restatement known after Q2 -> latest period stays Q2, TTM changes)
// - listing 201: older verified snapshot + newer estimated-lag snapshot (strict mode must omit without fallback)
// - listing 202: verified snapshot with estimated-lag TTM only (strict mode keeps row, nulls ttm_* + ttm_period_end + ttm_currency, preserves ttm_has_estimated_lag)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(
101::INTEGER,
TIMESTAMPTZ '2024-05-01 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-03-31',
'Q1'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2024-05-01 20:00:00+00',
100.0::DOUBLE,
10.0::DOUBLE,
15.0::DOUBLE,
1000.0::DOUBLE,
500.0::DOUBLE,
50.0::DOUBLE,
DATE '2024-03-31',
'USD'::VARCHAR,
380.0::DOUBLE,
38.0::DOUBLE,
55.0::DOUBLE,
FALSE::BOOLEAN
),
(
101::INTEGER,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-06-30',
'Q2'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
120.0::DOUBLE,
14.0::DOUBLE,
20.0::DOUBLE,
1050.0::DOUBLE,
520.0::DOUBLE,
50.0::DOUBLE,
DATE '2024-06-30',
'USD'::VARCHAR,
420.0::DOUBLE,
44.0::DOUBLE,
65.0::DOUBLE,
FALSE::BOOLEAN
),
(
101::INTEGER,
TIMESTAMPTZ '2024-09-15 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-06-30',
'Q2'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
120.0::DOUBLE,
14.0::DOUBLE,
20.0::DOUBLE,
1050.0::DOUBLE,
520.0::DOUBLE,
50.0::DOUBLE,
DATE '2024-06-30',
'USD'::VARCHAR,
415.0::DOUBLE,
42.0::DOUBLE,
63.0::DOUBLE,
FALSE::BOOLEAN
),
(
201::INTEGER,
TIMESTAMPTZ '2024-05-01 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-03-31',
'Q1'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2024-05-01 20:00:00+00',
50.0::DOUBLE,
5.0::DOUBLE,
7.0::DOUBLE,
400.0::DOUBLE,
200.0::DOUBLE,
20.0::DOUBLE,
DATE '2024-03-31',
'USD'::VARCHAR,
190.0::DOUBLE,
19.0::DOUBLE,
27.0::DOUBLE,
FALSE::BOOLEAN
),
(
201::INTEGER,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
'estimated_lag'::VARCHAR,
TRUE::BOOLEAN,
DATE '2024-06-30',
'Q2'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
60.0::DOUBLE,
6.0::DOUBLE,
8.0::DOUBLE,
420.0::DOUBLE,
210.0::DOUBLE,
20.0::DOUBLE,
DATE '2024-06-30',
'USD'::VARCHAR,
210.0::DOUBLE,
21.0::DOUBLE,
30.0::DOUBLE,
TRUE::BOOLEAN
),
(
202::INTEGER,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-06-30',
'Q2'::VARCHAR,
'CAD'::VARCHAR,
TIMESTAMPTZ '2024-08-01 20:00:00+00',
75.0::DOUBLE,
9.0::DOUBLE,
11.0::DOUBLE,
600.0::DOUBLE,
300.0::DOUBLE,
30.0::DOUBLE,
DATE '2024-06-30',
'CAD'::VARCHAR,
300.0::DOUBLE,
30.0::DOUBLE,
45.0::DOUBLE,
TRUE::BOOLEAN
)
) AS t(
listing_id, effective_known_at, known_at_source, has_estimated_lag,
period_end, fiscal_period, currency, period_known_at,
revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding,
ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag
)
) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
`);
// year=2025 partition: Vault microsecond boundary rows
// - listing 102: 1 microsecond before cutoff (eligible), exact cutoff (excluded), post-cutoff (excluded)
// - listing 103: exact cutoff only (must return 0 rows)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(
102::INTEGER,
TIMESTAMPTZ '2025-02-12 23:59:59.999999+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-12-31',
'Q4'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2025-02-12 23:59:59.999999+00',
210.0::DOUBLE,
21.0::DOUBLE,
31.0::DOUBLE,
1500.0::DOUBLE,
750.0::DOUBLE,
60.0::DOUBLE,
DATE '2024-12-31',
'USD'::VARCHAR,
800.0::DOUBLE,
80.0::DOUBLE,
120.0::DOUBLE,
FALSE::BOOLEAN
),
(
102::INTEGER,
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-12-31',
'Q4'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
999.0::DOUBLE,
99.0::DOUBLE,
99.0::DOUBLE,
9999.0::DOUBLE,
4999.0::DOUBLE,
60.0::DOUBLE,
DATE '2024-12-31',
'USD'::VARCHAR,
9999.0::DOUBLE,
999.0::DOUBLE,
999.0::DOUBLE,
FALSE::BOOLEAN
),
(
102::INTEGER,
TIMESTAMPTZ '2025-02-14 12:00:00.000000+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2025-03-31',
'Q1'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2025-02-14 12:00:00.000000+00',
1111.0::DOUBLE,
111.0::DOUBLE,
111.0::DOUBLE,
11111.0::DOUBLE,
5555.0::DOUBLE,
60.0::DOUBLE,
DATE '2025-03-31',
'USD'::VARCHAR,
11111.0::DOUBLE,
1111.0::DOUBLE,
1111.0::DOUBLE,
FALSE::BOOLEAN
),
(
103::INTEGER,
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
'filing_date'::VARCHAR,
FALSE::BOOLEAN,
DATE '2024-12-31',
'Q4'::VARCHAR,
'USD'::VARCHAR,
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
777.0::DOUBLE,
77.0::DOUBLE,
77.0::DOUBLE,
7777.0::DOUBLE,
3333.0::DOUBLE,
40.0::DOUBLE,
DATE '2024-12-31',
'USD'::VARCHAR,
7777.0::DOUBLE,
777.0::DOUBLE,
777.0::DOUBLE,
FALSE::BOOLEAN
)
) AS t(
listing_id, effective_known_at, known_at_source, has_estimated_lag,
period_end, fiscal_period, currency, period_known_at,
revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding,
ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag
)
) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
`);
} finally {
await writer.close();
}
const opened = await openDuckDbMarketDataStore({
curatedRoot,
vaultCutoffTs,
env: {
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
STOCK_BOT_DUCKDB_THREADS: '2',
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
},
});
try {
// 1. Before S1: no row for listing 101
const beforeS1 = await opened.store.fundamentalsAsOf({
listingIds: [101],
fields: ['revenue', 'ttm_revenue'],
asOf: '2024-04-30T23:59:59Z',
});
expect(beforeS1.rows).toEqual([]);
// 2. Between S1 and S2: Q1 row (revenue 100, ttm_revenue 380)
const betweenS1S2 = await opened.store.fundamentalsAsOf({
listingIds: [101],
fields: ['revenue', 'ttm_revenue'],
asOf: '2024-06-15',
});
expect(betweenS1S2.rows).toHaveLength(1);
expect(betweenS1S2.rows[0]).toEqual({
listing_id: 101,
effective_known_at: s1KnownMs,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-03-31',
fiscal_period: 'Q1',
currency: 'USD',
period_known_at: s1KnownMs,
revenue: 100,
ttm_revenue: 380,
ttm_period_end: '2024-03-31',
ttm_currency: 'USD',
ttm_has_estimated_lag: false,
});
// 3. Between S2 and S3: Q2 baseline (revenue 120, period_known_at = S2, pre-restatement TTM 420)
const betweenS2S3 = await opened.store.fundamentalsAsOf({
listingIds: [101],
fields: ['revenue', 'ttm_revenue'],
asOf: '2024-08-15',
});
expect(betweenS2S3.rows).toHaveLength(1);
expect(betweenS2S3.rows[0]).toEqual({
listing_id: 101,
effective_known_at: s2KnownMs,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-06-30',
fiscal_period: 'Q2',
currency: 'USD',
period_known_at: s2KnownMs,
revenue: 120,
ttm_revenue: 420,
ttm_period_end: '2024-06-30',
ttm_currency: 'USD',
ttm_has_estimated_lag: false,
});
// 4. At and after S3 (Q1 restatement with known_at > Q2): Q2 period_end, revenue, and period_known_at stay fixed while ttm_revenue updates to 415
for (const asOf of ['2024-09-15T20:00:00Z', '2024-10-01']) {
const afterS3 = await opened.store.fundamentalsAsOf({
listingIds: [101],
fields: ['revenue', 'ttm_revenue'],
asOf,
});
expect(afterS3.rows).toHaveLength(1);
expect(afterS3.rows[0]).toEqual({
listing_id: 101,
effective_known_at: s3KnownMs,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-06-30',
fiscal_period: 'Q2',
currency: 'USD',
period_known_at: s2KnownMs,
revenue: 120,
ttm_revenue: 415,
ttm_period_end: '2024-06-30',
ttm_currency: 'USD',
ttm_has_estimated_lag: false,
});
}
// 5. Multi-partition glob (year=2023 + year=2024) sorted by listing_id ASC, with non-TTM projection omitting TTM metadata columns
const multiYear = await opened.store.fundamentalsAsOf({
listingIds: [101, 50],
fields: ['revenue'],
asOf: '2024-10-01',
});
expect(multiYear.columns).toEqual([
'listing_id',
'effective_known_at',
'known_at_source',
'has_estimated_lag',
'period_end',
'fiscal_period',
'currency',
'period_known_at',
'revenue',
]);
expect(multiYear.rows.map(r => r.listing_id)).toEqual([50, 101]);
expect(multiYear.rows[0]!.period_end).toBe('2023-09-30');
expect(multiYear.rows[0]!.revenue).toBe(80);
expect(multiYear.rows[1]!.revenue).toBe(120);
// 6. Vault microsecond fence: last pre-cutoff microsecond is eligible; exact cutoff and post-cutoff are excluded
for (const asOf of ['2025-02-13T00:00:00.000Z', '2025-06-01']) {
const fenced = await opened.store.fundamentalsAsOf({
listingIds: [103, 102],
fields: ['revenue'],
asOf,
});
expect(fenced.rows).toHaveLength(1);
expect(fenced.rows[0]!.listing_id).toBe(102);
expect(fenced.rows[0]!.revenue).toBe(210);
expect(fenced.rows[0]!.period_end).toBe('2024-12-31');
}
// 7. allowEstimatedLag default (true) vs strict (false):
// - listing 201 (has_estimated_lag = true on latest snapshot) returned by default, omitted in strict mode without falling back to older verified Q1 row
// - listing 202 (has_estimated_lag = false, ttm_has_estimated_lag = true) kept in strict mode with all ttm_* values + ttm_period_end + ttm_currency nulled and ttm_has_estimated_lag preserved
const lagAllowed = await opened.store.fundamentalsAsOf({
listingIds: [202, 201],
fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'],
asOf: '2024-09-01',
});
expect(lagAllowed.rows.map(r => r.listing_id)).toEqual([201, 202]);
expect(lagAllowed.rows[0]!.revenue).toBe(60);
expect(lagAllowed.rows[0]!.has_estimated_lag).toBe(true);
expect(lagAllowed.rows[1]!.revenue).toBe(75);
expect(lagAllowed.rows[1]!.ttm_revenue).toBe(300);
expect(lagAllowed.rows[1]!.ttm_net_income).toBe(30);
expect(lagAllowed.rows[1]!.ttm_operating_cash_flow).toBe(45);
expect(lagAllowed.rows[1]!.ttm_period_end).toBe('2024-06-30');
expect(lagAllowed.rows[1]!.ttm_currency).toBe('CAD');
expect(lagAllowed.rows[1]!.ttm_has_estimated_lag).toBe(true);
const lagStrict = await opened.store.fundamentalsAsOf({
listingIds: [202, 201],
fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'],
asOf: '2024-09-01',
allowEstimatedLag: false,
});
expect(lagStrict.rows).toHaveLength(1);
expect(lagStrict.rows[0]).toEqual({
listing_id: 202,
effective_known_at: s2KnownMs,
known_at_source: 'filing_date',
has_estimated_lag: false,
period_end: '2024-06-30',
fiscal_period: 'Q2',
currency: 'CAD',
period_known_at: s2KnownMs,
revenue: 75,
ttm_revenue: null,
ttm_net_income: null,
ttm_operating_cash_flow: null,
ttm_period_end: null,
ttm_currency: null,
ttm_has_estimated_lag: true,
});
} finally {
await opened.close();
}
});
});
interface FundamentalsFixtureRow {
readonly listingId: number;
readonly effectiveKnownAt: string;
readonly hasEstimatedLag?: boolean;
readonly periodEnd: string;
readonly fiscalPeriod: string;
readonly periodKnownAt?: string;
readonly revenue: number | null;
readonly ttmRevenue: number | null;
readonly ttmHasEstimatedLag: boolean | null;
}
function fundamentalsRowSql(r: FundamentalsFixtureRow): string {
const num = (v: number | null): string => (v === null ? 'NULL::DOUBLE' : `${v}::DOUBLE`);
const bool = (v: boolean | null): string => (v === null ? 'NULL::BOOLEAN' : `${v ? 'TRUE' : 'FALSE'}::BOOLEAN`);
const ttmMissing = r.ttmRevenue === null;
return `(
${r.listingId}::INTEGER, TIMESTAMPTZ '${r.effectiveKnownAt}', 'filing_date'::VARCHAR, ${bool(r.hasEstimatedLag ?? false)},
DATE '${r.periodEnd}', '${r.fiscalPeriod}'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${r.periodKnownAt ?? r.effectiveKnownAt}',
${num(r.revenue)}, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE,
${ttmMissing ? 'NULL::DATE' : `DATE '${r.periodEnd}'`}, ${ttmMissing ? 'NULL::VARCHAR' : `'USD'::VARCHAR`},
${num(r.ttmRevenue)}, NULL::DOUBLE, NULL::DOUBLE, ${bool(r.ttmHasEstimatedLag)}
)`;
}
async function writeFundamentalsPartition(
curatedRoot: string,
year: number,
rows: readonly FundamentalsFixtureRow[]
): Promise<void> {
const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`);
await mkdir(dir, { recursive: true });
const writer = await createNodeDuckDbExecutor();
try {
await writer.run(`
COPY (
SELECT * FROM (VALUES ${rows.map(fundamentalsRowSql).join(', ')}) AS t(
listing_id, effective_known_at, known_at_source, has_estimated_lag,
period_end, fiscal_period, currency, period_known_at,
revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding,
ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag
)
) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET)
`);
} finally {
await writer.close();
}
}
describe('openDuckDbMarketDataStore fundamentalsAsOf edge cases (@duckdb/node-api)', () => {
async function openFundamentalsStore(): Promise<Awaited<ReturnType<typeof openDuckDbMarketDataStore>>> {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-edge-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(duckTempDir, { recursive: true });
// Partition directory does not drive ranking: listing 7's newest snapshot sits in
// year=2023 while its older one sits in year=2024; listing 8 is the reverse.
await writeFundamentalsPartition(curatedRoot, 2023, [
{ listingId: 7, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 70, ttmRevenue: 270, ttmHasEstimatedLag: false },
{ listingId: 8, effectiveKnownAt: '2023-11-01 12:00:00+00', periodEnd: '2023-09-30', fiscalPeriod: 'Q3', revenue: 80, ttmRevenue: 300, ttmHasEstimatedLag: false },
]);
await writeFundamentalsPartition(curatedRoot, 2024, [
{ listingId: 7, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 65, ttmRevenue: 260, ttmHasEstimatedLag: false },
{ listingId: 8, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 85, ttmRevenue: 310, ttmHasEstimatedLag: false },
// Sub-millisecond neighbours: only the microsecond distinguishes them.
{ listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000500+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 90, ttmRevenue: 360, ttmHasEstimatedLag: false },
{ listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000501+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 91, ttmRevenue: 361, ttmHasEstimatedLag: false },
// Verified Q1, then estimated Q2.
{ listingId: 10, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 100, ttmRevenue: 400, ttmHasEstimatedLag: false },
{ listingId: 10, effectiveKnownAt: '2024-08-01 12:00:00+00', hasEstimatedLag: true, periodEnd: '2024-06-30', fiscalPeriod: 'Q2', revenue: 110, ttmRevenue: 410, ttmHasEstimatedLag: true },
// TTM-only estimated lag.
{ listingId: 11, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 111, ttmRevenue: 444, ttmHasEstimatedLag: true },
// No TTM yet (fewer than four quarters): TTM values and flag are NULL.
{ listingId: 12, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 12, ttmRevenue: null, ttmHasEstimatedLag: null },
]);
return openDuckDbMarketDataStore({
curatedRoot,
vaultCutoffTs: computeVaultCutoffTs('2025-08-13'),
env: {
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
STOCK_BOT_DUCKDB_THREADS: '2',
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
},
});
}
test('selects the latest effective_known_at across Hive partitions regardless of partition directory', async () => {
const opened = await openFundamentalsStore();
try {
const result = await opened.store.fundamentalsAsOf({
listingIds: [8, 7],
fields: ['revenue'],
asOf: '2024-06-01',
});
expect(result.rows.map(r => [r.listing_id, r.fiscal_period, r.revenue])).toEqual([
[7, 'Q1', 70],
[8, 'Q4', 85],
]);
const earlier = await opened.store.fundamentalsAsOf({
listingIds: [7, 8],
fields: ['revenue'],
asOf: '2024-01-01',
});
expect(earlier.rows.map(r => [r.listing_id, r.fiscal_period])).toEqual([[8, 'Q3']]);
} finally {
await opened.close();
}
});
test('binds explicit sub-millisecond asOf so microsecond-adjacent snapshots are separated', async () => {
const opened = await openFundamentalsStore();
try {
const at = async (asOf: string): Promise<unknown[]> =>
(await opened.store.fundamentalsAsOf({ listingIds: [9], fields: ['revenue'], asOf })).rows.map(
r => r.revenue
);
expect(await at('2024-03-01T12:00:00.000499Z')).toEqual([]);
expect(await at('2024-03-01T12:00:00.000500Z')).toEqual([90]);
expect(await at('2024-03-01T14:00:00.000500+02:00')).toEqual([90]);
expect(await at('2024-03-01T12:00:00.000501Z')).toEqual([91]);
} finally {
await opened.close();
}
});
test('strict allowEstimatedLag returns the verified snapshot that was latest at an earlier asOf, and omits the listing once an estimated snapshot is latest', async () => {
const opened = await openFundamentalsStore();
try {
const beforeEstimate = await opened.store.fundamentalsAsOf({
listingIds: [10],
fields: ['revenue'],
asOf: '2024-07-31',
allowEstimatedLag: false,
});
expect(beforeEstimate.rows.map(r => [r.fiscal_period, r.revenue])).toEqual([['Q1', 100]]);
const afterEstimate = await opened.store.fundamentalsAsOf({
listingIds: [10],
fields: ['revenue'],
asOf: '2024-08-02',
allowEstimatedLag: false,
});
expect(afterEstimate.rows).toEqual([]);
} finally {
await opened.close();
}
});
test('strict mode keeps TTM-estimated rows without TTM columns when no ttm_* field is requested, and passes through NULL TTM flags', async () => {
const opened = await openFundamentalsStore();
try {
const noTtm = await opened.store.fundamentalsAsOf({
listingIds: [11],
fields: ['revenue'],
asOf: '2024-06-01',
allowEstimatedLag: false,
});
expect(noTtm.columns).not.toContain('ttm_has_estimated_lag');
expect(noTtm.rows).toEqual([
expect.objectContaining({ listing_id: 11, revenue: 111, has_estimated_lag: false }),
]);
expect(Object.keys(noTtm.rows[0]!)).toEqual(noTtm.columns as string[]);
const nullTtm = await opened.store.fundamentalsAsOf({
listingIds: [12, 11],
fields: ['ttm_revenue'],
asOf: '2024-06-01',
allowEstimatedLag: false,
});
expect(nullTtm.rows.map(r => [r.listing_id, r.ttm_revenue, r.ttm_period_end, r.ttm_currency, r.ttm_has_estimated_lag])).toEqual([
[11, null, null, null, true],
[12, null, null, null, null],
]);
} finally {
await opened.close();
}
});
test('returns only requested listings and is reproducible across repeated identical queries', async () => {
const opened = await openFundamentalsStore();
try {
const q = {
listingIds: [12, 999, 7],
fields: ['ttm_revenue', 'revenue'],
asOf: '2024-09-01T00:00:00.000001Z',
};
const first = await opened.store.fundamentalsAsOf(q);
const second = await opened.store.fundamentalsAsOf(q);
expect(first.rows.map(r => r.listing_id)).toEqual([7, 12]);
expect(second).toEqual(first);
} finally {
await opened.close();
}
});
});

View file

@ -1,394 +0,0 @@
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { existsSync } from 'node:fs';
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DuckDBConnection, DuckDBInstance } from '@duckdb/node-api';
import { createNodeDuckDbExecutor, openResearchCopilotStore } from '@stock-bot/duckdb';
import {
MarketDataStoreValidationError,
VaultHoldoutFenceError,
type BarRecord,
} from '@stock-bot/research/market-data-store';
import {
runResearchCopilotStdioHost,
type PostgresResearchCopilotExecutor,
type QueryDataResultPayload,
type ResearchCopilotHostConfig,
type StdioInput,
type StdioOutput,
} from '@stock-bot/research/mcp';
// QA coverage for T-184 beyond the implementation tests:
// - budget env (`STOCKBOT_DUCKDB_*`) is forwarded and reaches DuckDB;
// - invalid budget env fails closed without leaking native handles or the Postgres URL;
// - `openStore: openResearchCopilotStore` works unwrapped (default env resolution);
// - the Vault cutoff comes from `config.vaultCutoffTs` (not a constant);
// - `databasePath` is forwarded.
// Fixture: listing 202, rows at 2025-03-10/11/12 20:00Z (known_at == ts).
const LISTING_ID = 202;
const DAY1_MS = Date.UTC(2025, 2, 10, 20, 0, 0, 0);
const DAY2_MS = Date.UTC(2025, 2, 11, 20, 0, 0, 0);
const DAY3_MS = Date.UTC(2025, 2, 12, 20, 0, 0, 0);
const FIXED_NOW_MS = Date.UTC(2025, 2, 11, 12, 0, 0, 0);
const PG_SECRET = 'qa_only_fake_pw_7c1e';
const FAKE_POSTGRES_URL = `postgresql://research_ro:${PG_SECRET}@127.0.0.1:5433/trading_bot_dev`;
const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
const tempDirs: string[] = [];
const spies: Array<{ mockRestore(): void }> = [];
afterEach(async () => {
while (spies.length > 0) {
spies.pop()?.mockRestore();
}
while (tempDirs.length > 0) {
const dir = tempDirs.pop();
if (dir !== undefined) {
await rm(dir, { recursive: true, force: true });
}
}
});
function track<T extends { mockRestore(): void }>(spy: T): T {
spies.push(spy);
return spy;
}
function bar(ts: number, base: number): BarRecord {
return {
listingId: LISTING_ID,
ts,
open: base,
high: base + 1,
low: base - 1,
close: base + 0.5,
volume: 1000 * base,
vwap: base + 0.25,
knownAt: ts,
};
}
const BAR1 = bar(DAY1_MS, 10);
const BAR2 = bar(DAY2_MS, 20);
const BAR3 = bar(DAY3_MS, 30);
function config(curatedRoot: string, vaultCutoffTs: number): ResearchCopilotHostConfig {
return {
postgresUrl: FAKE_POSTGRES_URL,
curatedRoot,
vaultCutoffTs,
principalId: AGENT_PRINCIPAL,
libraryRoot: '/tmp/unused-library-root',
referenceListingIds: { XNYS: [LISTING_ID] },
};
}
async function makeRoot(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'stockbot-t184-qa-'));
tempDirs.push(root);
return root;
}
function utcTs(ms: number): string {
return `${new Date(ms).toISOString().slice(0, 19).replace('T', ' ')}+00`;
}
function utcDate(ms: number): string {
return new Date(ms).toISOString().slice(0, 10);
}
async function writeFixture(root: string): Promise<string> {
const curatedRoot = join(root, 'curated');
await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true });
const rows = [BAR1, BAR2, BAR3]
.map(
b =>
// Explicit UTC literals: casting naive timestamps to TIMESTAMPTZ would use the host TimeZone.
`(${LISTING_ID}::INTEGER, DATE '${utcDate(b.ts)}', TIMESTAMPTZ '${utcTs(b.ts)}', ${b.open}::DOUBLE, ${b.high}::DOUBLE, ${b.low}::DOUBLE, ${b.close}::DOUBLE, ${b.volume}::DOUBLE, ${b.vwap}::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '${utcTs(b.knownAt)}')`
)
.join(',\n');
const writer = await createNodeDuckDbExecutor();
try {
await writer.run(`
COPY (
SELECT * FROM (VALUES ${rows})
AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
`);
} finally {
await writer.close();
}
return curatedRoot;
}
async function collect(
iterable: AsyncIterable<{ readonly rows: readonly BarRecord[] }>
): Promise<BarRecord[]> {
const out: BarRecord[] = [];
for await (const batch of iterable) {
out.push(...batch.rows);
}
return out;
}
async function captureError(fn: () => Promise<unknown>): Promise<unknown> {
try {
await fn();
} catch (err) {
return err;
}
return undefined;
}
function fullRangeQuery() {
return {
listingIds: [LISTING_ID],
timeframe: '1d' as const,
from: '2025-03-01',
to: '2025-03-31',
asOf: '2025-03-31',
adjustment: 'raw' as const,
};
}
function memoryStdio(messages: readonly unknown[]): {
readonly input: StdioInput;
readonly output: StdioOutput;
raw(): string;
} {
const chunks: string[] = [];
return {
input: {
async *[Symbol.asyncIterator]() {
for (const m of messages) {
yield `${JSON.stringify(m)}\n`;
}
},
},
output: {
write(chunk: string): boolean {
chunks.push(chunk);
return true;
},
},
raw: () => chunks.join(''),
};
}
function fakePg(): { executor: PostgresResearchCopilotExecutor; calls: number } {
const state = {
calls: 0,
executor: {
async query<Row = Record<string, unknown>>(): Promise<{ readonly rows: readonly Row[] }> {
state.calls += 1;
return { rows: [] };
},
} as PostgresResearchCopilotExecutor,
};
return state;
}
function hostMessages(): unknown[] {
return [
{
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: 't184-qa', version: '1.0.0' },
},
},
{ jsonrpc: '2.0', method: 'notifications/initialized' },
{
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
params: {
name: 'query_data',
arguments: {
listingIds: [LISTING_ID],
from: '2025-03-01',
to: '2025-03-31',
asOf: '2025-03-31',
},
},
},
];
}
describe('openResearchCopilotStore QA (T-184)', () => {
test('uses config.vaultCutoffTs as the only cutoff: moving the cutoff moves the visible rows', async () => {
const curatedRoot = await writeFixture(await makeRoot());
// Cutoff exactly at DAY2 ts: DAY2 (ts == cutoff) is excluded, only DAY1 visible.
const atDay2 = await openResearchCopilotStore(config(curatedRoot, DAY2_MS));
try {
expect(await collect(atDay2.store.bars(fullRangeQuery()))).toEqual([BAR1]);
} finally {
await atDay2.close();
}
// Cutoff 1ms after DAY2: DAY1 + DAY2 visible, DAY3 still fenced.
const afterDay2 = await openResearchCopilotStore(config(curatedRoot, DAY2_MS + 1));
try {
expect(await collect(afterDay2.store.bars(fullRangeQuery()))).toEqual([BAR1, BAR2]);
const err = await captureError(() =>
collect(afterDay2.store.bars({ ...fullRangeQuery(), from: '2025-03-12' }))
);
expect(err).toBeInstanceOf(VaultHoldoutFenceError);
} finally {
await afterDay2.close();
}
// Cutoff after all rows: everything visible (proves no hidden constant cutoff).
const late = await openResearchCopilotStore(config(curatedRoot, Date.UTC(2025, 5, 1)));
try {
expect(await collect(late.store.bars(fullRangeQuery()))).toEqual([BAR1, BAR2, BAR3]);
} finally {
await late.close();
}
});
test('forwards STOCKBOT_DUCKDB_* budget env so DuckDB receives the configured spill directory, threads and memory limit', async () => {
const root = await makeRoot();
const curatedRoot = await writeFixture(root);
const spillDir = join(root, 'spill');
await mkdir(spillDir, { recursive: true });
const runSpy = track(spyOn(DuckDBConnection.prototype, 'run'));
const handle = await openResearchCopilotStore(config(curatedRoot, DAY2_MS), {
env: {
STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB',
STOCKBOT_DUCKDB_THREADS: '1',
STOCKBOT_DUCKDB_TEMP_DIRECTORY: spillDir,
},
});
try {
expect(await collect(handle.store.bars(fullRangeQuery()))).toEqual([BAR1]);
} finally {
await handle.close();
}
const statements = runSpy.mock.calls.map(call => String(call[0]));
expect(statements).toContain(`SET temp_directory = '${spillDir}';`);
expect(statements).toContain('SET threads = 1;');
expect(statements).toContain("SET memory_limit = '512MB';");
});
test('invalid budget env fails closed: open rejects, native connection and instance closed once, no Postgres URL in the error', async () => {
const curatedRoot = await writeFixture(await makeRoot());
const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync'));
const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync'));
const err = await captureError(() =>
openResearchCopilotStore(config(curatedRoot, DAY2_MS), {
env: { STOCKBOT_DUCKDB_THREADS: 'not-a-number' },
})
);
expect(err).toBeInstanceOf(MarketDataStoreValidationError);
expect(connClose).toHaveBeenCalledTimes(1);
expect(instClose).toHaveBeenCalledTimes(1);
const text = `${(err as Error).message} ${(err as Error).stack ?? ''}`;
expect(text).not.toContain(PG_SECRET);
expect(text).not.toContain('postgresql://');
});
test('forwards databasePath: a file-backed DuckDB database is created at the given path', async () => {
const root = await makeRoot();
const curatedRoot = await writeFixture(root);
const dbPath = join(root, 'copilot.duckdb');
expect(existsSync(dbPath)).toBe(false);
const handle = await openResearchCopilotStore(config(curatedRoot, DAY2_MS), {
databasePath: dbPath,
});
try {
expect(existsSync(dbPath)).toBe(true);
expect(await collect(handle.store.bars(fullRangeQuery()))).toEqual([BAR1]);
} finally {
await handle.close();
}
});
test('host wired with openStore: openResearchCopilotStore (unwrapped, default env) serves query_data fenced at config cutoff and closes DuckDB once', async () => {
const curatedRoot = await writeFixture(await makeRoot());
const pg = fakePg();
const io = memoryStdio(hostMessages());
const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync'));
const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync'));
await runResearchCopilotStdioHost({
config: config(curatedRoot, DAY2_MS + 1),
openExecutor: async () => ({ executor: pg.executor, close: async () => {} }),
openStore: openResearchCopilotStore,
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
newId: () => 'qa-id',
now: () => FIXED_NOW_MS,
stdio: { input: io.input, output: io.output },
});
const lines = io
.raw()
.trimEnd()
.split('\n')
.map(l => JSON.parse(l) as { id: number; result: Record<string, unknown> });
expect(lines.map(l => l.id)).toEqual([1, 2]);
const envelope = lines[1]!.result as {
isError?: boolean;
content: Array<{ text: string }>;
};
expect(envelope.isError).toBeUndefined();
const payload = JSON.parse(envelope.content[0]!.text) as QueryDataResultPayload;
expect(payload.vaultCutoffTs).toBe(DAY2_MS + 1);
expect(payload.toMs).toBe(DAY2_MS);
expect(payload.rows).toEqual([BAR1, BAR2]);
expect(io.raw()).not.toContain(PG_SECRET);
expect(pg.calls).toBe(0);
expect(connClose).toHaveBeenCalledTimes(1);
expect(instClose).toHaveBeenCalledTimes(1);
});
test('host with empty curatedRoot: query_data fails without hanging, leaks no Postgres URL, and DuckDB still closes once at EOF', async () => {
const root = await makeRoot();
const emptyRoot = join(root, 'curated');
await mkdir(emptyRoot, { recursive: true });
const io = memoryStdio(hostMessages());
const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync'));
const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync'));
await runResearchCopilotStdioHost({
config: config(emptyRoot, DAY2_MS),
openExecutor: async () => ({ executor: fakePg().executor, close: async () => {} }),
openStore: openResearchCopilotStore,
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
newId: () => 'qa-id',
now: () => FIXED_NOW_MS,
stdio: { input: io.input, output: io.output },
});
const lines = io
.raw()
.trimEnd()
.split('\n')
.map(
l =>
JSON.parse(l) as {
id: number;
result?: { isError?: boolean; content?: Array<{ text: string }> };
error?: unknown;
}
);
const toolResponse = lines.find(l => l.id === 2);
expect(toolResponse).toBeDefined();
const failed = toolResponse!.error !== undefined || toolResponse!.result?.isError === true;
expect(failed).toBe(true);
expect(io.raw()).not.toContain(PG_SECRET);
expect(connClose).toHaveBeenCalledTimes(1);
expect(instClose).toHaveBeenCalledTimes(1);
});
});

View file

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

View file

@ -1,14 +0,0 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": true
},
"include": ["src/**/*"],
"references": [
{
"path": "../../research"
}
]
}

View file

@ -1,21 +1,6 @@
export { PostgreSQLClient } from './client';
export { PostgreSQLTransactionManager } from './transactions';
export { runPostgresMigrations, type MigrationTrack } from './migrations';
export {
RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS,
RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS,
RESEARCH_COPILOT_PG_POOL_MAX,
RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS,
RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS,
ResearchCopilotExecutorError,
openResearchCopilotExecutor,
type ManagedResearchCopilotExecutor,
type ResearchCopilotExecutor,
type ResearchCopilotExecutorConfig,
type ResearchCopilotExecutorDeps,
type ResearchCopilotExecutorErrorCode,
type ResearchCopilotExecutorPool,
} from './research-copilot-executor';
export type {
ConnectionEvents,
PoolMetrics,

View file

@ -45,7 +45,6 @@ const RESEARCH_FILES = new Set([
'32-candidate-parameter-defaults.sql',
'33-candidate-decimal-normalization.sql',
'36-trial-ledger.sql',
'37-research-findings.sql',
]);
function locateMigrationsDir(): string {

View file

@ -1,379 +0,0 @@
/**
* Real PostgreSQL executor factory for the MCP research copilot stdio host.
*
* Opens a bounded `pg.Pool` (`max: 4`, 5 s connect timeout, 10 s statement
* timeout, 15 s driver query timeout, 2 s lock timeout), verifies connectivity
* with a single `SELECT 1` probe, attaches an idle-client `'error'` listener,
* and returns a managed `{ executor, close }` handle structurally assignable
* to `ManagedPostgresExecutor` in `@stock-bot/research/mcp` without importing
* `@stock-bot/research` at runtime.
*
* All errors thrown by this module are {@link ResearchCopilotExecutorError}
* instances with fixed, sanitized messages and no `cause`, so connection
* strings, credentials, hostnames, and raw `pg` error text never leak.
* PostgreSQL unique-violation SQLSTATE `'23505'` is preserved on sanitized
* query errors for `createPostgresFindingWritePort` idempotent retries.
*/
import { Pool, type PoolConfig } from 'pg';
/** Maximum number of PostgreSQL connections in the copilot executor pool. */
export const RESEARCH_COPILOT_PG_POOL_MAX = 4;
/** TCP/startup connection timeout in milliseconds. */
export const RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS = 5_000;
/** Server-side PostgreSQL `statement_timeout` in milliseconds. */
export const RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS = 10_000;
/** Driver-side `pg` `query_timeout` in milliseconds. */
export const RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS = 15_000;
/** Server-side PostgreSQL `lock_timeout` in milliseconds. */
export const RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS = 2_000;
/** Typed error codes emitted by {@link ResearchCopilotExecutorError}. */
export type ResearchCopilotExecutorErrorCode =
| 'INVALID_CONFIG'
| 'OPEN_FAILED'
| 'QUERY_FAILED'
| 'EXECUTOR_CLOSED'
| 'CLOSE_FAILED'
| '23505';
const ERROR_MESSAGES: Readonly<Record<ResearchCopilotExecutorErrorCode, string>> = {
INVALID_CONFIG:
'Invalid PostgreSQL configuration: expected a postgres:// or postgresql:// URL with an explicit host and database.',
OPEN_FAILED: 'Failed to open PostgreSQL executor for research copilot.',
QUERY_FAILED: 'PostgreSQL query failed in research copilot executor.',
EXECUTOR_CLOSED: 'Research copilot PostgreSQL executor is closed.',
CLOSE_FAILED: 'Failed to close PostgreSQL executor for research copilot.',
'23505': 'PostgreSQL unique constraint violation in research copilot executor.',
};
const STRIPPED_TIMEOUT_PARAMS: ReadonlySet<string> = new Set([
'statement_timeout',
'lock_timeout',
'query_timeout',
'connect_timeout',
'connectiontimeoutmillis',
]);
const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i;
const PORT_DIGITS_RE = /^\d+$/;
const CONTROL_CHAR_RE = /[\r\n\0]/;
/**
* Sanitized error thrown by {@link openResearchCopilotExecutor} and the
* managed executor it returns. Never attaches a raw `cause` or embeds DSNs,
* credentials, hostnames, or raw driver messages.
*/
export class ResearchCopilotExecutorError extends Error {
readonly code: ResearchCopilotExecutorErrorCode;
constructor(code: ResearchCopilotExecutorErrorCode, message: string) {
super(message);
this.name = 'ResearchCopilotExecutorError';
this.code = code;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/** Configuration accepted by {@link openResearchCopilotExecutor}. */
export interface ResearchCopilotExecutorConfig {
readonly postgresUrl: string;
}
/** Minimal `pg.Pool` surface required by {@link openResearchCopilotExecutor}. */
export interface ResearchCopilotExecutorPool {
query(text: string, values?: unknown[]): Promise<{ readonly rows: readonly unknown[] }>;
end(): Promise<void>;
on(event: 'error', listener: (error: Error) => void): unknown;
}
/** Optional dependency injection hooks for {@link openResearchCopilotExecutor}. */
export interface ResearchCopilotExecutorDeps {
readonly createPool?: (poolConfig: PoolConfig) => ResearchCopilotExecutorPool;
}
/** Structural query executor compatible with MCP research copilot PostgreSQL adapters. */
export interface ResearchCopilotExecutor {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }>;
}
/** Managed executor handle structurally assignable to `ManagedPostgresExecutor`. */
export interface ManagedResearchCopilotExecutor {
readonly executor: ResearchCopilotExecutor;
close(): Promise<void>;
}
function invalidConfigError(): ResearchCopilotExecutorError {
return new ResearchCopilotExecutorError('INVALID_CONFIG', ERROR_MESSAGES.INVALID_CONFIG);
}
function assertValidPort(rawPort: string): void {
if (!PORT_DIGITS_RE.test(rawPort)) {
throw invalidConfigError();
}
const portNum = Number(rawPort);
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
throw invalidConfigError();
}
}
function parseAndNormalizePoolConfig(config: ResearchCopilotExecutorConfig): PoolConfig {
if (typeof config !== 'object' || config === null || typeof config.postgresUrl !== 'string') {
throw invalidConfigError();
}
const rawUrl = config.postgresUrl;
if (
rawUrl.length === 0 ||
rawUrl !== rawUrl.trim() ||
CONTROL_CHAR_RE.test(rawUrl) ||
!POSTGRES_URL_PREFIX_RE.test(rawUrl)
) {
throw invalidConfigError();
}
let parsed: URL;
try {
parsed = new URL(rawUrl);
} catch {
throw invalidConfigError();
}
if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {
throw invalidConfigError();
}
const hostQueryParams = parsed.searchParams.getAll('host');
if (hostQueryParams.length > 1) {
throw invalidConfigError();
}
const queryHost = hostQueryParams.length === 1 ? (hostQueryParams[0] as string).trim() : '';
if (hostQueryParams.length === 1 && queryHost.length === 0) {
throw invalidConfigError();
}
const hasAuthorityHost = parsed.hostname.length > 0;
if (hasAuthorityHost) {
let decodedHost: string;
try {
decodedHost = decodeURIComponent(parsed.hostname);
} catch {
throw invalidConfigError();
}
if (decodedHost.trim().length === 0) {
throw invalidConfigError();
}
}
if (!hasAuthorityHost && queryHost.length === 0) {
throw invalidConfigError();
}
if (parsed.port.length > 0) {
assertValidPort(parsed.port);
}
const portQueryParams = parsed.searchParams.getAll('port');
if (portQueryParams.length > 1) {
throw invalidConfigError();
}
if (portQueryParams.length === 1) {
assertValidPort((portQueryParams[0] as string).trim());
}
if (!parsed.pathname.startsWith('/') || parsed.pathname.length <= 1) {
throw invalidConfigError();
}
const rawDatabase = parsed.pathname.slice(1);
if (rawDatabase.includes('/')) {
throw invalidConfigError();
}
let decodedDatabase: string;
try {
decodedDatabase = decodeURIComponent(rawDatabase);
} catch {
throw invalidConfigError();
}
if (decodedDatabase.trim().length === 0) {
throw invalidConfigError();
}
try {
if (parsed.username.length > 0) {
decodeURIComponent(parsed.username);
}
if (parsed.password.length > 0) {
decodeURIComponent(parsed.password);
}
} catch {
throw invalidConfigError();
}
const existingOptions: string[] = [];
const keysToDelete: string[] = [];
for (const [key, value] of parsed.searchParams.entries()) {
const lower = key.toLowerCase();
if (lower === 'options') {
const trimmed = value.trim();
if (trimmed.length > 0) {
existingOptions.push(trimmed);
}
keysToDelete.push(key);
} else if (STRIPPED_TIMEOUT_PARAMS.has(lower)) {
keysToDelete.push(key);
}
}
for (let i = 0; i < keysToDelete.length; i += 1) {
parsed.searchParams.delete(keysToDelete[i] as string);
}
const envOptions = typeof process.env.PGOPTIONS === 'string' ? process.env.PGOPTIONS.trim() : '';
const baseOptions = existingOptions.length > 0 ? existingOptions.join(' ') : envOptions;
const poolConfig: PoolConfig = {
connectionString: parsed.toString(),
max: RESEARCH_COPILOT_PG_POOL_MAX,
connectionTimeoutMillis: RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS,
statement_timeout: RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS,
query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS,
lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS,
};
if (baseOptions.length > 0) {
poolConfig.options = `${baseOptions} -c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`;
}
return poolConfig;
}
function resolveCreatePool(
deps?: ResearchCopilotExecutorDeps
): (poolConfig: PoolConfig) => ResearchCopilotExecutorPool {
if (deps === undefined) {
return poolConfig => new Pool(poolConfig);
}
if (typeof deps !== 'object' || deps === null) {
throw invalidConfigError();
}
if (deps.createPool === undefined) {
return poolConfig => new Pool(poolConfig);
}
if (typeof deps.createPool !== 'function') {
throw invalidConfigError();
}
return deps.createPool;
}
function getPostgresErrorCode(error: unknown): string | undefined {
if (typeof error === 'object' && error !== null) {
const code = (error as { readonly code?: unknown }).code;
if (typeof code === 'string') {
return code;
}
}
return undefined;
}
async function safeEndPool(pool: ResearchCopilotExecutorPool): Promise<void> {
try {
await pool.end();
} catch {
// Best-effort cleanup during failed startup; preserve primary OPEN_FAILED error.
}
}
/**
* Opens a bounded, probed PostgreSQL executor for the MCP research copilot
* stdio host.
*/
export async function openResearchCopilotExecutor(
config: ResearchCopilotExecutorConfig,
deps?: ResearchCopilotExecutorDeps
): Promise<ManagedResearchCopilotExecutor> {
const poolConfig = parseAndNormalizePoolConfig(config);
const createPool = resolveCreatePool(deps);
let pool: ResearchCopilotExecutorPool;
try {
pool = createPool(poolConfig);
} catch {
throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED);
}
if (
typeof pool !== 'object' ||
pool === null ||
typeof pool.query !== 'function' ||
typeof pool.end !== 'function' ||
typeof pool.on !== 'function'
) {
throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED);
}
try {
// Keep idle-client disconnects from becoming unhandled EventEmitter errors.
pool.on('error', () => {
// Intentionally absorbed; subsequent queries surface sanitized QUERY_FAILED errors.
});
await pool.query('SELECT 1');
} catch {
await safeEndPool(pool);
throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED);
}
let closed = false;
let closePromise: Promise<void> | null = null;
const executor: ResearchCopilotExecutor = {
async query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
if (closed) {
throw new ResearchCopilotExecutorError('EXECUTOR_CLOSED', ERROR_MESSAGES.EXECUTOR_CLOSED);
}
let rawResult: { readonly rows: readonly unknown[] };
try {
rawResult =
params === undefined ? await pool.query(text) : await pool.query(text, [...params]);
} catch (error) {
if (getPostgresErrorCode(error) === '23505') {
throw new ResearchCopilotExecutorError('23505', ERROR_MESSAGES['23505']);
}
throw new ResearchCopilotExecutorError('QUERY_FAILED', ERROR_MESSAGES.QUERY_FAILED);
}
if (
typeof rawResult !== 'object' ||
rawResult === null ||
!Array.isArray(rawResult.rows)
) {
throw new ResearchCopilotExecutorError('QUERY_FAILED', ERROR_MESSAGES.QUERY_FAILED);
}
return { rows: rawResult.rows as readonly Row[] };
},
};
const close = (): Promise<void> => {
closed = true;
if (closePromise === null) {
closePromise = Promise.resolve()
.then(() => pool.end())
.catch(() => {
throw new ResearchCopilotExecutorError('CLOSE_FAILED', ERROR_MESSAGES.CLOSE_FAILED);
});
}
return closePromise;
};
return { executor, close };
}

View file

@ -1,428 +0,0 @@
import { readFileSync } from 'node:fs';
import { createServer, type AddressInfo, type Socket } from 'node:net';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import { Client, Pool, type PoolConfig } from 'pg';
import {
RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS,
RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS,
RESEARCH_COPILOT_PG_POOL_MAX,
RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS,
RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS,
ResearchCopilotExecutorError,
type ResearchCopilotExecutorPool,
openResearchCopilotExecutor,
} from '../src/index';
const cleanup: Array<() => Promise<void> | void> = [];
afterEach(async () => {
for (const fn of cleanup.splice(0).reverse()) {
await fn();
}
});
describe('openResearchCopilotExecutor edge cases', () => {
test('strips URL timeout overrides while preserving search_path and enforcing executor timeouts', async () => {
const capturedConfigs: PoolConfig[] = [];
const fakePool: ResearchCopilotExecutorPool = {
async query() {
return { rows: [{ '?column?': 1 }] };
},
async end() {},
on() {
return fakePool;
},
};
const hostileUrl =
'postgres://u:p@127.0.0.1:5432/research_db' +
'?sslmode=disable' +
'&application_name=copilot_edge' +
'&statement_timeout=99999' +
'&LOCK_TIMEOUT=88888' +
'&query_timeout=77777' +
'&connect_timeout=66' +
'&connectionTimeoutMillis=55555' +
'&options=-c%20search_path%3Disolated_schema%20-c%20statement_timeout%3D60000%20-c%20lock_timeout%3D60000';
const handle = await openResearchCopilotExecutor(
{ postgresUrl: hostileUrl },
{
createPool(poolConfig) {
capturedConfigs.push(poolConfig);
return fakePool;
},
}
);
expect(capturedConfigs).toHaveLength(1);
const poolConfig = capturedConfigs[0]!;
const normalizedUrl = new URL(poolConfig.connectionString!);
expect(normalizedUrl.searchParams.get('sslmode')).toBe('disable');
expect(normalizedUrl.searchParams.get('application_name')).toBe('copilot_edge');
expect(normalizedUrl.searchParams.has('statement_timeout')).toBe(false);
expect(normalizedUrl.searchParams.has('LOCK_TIMEOUT')).toBe(false);
expect(normalizedUrl.searchParams.has('query_timeout')).toBe(false);
expect(normalizedUrl.searchParams.has('connect_timeout')).toBe(false);
expect(normalizedUrl.searchParams.has('connectionTimeoutMillis')).toBe(false);
expect(normalizedUrl.searchParams.has('options')).toBe(false);
expect(poolConfig.options).toBe(
`-c search_path=isolated_schema -c statement_timeout=60000 -c lock_timeout=60000 ` +
`-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`
);
// Verify pg's own ConnectionParameters parser resolves the enforced timeouts.
const client = new Client(poolConfig);
const params = (
client as unknown as {
connectionParameters: {
statement_timeout?: unknown;
lock_timeout?: unknown;
query_timeout?: unknown;
connect_timeout?: unknown;
options?: string;
application_name?: string;
};
}
).connectionParameters;
expect(params.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS);
expect(params.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS);
expect(params.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS);
expect(params.connect_timeout).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS / 1000);
expect(params.application_name).toBe('copilot_edge');
expect(params.options).toBe(poolConfig.options);
await handle.close();
});
test('accepts Unix-domain socket host query parameter and resolves domain-socket parameters in pg', async () => {
const capturedConfigs: PoolConfig[] = [];
const fakePool: ResearchCopilotExecutorPool = {
async query() {
return { rows: [{ '?column?': 1 }] };
},
async end() {},
on() {
return fakePool;
},
};
const handle = await openResearchCopilotExecutor(
{
postgresUrl:
'postgres:///research_db?host=/var/run/postgresql&statement_timeout=99999&lock_timeout=88888',
},
{
createPool(poolConfig) {
capturedConfigs.push(poolConfig);
return fakePool;
},
}
);
expect(capturedConfigs).toHaveLength(1);
const client = new Client(capturedConfigs[0]);
const params = (
client as unknown as {
connectionParameters: {
host?: string;
database?: string;
isDomainSocket?: boolean;
statement_timeout?: unknown;
lock_timeout?: unknown;
query_timeout?: unknown;
};
}
).connectionParameters;
expect(params.host).toBe('/var/run/postgresql');
expect(params.database).toBe('research_db');
expect(params.isDomainSocket).toBe(true);
expect(params.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS);
expect(params.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS);
expect(params.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS);
await handle.close();
});
test('rejects URLs missing host or database even when PGHOST and PGDATABASE are set', async () => {
const previousPgHost = process.env.PGHOST;
const previousPgDatabase = process.env.PGDATABASE;
process.env.PGHOST = '127.0.0.1';
process.env.PGDATABASE = 'fallback_db';
cleanup.push(() => {
if (previousPgHost === undefined) {
delete process.env.PGHOST;
} else {
process.env.PGHOST = previousPgHost;
}
if (previousPgDatabase === undefined) {
delete process.env.PGDATABASE;
} else {
process.env.PGDATABASE = previousPgDatabase;
}
});
let createPoolCalls = 0;
for (const postgresUrl of [
'postgres:///research_db',
'postgres://127.0.0.1:5432/',
'postgres://127.0.0.1:5432',
]) {
await expect(
openResearchCopilotExecutor(
{ postgresUrl },
{
createPool() {
createPoolCalls += 1;
return {
async query() {
return { rows: [] };
},
async end() {},
on() {
return undefined;
},
};
},
}
)
).rejects.toMatchObject({
name: 'ResearchCopilotExecutorError',
code: 'INVALID_CONFIG',
});
}
expect(createPoolCalls).toBe(0);
});
test('preserves PGOPTIONS startup precedence while enforcing executor timeouts', async () => {
const previousPgOptions = process.env.PGOPTIONS;
cleanup.push(() => {
if (previousPgOptions === undefined) {
delete process.env.PGOPTIONS;
} else {
process.env.PGOPTIONS = previousPgOptions;
}
});
const fakePool: ResearchCopilotExecutorPool = {
async query() {
return { rows: [{ '?column?': 1 }] };
},
async end() {},
on() {
return fakePool;
},
};
// 1. No URL options and no PGOPTIONS -> PoolConfig.options omitted.
delete process.env.PGOPTIONS;
let captured: PoolConfig | undefined;
const h1 = await openResearchCopilotExecutor(
{ postgresUrl: 'postgres://127.0.0.1:5432/research_db' },
{
createPool(poolConfig) {
captured = poolConfig;
return fakePool;
},
}
);
expect(captured?.options).toBeUndefined();
const c1 = new Client(captured);
const p1 = (
c1 as unknown as {
connectionParameters: {
options?: string;
statement_timeout?: unknown;
lock_timeout?: unknown;
};
}
).connectionParameters;
expect(p1.options).toBeUndefined();
expect(p1.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS);
expect(p1.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS);
await h1.close();
// 2. PGOPTIONS set with no URL options -> PGOPTIONS preserved + executor timeouts appended.
process.env.PGOPTIONS = '-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888';
captured = undefined;
const h2 = await openResearchCopilotExecutor(
{ postgresUrl: 'postgres://127.0.0.1:5432/research_db' },
{
createPool(poolConfig) {
captured = poolConfig;
return fakePool;
},
}
);
expect(captured?.options).toBe(
`-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888 ` +
`-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`
);
const c2 = new Client(captured);
const p2 = (
c2 as unknown as { connectionParameters: { options?: string } }
).connectionParameters;
expect(p2.options).toBe(captured?.options);
await h2.close();
// 3. Both URL options and PGOPTIONS set -> URL options wins over PGOPTIONS, timeouts still appended.
process.env.PGOPTIONS = '-c search_path=env_schema';
captured = undefined;
const h3 = await openResearchCopilotExecutor(
{
postgresUrl:
'postgres://127.0.0.1:5432/research_db?options=-c%20search_path%3Durl_schema',
},
{
createPool(poolConfig) {
captured = poolConfig;
return fakePool;
},
}
);
expect(captured?.options).toBe(
`-c search_path=url_schema ` +
`-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`
);
await h3.close();
});
test('absorbs idle-client pool error events without crashing the process', async () => {
const errorListeners: Array<(error: Error) => void> = [];
const fakePool: ResearchCopilotExecutorPool = {
async query(text) {
return { rows: [{ sql: text }] };
},
async end() {},
on(event, listener) {
if (event === 'error') {
errorListeners.push(listener);
}
return fakePool;
},
};
const handle = await openResearchCopilotExecutor(
{ postgresUrl: 'postgres://127.0.0.1:5432/research_db' },
{ createPool: () => fakePool }
);
expect(errorListeners).toHaveLength(1);
expect(() => errorListeners[0]!(new Error('idle client disconnected'))).not.toThrow();
const res = await handle.executor.query<{ sql: string }>('SELECT 2');
expect(res.rows).toEqual([{ sql: 'SELECT 2' }]);
await handle.close();
});
test('deduplicates concurrent close() calls and rejects queries started during shutdown', async () => {
let resolveEnd!: () => void;
let endCalls = 0;
let queryCalls = 0;
const fakePool: ResearchCopilotExecutorPool = {
async query() {
queryCalls += 1;
return { rows: [] };
},
end() {
endCalls += 1;
return new Promise<void>(resolve => {
resolveEnd = resolve;
});
},
on() {
return fakePool;
},
};
const handle = await openResearchCopilotExecutor(
{ postgresUrl: 'postgres://127.0.0.1:5432/research_db' },
{ createPool: () => fakePool }
);
expect(queryCalls).toBe(1);
const closeA = handle.close();
const closeB = handle.close();
// Even while pool.end() is still in flight, new queries must reject immediately.
await expect(handle.executor.query('SELECT 2')).rejects.toMatchObject({
name: 'ResearchCopilotExecutorError',
code: 'EXECUTOR_CLOSED',
});
expect(queryCalls).toBe(1);
expect(endCalls).toBe(1);
resolveEnd();
await Promise.all([closeA, closeB]);
expect(endCalls).toBe(1);
});
test('rejects with sanitized OPEN_FAILED when a real pg.Pool times out against a silent loopback listener', async () => {
const sockets = new Set<Socket>();
const server = createServer(socket => {
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
// Intentionally accept and never reply so pg hits its connection timeout.
});
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => resolve());
});
cleanup.push(async () => {
for (const socket of sockets) {
socket.destroy();
}
await new Promise<void>(resolve => server.close(() => resolve()));
});
const { port } = server.address() as AddressInfo;
const secretPass = 'LoopbackSecretPass99';
const loopbackUrl = `postgres://loopback_user:${secretPass}@127.0.0.1:${port}/research_db`;
let observedConfig: PoolConfig | undefined;
let caught: unknown;
try {
await openResearchCopilotExecutor(
{ postgresUrl: loopbackUrl },
{
createPool(poolConfig) {
observedConfig = poolConfig;
// Keep the default config assertions intact, but tighten connect timeout for fast local test execution.
return new Pool({
...poolConfig,
connectionTimeoutMillis: 150,
});
},
}
);
} catch (err) {
caught = err;
}
expect(observedConfig?.max).toBe(RESEARCH_COPILOT_PG_POOL_MAX);
expect(observedConfig?.connectionTimeoutMillis).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS);
expect(observedConfig?.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS);
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
const typed = caught as ResearchCopilotExecutorError;
expect(typed.code).toBe('OPEN_FAILED');
expect((typed as { cause?: unknown }).cause).toBeUndefined();
expect(typed.message).not.toContain('loopback_user');
expect(typed.message).not.toContain(secretPass);
expect(typed.message).not.toContain('127.0.0.1');
expect(typed.message).not.toContain(String(port));
});
test('has no runtime import of @stock-bot/research', () => {
const sourcePath = fileURLToPath(
new URL('../src/research-copilot-executor.ts', import.meta.url)
);
const source = readFileSync(sourcePath, 'utf8');
expect(source).not.toMatch(/from\s+['"]@stock-bot\/research/);
expect(source).not.toMatch(/require\(\s*['"]@stock-bot\/research/);
});
});

View file

@ -1,423 +0,0 @@
import { describe, expect, test } from 'bun:test';
import type { PoolConfig } from 'pg';
import {
RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS,
RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS,
RESEARCH_COPILOT_PG_POOL_MAX,
RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS,
RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS,
ResearchCopilotExecutorError,
type ResearchCopilotExecutorPool,
openResearchCopilotExecutor,
} from '../src/index';
const SECRET_USER = 'copilot_secret_user';
const SECRET_PASS = 'Sup3rS3cretP@ssw0rd!';
const SECRET_HOST = 'pg-internal-secret.example.test';
const VALID_URL = `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`;
interface FakePoolState {
readonly queries: Array<{ readonly text: string; readonly values?: unknown[] }>;
readonly errorListeners: Array<(error: Error) => void>;
endCalls: number;
readonly pool: ResearchCopilotExecutorPool;
}
function createFakePool(options?: {
onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>;
onEnd?: () => Promise<void>;
}): FakePoolState {
const queries: Array<{ readonly text: string; readonly values?: unknown[] }> = [];
const errorListeners: Array<(error: Error) => void> = [];
const state: FakePoolState = {
queries,
errorListeners,
endCalls: 0,
pool: {
async query(text: string, values?: unknown[]) {
queries.push(values === undefined ? { text } : { text, values });
if (options?.onQuery) {
return options.onQuery(text, values);
}
return { rows: [] };
},
async end() {
state.endCalls += 1;
if (options?.onEnd) {
return options.onEnd();
}
},
on(event: 'error', listener: (error: Error) => void) {
if (event === 'error') {
errorListeners.push(listener);
}
return state.pool;
},
},
};
return state;
}
function assertNoSecretsLeaked(error: unknown): void {
expect(error).toBeInstanceOf(ResearchCopilotExecutorError);
const typed = error as ResearchCopilotExecutorError;
expect((typed as { cause?: unknown }).cause).toBeUndefined();
expect('cause' in typed).toBe(false);
expect('detail' in typed).toBe(false);
expect('extraDiag' in typed).toBe(false);
const message = typed.message;
for (const needle of [
VALID_URL,
SECRET_USER,
SECRET_PASS,
encodeURIComponent(SECRET_PASS),
SECRET_HOST,
'raw-pg-secret',
]) {
expect(message).not.toContain(needle);
}
}
describe('openResearchCopilotExecutor', () => {
test('opens a bounded pg pool, probes once with SELECT 1, and attaches an error listener', async () => {
const previousPgOptions = process.env.PGOPTIONS;
delete process.env.PGOPTIONS;
try {
const capturedConfigs: PoolConfig[] = [];
const fake = createFakePool({
async onQuery(text) {
if (text === 'SELECT 1') {
return { rows: [{ '?column?': 1 }] };
}
return { rows: [{ id: 42 }] };
},
});
const handle = await openResearchCopilotExecutor(
{ postgresUrl: VALID_URL },
{
createPool(poolConfig) {
capturedConfigs.push(poolConfig);
return fake.pool;
},
}
);
expect(capturedConfigs).toHaveLength(1);
expect(capturedConfigs[0]).toEqual({
connectionString: VALID_URL,
max: RESEARCH_COPILOT_PG_POOL_MAX,
connectionTimeoutMillis: RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS,
statement_timeout: RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS,
query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS,
lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS,
});
expect(capturedConfigs[0]?.options).toBeUndefined();
expect(RESEARCH_COPILOT_PG_POOL_MAX).toBe(4);
expect(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS).toBe(5_000);
expect(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS).toBe(10_000);
expect(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS).toBe(15_000);
expect(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS).toBe(2_000);
expect(fake.errorListeners).toHaveLength(1);
expect(fake.queries).toEqual([{ text: 'SELECT 1' }]);
const res = await handle.executor.query<{ id: number }>('SELECT $1::int AS id', [42]);
expect(res.rows).toEqual([{ id: 42 }]);
expect(fake.queries).toEqual([
{ text: 'SELECT 1' },
{ text: 'SELECT $1::int AS id', values: [42] },
]);
await handle.close();
expect(fake.endCalls).toBe(1);
} finally {
if (previousPgOptions === undefined) {
delete process.env.PGOPTIONS;
} else {
process.env.PGOPTIONS = previousPgOptions;
}
}
});
test('accepts postgresql:// scheme and Unix-domain socket host query parameters', async () => {
for (const postgresUrl of [
'postgresql://127.0.0.1:5432/research_db',
'postgres:///research_db?host=/var/run/postgresql',
'postgresql:///research_db?host=/var/run/postgresql',
]) {
const fake = createFakePool();
const handle = await openResearchCopilotExecutor(
{ postgresUrl },
{ createPool: () => fake.pool }
);
expect(fake.queries).toEqual([{ text: 'SELECT 1' }]);
await handle.close();
}
});
test('rejects invalid URLs with INVALID_CONFIG before constructing a pool', async () => {
const invalidUrls = [
'',
' ',
` ${VALID_URL} `,
`${VALID_URL}\n`,
'not-a-url',
`http://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`,
`mysql://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:3306/research_db`,
'postgres:/research_db?host=%2Ftmp',
'postgresql:/research_db?host=%2Ftmp',
'postgres:///research_db',
'postgres:///research_db?host=',
'postgres:///research_db?host=%20%20',
'postgres:///research_db?host=/var/run/postgresql&host=/tmp',
'postgres:///research_db?HOST=/var/run/postgresql',
'postgres://copilot@db.example/?dbname=research',
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=/a&host=/b`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=0`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=70000`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=abc`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=5432&port=5433`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%20%20`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/db/extra`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:0/research_db`,
`postgres://%ZZ:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`,
`postgres://${SECRET_USER}:%ZZ@${SECRET_HOST}:5432/research_db`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%ZZ`,
];
let createPoolCalls = 0;
for (const postgresUrl of invalidUrls) {
let caught: unknown;
try {
await openResearchCopilotExecutor(
{ postgresUrl },
{
createPool() {
createPoolCalls += 1;
return createFakePool().pool;
},
}
);
} catch (err) {
caught = err;
}
assertNoSecretsLeaked(caught);
expect((caught as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG');
}
expect(createPoolCalls).toBe(0);
});
test('rejects malformed config or deps with INVALID_CONFIG', async () => {
await expect(
openResearchCopilotExecutor(null as unknown as { postgresUrl: string })
).rejects.toMatchObject({
name: 'ResearchCopilotExecutorError',
code: 'INVALID_CONFIG',
});
await expect(
openResearchCopilotExecutor(
{ postgresUrl: VALID_URL },
{ createPool: 'not-a-fn' as unknown as () => ResearchCopilotExecutorPool }
)
).rejects.toMatchObject({
name: 'ResearchCopilotExecutorError',
code: 'INVALID_CONFIG',
});
});
test('ends pool and throws sanitized OPEN_FAILED when startup probe fails', async () => {
const fake = createFakePool({
async onQuery() {
throw new Error(`password authentication failed for ${SECRET_USER} at ${SECRET_HOST} raw-pg-secret`);
},
});
let caught: unknown;
try {
await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool });
} catch (err) {
caught = err;
}
assertNoSecretsLeaked(caught);
expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED');
expect(fake.endCalls).toBe(1);
});
test('still throws OPEN_FAILED when both probe and cleanup end() fail', async () => {
const fake = createFakePool({
async onQuery() {
throw new Error(`connect ECONNREFUSED ${SECRET_HOST} raw-pg-secret`);
},
async onEnd() {
throw new Error(`pool end failed ${VALID_URL}`);
},
});
let caught: unknown;
try {
await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool });
} catch (err) {
caught = err;
}
assertNoSecretsLeaked(caught);
expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED');
expect(fake.endCalls).toBe(1);
});
test('forwards parameters defensively without mutating caller arrays', async () => {
const fake = createFakePool({
async onQuery(text, values) {
if (values) {
values.push('mutated-by-driver');
}
return { rows: [{ text }] };
},
});
const handle = await openResearchCopilotExecutor(
{ postgresUrl: VALID_URL },
{ createPool: () => fake.pool }
);
const callerParams = Object.freeze(['alpha', 7]);
const res = await handle.executor.query('SELECT $1, $2', callerParams);
expect(res.rows).toEqual([{ text: 'SELECT $1, $2' }]);
expect(callerParams).toEqual(['alpha', 7]);
await handle.executor.query('SELECT 2');
expect(fake.queries[2]).toEqual({ text: 'SELECT 2' });
expect('values' in fake.queries[2]!).toBe(false);
await handle.close();
});
test('preserves SQLSTATE 23505 on sanitized unique-violation query errors without leaking cause or driver fields', async () => {
let callCount = 0;
const rawCause = new Error(`nested pgpass secret ${SECRET_PASS}`);
const fake = createFakePool({
async onQuery() {
callCount += 1;
if (callCount === 1) {
return { rows: [{ '?column?': 1 }] };
}
const pgErr = Object.assign(
new Error(`duplicate key value violates unique constraint on ${SECRET_HOST} raw-pg-secret`, {
cause: rawCause,
}),
{
code: '23505',
detail: `Key (id)=(dup-1) already exists (${SECRET_PASS})`,
extraDiag: 'sensitive-driver-field',
}
);
throw pgErr;
},
});
const handle = await openResearchCopilotExecutor(
{ postgresUrl: VALID_URL },
{ createPool: () => fake.pool }
);
let caught: unknown;
try {
await handle.executor.query('INSERT INTO findings (id) VALUES ($1)', ['dup-1']);
} catch (err) {
caught = err;
}
assertNoSecretsLeaked(caught);
expect((caught as ResearchCopilotExecutorError).code).toBe('23505');
await handle.close();
});
test('sanitizes generic query errors to QUERY_FAILED with no cause, extra fields, or raw text', async () => {
let callCount = 0;
const rawCause = new Error(`nested env PGPASSWORD=${SECRET_PASS}`);
const fake = createFakePool({
async onQuery() {
callCount += 1;
if (callCount === 1) {
return { rows: [{ '?column?': 1 }] };
}
throw Object.assign(
new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`, {
cause: rawCause,
}),
{ code: '42P01', detail: 'driver-detail', extraDiag: 'sensitive-driver-field' }
);
},
});
const handle = await openResearchCopilotExecutor(
{ postgresUrl: VALID_URL },
{ createPool: () => fake.pool }
);
let caught: unknown;
try {
await handle.executor.query('SELECT * FROM missing');
} catch (err) {
caught = err;
}
assertNoSecretsLeaked(caught);
expect((caught as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED');
await handle.close();
});
test('close() is idempotent and subsequent queries fail with EXECUTOR_CLOSED', async () => {
const fake = createFakePool();
const handle = await openResearchCopilotExecutor(
{ postgresUrl: VALID_URL },
{ createPool: () => fake.pool }
);
await handle.close();
await handle.close();
expect(fake.endCalls).toBe(1);
let caught: unknown;
try {
await handle.executor.query('SELECT 1');
} catch (err) {
caught = err;
}
assertNoSecretsLeaked(caught);
expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED');
expect(fake.queries).toHaveLength(1); // Only the initial SELECT 1 probe ran.
});
test('sanitizes pool.end() failures to CLOSE_FAILED with no cause or secret leakage', async () => {
const fake = createFakePool({
async onEnd() {
throw new Error(`failed closing pool for ${VALID_URL} raw-pg-secret`);
},
});
const handle = await openResearchCopilotExecutor(
{ postgresUrl: VALID_URL },
{ createPool: () => fake.pool }
);
let caught: unknown;
try {
await handle.close();
} catch (err) {
caught = err;
}
assertNoSecretsLeaked(caught);
expect((caught as ResearchCopilotExecutorError).code).toBe('CLOSE_FAILED');
expect(fake.endCalls).toBe(1);
});
});

View file

@ -1,50 +0,0 @@
import type { Pool } from 'pg';
import type {
ManagedPostgresExecutor,
PostgresResearchCopilotExecutor,
ResearchCopilotHostConfig,
ResearchCopilotStdioHostDeps,
} from '@stock-bot/research/mcp';
import {
type ManagedResearchCopilotExecutor,
type ResearchCopilotExecutor,
type ResearchCopilotExecutorConfig,
type ResearchCopilotExecutorDeps,
type ResearchCopilotExecutorError,
type ResearchCopilotExecutorErrorCode,
type ResearchCopilotExecutorPool,
openResearchCopilotExecutor,
} from '../src/index';
// The factory must plug directly into ResearchCopilotStdioHostDeps.openExecutor.
openResearchCopilotExecutor satisfies ResearchCopilotStdioHostDeps['openExecutor'];
// Full host config is structurally assignable to the minimal executor config.
declare const hostConfig: ResearchCopilotHostConfig;
hostConfig satisfies ResearchCopilotExecutorConfig;
// Returned handle and executor are structurally assignable to the MCP host ports.
declare const managedHandle: ManagedResearchCopilotExecutor;
managedHandle satisfies ManagedPostgresExecutor;
declare const executor: ResearchCopilotExecutor;
executor satisfies PostgresResearchCopilotExecutor;
// Real pg.Pool satisfies the injected pool contract.
declare const pgPool: Pool;
pgPool satisfies ResearchCopilotExecutorPool;
// Optional deps contract accepts createPool returning pg.Pool.
const validDeps: ResearchCopilotExecutorDeps = {
createPool: () => pgPool,
};
void validDeps;
// Error code union includes all sanitized lifecycle codes plus SQLSTATE 23505.
declare const errorInstance: ResearchCopilotExecutorError;
const errorCode: ResearchCopilotExecutorErrorCode = errorInstance.code;
void errorCode;
// Negative checks: missing postgresUrl must fail typechecking.
// @ts-expect-error postgresUrl is required.
void openResearchCopilotExecutor({});

View file

@ -1,97 +1,65 @@
# 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.
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 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
- **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
### Parameterized Queries & `LATEST ON`
```typescript
import { QuestDBClient, QuestDBQueryBuilder } from '@stock-bot/questdb';
import { QuestDBClient } from '@stock-bot/questdb';
const questClient = new QuestDBClient({
host: 'localhost',
httpPort: 9000,
pgPort: 8812,
influxPort: 9009,
database: 'qdb',
});
// Initialize client
const questClient = new QuestDBClient();
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'],
// 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()
});
// Override the designated timestamp column explicitly
const latestRevisions = await questClient.latestBy(
'bar_revisions',
['listing_id', 'revised_at', 'new_close'],
'listing_id',
{ timestampColumn: 'revised_at' }
);
// 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 with bound filters
const hourlyStats = await questClient
.aggregate('ohlcv_data')
.selectAgg({ avg_close: 'avg(close)' })
.whereSymbol('AAPL')
.whereLastHours(24)
// Time-series aggregations
const dailyStats = await questClient.aggregate('ohlcv')
.select(['symbol', 'avg(close) as avg_price'])
.where('symbol = ?', ['AAPL'])
.groupBy('symbol')
.sampleBy('1h')
.sampleBy('1d', 'timestamp')
.execute();
```
### Reading `bars_1m` Ranges
## Data Types
```typescript
import { readBars1m } from '@stock-bot/questdb';
The client provides typed access to the following time-series data:
// 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()`.
- **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
@ -106,10 +74,29 @@ QUESTDB_INFLUX_PORT=9009
## Time-Series Features
QuestDB 10.2.0 supports:
QuestDB excels at:
- **High-frequency data**: Millions of data points per second
- **Time-based partitioning**: Monthly WAL partitions for intraday tables
- **Time-based partitioning**: Automatic partitioning by time
- **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>`)
- **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'
```

View file

@ -3,193 +3,15 @@ import { Pool } from 'pg';
import type { LoggerLike } from '@stock-bot/logger';
import { QuestDBHealthMonitor } from './health';
import { QuestDBInfluxWriter } from './influx-writer';
import {
assertIdentifier,
assertSampleInterval,
assertSelectColumn,
QuestDBQueryBuilder,
rebaseWhereCondition,
} from './query-builder';
import { QuestDBQueryBuilder } 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
*
@ -409,125 +231,72 @@ export class QuestDBClient {
}
/**
* Execute a time-series specific query with SAMPLE BY.
* `where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `params`.
* Execute a time-series specific query with SAMPLE BY
*/
async sampleBy<T = QueryResultRow>(
table: TableNames | string,
table: TableNames,
columns: string[],
interval: string,
timeColumn: string = 'timestamp',
_timeColumn: string = 'timestamp',
where?: string,
params?: unknown[]
): Promise<QueryResult<T>> {
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 columnsStr = columns.join(', ');
const whereClause = where ? `WHERE ${where}` : '';
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');
}
const sql = `
SELECT ${columnsStr}
FROM ${table}
${whereClause}
SAMPLE BY ${interval}
ALIGN TO CALENDAR
`;
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);
return await this.query<T>(sql, params);
}
/**
* 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`.
* Get latest values by symbol using LATEST BY
*/
async latestBy<T = QueryResultRow>(
table: TableNames | string,
table: TableNames,
columns: string | string[] = '*',
keyColumns: string | string[] = 'symbol',
options?: LatestByOptions
keyColumns: string | string[] = 'symbol'
): Promise<QueryResult<T>> {
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 columnsStr = Array.isArray(columns) ? columns.join(', ') : columns;
const keyColumnsStr = Array.isArray(keyColumns) ? keyColumns.join(', ') : keyColumns;
const builder = this.queryBuilder().select(...cols).from(table);
const sql = `
SELECT ${columnsStr}
FROM ${table}
LATEST BY ${keyColumnsStr}
`;
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>();
return await this.query<T>(sql);
}
/**
* Execute ASOF JOIN for time-series correlation.
* `joinCondition` and `where` are treated as trusted SQL fragments.
* Execute ASOF JOIN for time-series correlation
*/
async asofJoin<T = QueryResultRow>(
leftTable: TableNames | string,
rightTable: TableNames | string,
leftTable: TableNames,
rightTable: TableNames,
joinCondition: string,
columns?: string[],
where?: string,
params?: unknown[]
): Promise<QueryResult<T>> {
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 columnsStr = columns ? columns.join(', ') : '*';
const whereClause = where ? `WHERE ${where}` : '';
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');
}
const sql = `
SELECT ${columnsStr}
FROM ${leftTable}
ASOF JOIN ${rightTable} ON ${joinCondition}
${whereClause}
`;
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);
return await this.query<T>(sql, params);
}
/**
@ -551,7 +320,9 @@ export class QuestDBClient {
* Get table information
*/
async getTableInfo(tableName: string): Promise<QueryResultRow[]> {
const result = await this.query('SELECT * FROM table_columns($1)', [tableName]);
const result = await this.query(`SELECT * FROM table_columns WHERE table_name = ?`, [
tableName,
]);
return result.rows;
}
@ -603,9 +374,8 @@ export class QuestDBClient {
* Optimize table by rebuilding partitions
*/
async optimizeTable(tableName: string): Promise<void> {
const validTable = assertIdentifier(tableName, 'table name');
await this.query(`VACUUM TABLE ${validTable}`);
this.logger.debug(`Optimized table: ${validTable}`);
await this.query(`VACUUM TABLE ${tableName}`);
this.logger.debug(`Optimized table: ${tableName}`);
}
/**
@ -617,19 +387,14 @@ 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 ${validTable} (
CREATE TABLE IF NOT EXISTS ${tableName} (
${columns}
) TIMESTAMP(${validTimestamp}) PARTITION BY ${partitionBy}
) TIMESTAMP(${timestampColumn}) PARTITION BY ${partitionBy}
`;
await this.query(sql);
this.logger.info(`Created table: ${validTable}`);
this.logger.info(`Created table: ${tableName}`);
}
/**

View file

@ -1,550 +0,0 @@
import type { Bar1mRow } from './types';
/** QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`). */
export const ILP_V2_DOUBLE_TYPE = 0x10;
/** Default maximum buffered bytes before flushing a batch (1 MiB). */
export const DEFAULT_ILP_MAX_BATCH_BYTES = 1_048_576;
/** Default maximum buffered rows before flushing a batch. */
export const DEFAULT_ILP_MAX_BATCH_ROWS = 10_000;
const TABLE_BARS_1M = 'bars_1m';
const TABLE_FX_1M = 'fx_1m';
const INT32_MIN = -2_147_483_648;
const INT32_MAX = 2_147_483_647;
const INT64_MIN = -(2n ** 63n);
const INT64_MAX = 2n ** 63n - 1n;
const BYTE_SPACE = 0x20;
const BYTE_COMMA = 0x2c;
const BYTE_EQUALS = 0x3d;
const BYTE_LF = 0x0a;
const BYTE_CR = 0x0d;
const BYTE_BACKSLASH = 0x5c;
const textEncoder = new TextEncoder();
const BARS_1M_OPEN_PREFIX = textEncoder.encode(' open==');
const HIGH_PREFIX = textEncoder.encode(',high==');
const LOW_PREFIX = textEncoder.encode(',low==');
const CLOSE_PREFIX = textEncoder.encode(',close==');
const VOLUME_PREFIX = textEncoder.encode(',volume==');
const FX_1M_PREFIX = textEncoder.encode(`${TABLE_FX_1M},pair=`);
const FX_1M_SOURCE_PREFIX = textEncoder.encode(',source=');
/** Valid intraday trading session tags for `bars_1m`. */
export type Bar1mSession = 'PRE' | 'RTH' | 'POST';
/**
* Curated `bars_1m` row input for QuestDB ILP v2 encoding.
*
* Derived from read-side `Bar1mRow` with `vwap` omitted (left NULL in QuestDB) and
* `session` / `source` narrowed to required non-null write values matching `M2_INTRADAY_SCHEMAS.bars_1m`.
*/
export type Bar1mIlpV2Row = Omit<Bar1mRow, 'vwap' | 'session' | 'source'> & {
session: Bar1mSession;
source: string;
};
/**
* Curated `fx_1m` row input for QuestDB ILP v2 encoding.
*
* Matches `M2_INTRADAY_SCHEMAS.fx_1m`: symbols `pair`, `source`; binary doubles
* `open`, `high`, `low`, `close`; designated timestamp `ts` (UTC epoch microseconds).
*/
export interface Fx1mIlpV2Row {
pair: string;
source: string;
open: number;
high: number;
low: number;
close: number;
ts: bigint;
}
/** Discriminated error kinds for `IlpV2EncodeError`. */
export type IlpV2EncodeErrorKind =
| 'empty-symbol'
| 'invalid-session'
| 'invalid-listing-id'
| 'non-finite-double'
| 'negative-timestamp'
| 'timestamp-out-of-range';
/**
* Typed validation error thrown by `encodeBar1mIlpV2` and `encodeFx1mIlpV2`.
*
* Validation runs atomically before any bytes are encoded or buffered.
*/
export class IlpV2EncodeError extends Error {
public readonly kind: IlpV2EncodeErrorKind;
public readonly field: string;
public readonly value?: number | bigint | string;
constructor(
kind: IlpV2EncodeErrorKind,
field: string,
message: string,
value?: number | bigint | string
) {
super(message);
this.name = 'IlpV2EncodeError';
this.kind = kind;
this.field = field;
if (value !== undefined) {
this.value = value;
}
Object.setPrototypeOf(this, new.target.prototype);
}
}
/** Injected output port for `createIlpV2BatchWriter`. */
export interface IlpV2BatchSink {
write(batch: Uint8Array): Promise<void>;
}
/** Configuration options for `createIlpV2BatchWriter`. */
export interface IlpV2BatchWriterOptions {
sink: IlpV2BatchSink;
maxBatchBytes?: number;
maxBatchRows?: number;
}
/** Write summary returned by `IlpV2BatchWriter.finish()`. */
export interface IlpV2BatchWriterStats {
rows: number;
batches: number;
bytes: number;
}
/** Pure, sink-injected QuestDB ILP v2 batch writer for `bars_1m` and `fx_1m`. */
export interface IlpV2BatchWriter {
writeBar1m(row: Bar1mIlpV2Row): Promise<void>;
writeFx1m(row: Fx1mIlpV2Row): Promise<void>;
flush(): Promise<void>;
finish(): Promise<IlpV2BatchWriterStats>;
}
function validateNonEmptySymbol(field: string, value: string): void {
if (typeof value !== 'string' || value.length === 0) {
throw new IlpV2EncodeError('empty-symbol', field, `empty ILP symbol field '${field}'`);
}
}
function validateSession(value: Bar1mSession): void {
if (typeof value !== 'string' || value.length === 0) {
throw new IlpV2EncodeError('empty-symbol', 'session', "empty ILP symbol field 'session'");
}
if (value !== 'PRE' && value !== 'RTH' && value !== 'POST') {
throw new IlpV2EncodeError(
'invalid-session',
'session',
`invalid ILP session '${String(value)}' (expected PRE, RTH, or POST)`,
String(value)
);
}
}
function validateListingId(value: number): void {
if (
typeof value !== 'number' ||
!Number.isInteger(value) ||
value < INT32_MIN ||
value > INT32_MAX
) {
throw new IlpV2EncodeError(
'invalid-listing-id',
'listing_id',
`invalid ILP listing_id '${String(value)}' (expected signed 32-bit integer)`,
value
);
}
}
function validateFiniteDouble(field: string, value: number): void {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new IlpV2EncodeError(
'non-finite-double',
field,
`non-finite ILP double field '${field}': ${String(value)}`,
value
);
}
}
function validateInt64Timestamp(field: string, value: bigint): void {
if (typeof value !== 'bigint' || value < INT64_MIN || value > INT64_MAX) {
throw new IlpV2EncodeError(
'timestamp-out-of-range',
field,
`ILP timestamp '${field}' out of signed 64-bit range: ${String(value)}`,
typeof value === 'bigint' ? value : undefined
);
}
}
function validateDesignatedTimestamp(field: string, value: bigint): void {
validateInt64Timestamp(field, value);
if (value < 0n) {
throw new IlpV2EncodeError(
'negative-timestamp',
field,
`negative ILP designated timestamp '${field}': ${value.toString(10)} (must be >= 0)`,
value
);
}
}
function needsSymbolEscape(byte: number): boolean {
return (
byte === BYTE_SPACE ||
byte === BYTE_COMMA ||
byte === BYTE_EQUALS ||
byte === BYTE_LF ||
byte === BYTE_CR ||
byte === BYTE_BACKSLASH
);
}
/**
* Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`.
*/
function encodeEscapedSymbol(value: string): Uint8Array {
const raw = textEncoder.encode(value);
let extra = 0;
for (const b of raw) {
if (needsSymbolEscape(b)) {
extra += 1;
}
}
if (extra === 0) {
return raw;
}
const escaped = new Uint8Array(raw.length + extra);
let out = 0;
for (const b of raw) {
if (needsSymbolEscape(b)) {
escaped[out++] = BYTE_BACKSLASH;
}
escaped[out++] = b;
}
return escaped;
}
function writeBinaryDoubleField(
out: Uint8Array,
view: DataView,
offset: number,
prefix: Uint8Array,
value: number
): number {
out.set(prefix, offset);
const typeOffset = offset + prefix.byteLength;
out[typeOffset] = ILP_V2_DOUBLE_TYPE;
view.setFloat64(typeOffset + 1, value, true);
return typeOffset + 9;
}
/**
* Encodes one curated `bars_1m` row in QuestDB ILP v2 format.
*
* Wire contract (byte-for-byte parity with `tools/curate-etl/src/ilp.rs::encode_bar_1m`):
* - Table `bars_1m`
* - Symbols `listing_id` (decimal), `session` (`PRE`/`RTH`/`POST`), `source` (escaped)
* - Binary IEEE-754 little-endian doubles `open`, `high`, `low`, `close`, `volume` (`vwap` omitted)
* - Timestamp column `known_at=<epoch_micros>t` (signed 64-bit integer preserved as supplied)
* - Designated timestamp ` <epoch_micros>t\n` (non-negative signed 64-bit integer)
*/
export function encodeBar1mIlpV2(row: Bar1mIlpV2Row): Uint8Array {
validateListingId(row.listing_id);
validateSession(row.session);
validateNonEmptySymbol('source', row.source);
validateFiniteDouble('open', row.open);
validateFiniteDouble('high', row.high);
validateFiniteDouble('low', row.low);
validateFiniteDouble('close', row.close);
validateFiniteDouble('volume', row.volume);
validateInt64Timestamp('known_at', row.known_at);
validateDesignatedTimestamp('ts', row.ts);
const listingIdDecimal = row.listing_id === 0 ? '0' : String(row.listing_id);
const prefixBytes = textEncoder.encode(
`${TABLE_BARS_1M},listing_id=${listingIdDecimal},session=${row.session},source=`
);
const escapedSourceBytes = encodeEscapedSymbol(row.source);
const suffixBytes = textEncoder.encode(
`,known_at=${row.known_at.toString(10)}t ${row.ts.toString(10)}t\n`
);
// Binary doubles section: ' open==\x10<8>,high==\x10<8>,low==\x10<8>,close==\x10<8>,volume==\x10<8>'
const binaryFieldsLen =
BARS_1M_OPEN_PREFIX.byteLength +
9 +
HIGH_PREFIX.byteLength +
9 +
LOW_PREFIX.byteLength +
9 +
CLOSE_PREFIX.byteLength +
9 +
VOLUME_PREFIX.byteLength +
9;
const out = new Uint8Array(
prefixBytes.byteLength + escapedSourceBytes.byteLength + binaryFieldsLen + suffixBytes.byteLength
);
const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
let offset = 0;
out.set(prefixBytes, offset);
offset += prefixBytes.byteLength;
out.set(escapedSourceBytes, offset);
offset += escapedSourceBytes.byteLength;
offset = writeBinaryDoubleField(out, view, offset, BARS_1M_OPEN_PREFIX, row.open);
offset = writeBinaryDoubleField(out, view, offset, HIGH_PREFIX, row.high);
offset = writeBinaryDoubleField(out, view, offset, LOW_PREFIX, row.low);
offset = writeBinaryDoubleField(out, view, offset, CLOSE_PREFIX, row.close);
offset = writeBinaryDoubleField(out, view, offset, VOLUME_PREFIX, row.volume);
out.set(suffixBytes, offset);
return out;
}
/**
* Encodes one `fx_1m` row in QuestDB ILP v2 format.
*
* Wire contract (byte-for-byte parity with `tools/curate-etl/src/ilp.rs::encode_fx_1m`):
* - Table `fx_1m`
* - Symbols `pair` (escaped), `source` (escaped)
* - Binary IEEE-754 little-endian doubles `open`, `high`, `low`, `close`
* - Designated timestamp ` <epoch_micros>t\n` (non-negative signed 64-bit integer)
*/
export function encodeFx1mIlpV2(row: Fx1mIlpV2Row): Uint8Array {
validateNonEmptySymbol('pair', row.pair);
validateNonEmptySymbol('source', row.source);
validateFiniteDouble('open', row.open);
validateFiniteDouble('high', row.high);
validateFiniteDouble('low', row.low);
validateFiniteDouble('close', row.close);
validateDesignatedTimestamp('ts', row.ts);
const escapedPairBytes = encodeEscapedSymbol(row.pair);
const escapedSourceBytes = encodeEscapedSymbol(row.source);
const suffixBytes = textEncoder.encode(` ${row.ts.toString(10)}t\n`);
const binaryFieldsLen =
BARS_1M_OPEN_PREFIX.byteLength +
9 +
HIGH_PREFIX.byteLength +
9 +
LOW_PREFIX.byteLength +
9 +
CLOSE_PREFIX.byteLength +
9;
const out = new Uint8Array(
FX_1M_PREFIX.byteLength +
escapedPairBytes.byteLength +
FX_1M_SOURCE_PREFIX.byteLength +
escapedSourceBytes.byteLength +
binaryFieldsLen +
suffixBytes.byteLength
);
const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
let offset = 0;
out.set(FX_1M_PREFIX, offset);
offset += FX_1M_PREFIX.byteLength;
out.set(escapedPairBytes, offset);
offset += escapedPairBytes.byteLength;
out.set(FX_1M_SOURCE_PREFIX, offset);
offset += FX_1M_SOURCE_PREFIX.byteLength;
out.set(escapedSourceBytes, offset);
offset += escapedSourceBytes.byteLength;
offset = writeBinaryDoubleField(out, view, offset, BARS_1M_OPEN_PREFIX, row.open);
offset = writeBinaryDoubleField(out, view, offset, HIGH_PREFIX, row.high);
offset = writeBinaryDoubleField(out, view, offset, LOW_PREFIX, row.low);
offset = writeBinaryDoubleField(out, view, offset, CLOSE_PREFIX, row.close);
out.set(suffixBytes, offset);
return out;
}
function assertPositiveIntegerOption(name: string, value: number): void {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
throw new RangeError(`ILP v2 batch writer option '${name}' must be a positive integer`);
}
}
/**
* Creates a pure, sink-injected QuestDB ILP v2 batch writer for `bars_1m` and `fx_1m`.
*
* Operations are serialized in call order so overlapping calls never reorder rows or overlap
* sink writes. Batches always end on whole-row boundaries, fail closed on sink errors, and
* reject writes after `finish()`.
*/
export function createIlpV2BatchWriter(options: IlpV2BatchWriterOptions): IlpV2BatchWriter {
if (!options || !options.sink || typeof options.sink.write !== 'function') {
throw new TypeError('ILP v2 batch writer requires a sink with a write(batch) method');
}
const maxBatchBytes = options.maxBatchBytes ?? DEFAULT_ILP_MAX_BATCH_BYTES;
const maxBatchRows = options.maxBatchRows ?? DEFAULT_ILP_MAX_BATCH_ROWS;
assertPositiveIntegerOption('maxBatchBytes', maxBatchBytes);
assertPositiveIntegerOption('maxBatchRows', maxBatchRows);
const { sink } = options;
const pendingChunks: Uint8Array[] = [];
let pendingBytes = 0;
let pendingRows = 0;
let writtenRows = 0;
let writtenBatches = 0;
let writtenBytes = 0;
let finished = false;
let hasSinkFailure = false;
let sinkFailure: unknown = null;
let queueTail: Promise<void> = Promise.resolve();
function enqueue<T>(operation: () => Promise<T>): Promise<T> {
const result = queueTail.then(operation, operation);
queueTail = result.then(
() => undefined,
() => undefined
);
return result;
}
function assertHealthyForMutation(action: string): void {
if (hasSinkFailure) {
throw new Error(`ILP v2 batch writer is closed after a sink write failure (${action})`, {
cause: sinkFailure,
});
}
if (finished) {
throw new Error(`ILP v2 batch writer is already finished (${action})`);
}
}
async function flushPending(): Promise<void> {
if (pendingChunks.length === 0) {
return;
}
const batch = new Uint8Array(pendingBytes);
let offset = 0;
for (const chunk of pendingChunks) {
batch.set(chunk, offset);
offset += chunk.byteLength;
}
const rowCount = pendingRows;
const byteCount = pendingBytes;
try {
await sink.write(batch);
} catch (error) {
hasSinkFailure = true;
sinkFailure = error;
pendingChunks.length = 0;
pendingBytes = 0;
pendingRows = 0;
throw error;
}
pendingChunks.length = 0;
pendingBytes = 0;
pendingRows = 0;
writtenRows += rowCount;
writtenBatches += 1;
writtenBytes += byteCount;
}
async function enqueueEncodedRow(encoded: Uint8Array): Promise<void> {
if (pendingChunks.length > 0 && pendingBytes + encoded.byteLength > maxBatchBytes) {
await flushPending();
}
pendingChunks.push(encoded);
pendingBytes += encoded.byteLength;
pendingRows += 1;
if (pendingRows >= maxBatchRows || pendingBytes >= maxBatchBytes) {
await flushPending();
}
}
function snapshotBar1mRow(row: Bar1mIlpV2Row): Bar1mIlpV2Row {
return {
listing_id: row.listing_id,
ts: row.ts,
known_at: row.known_at,
open: row.open,
high: row.high,
low: row.low,
close: row.close,
volume: row.volume,
session: row.session,
source: row.source,
};
}
function snapshotFx1mRow(row: Fx1mIlpV2Row): Fx1mIlpV2Row {
return {
pair: row.pair,
source: row.source,
open: row.open,
high: row.high,
low: row.low,
close: row.close,
ts: row.ts,
};
}
return {
writeBar1m(row: Bar1mIlpV2Row): Promise<void> {
const snapshot = snapshotBar1mRow(row);
return enqueue(async () => {
assertHealthyForMutation('writeBar1m');
const encoded = encodeBar1mIlpV2(snapshot);
await enqueueEncodedRow(encoded);
});
},
writeFx1m(row: Fx1mIlpV2Row): Promise<void> {
const snapshot = snapshotFx1mRow(row);
return enqueue(async () => {
assertHealthyForMutation('writeFx1m');
const encoded = encodeFx1mIlpV2(snapshot);
await enqueueEncodedRow(encoded);
});
},
flush(): Promise<void> {
return enqueue(async () => {
assertHealthyForMutation('flush');
await flushPending();
});
},
finish(): Promise<IlpV2BatchWriterStats> {
return enqueue(async () => {
assertHealthyForMutation('finish');
await flushPending();
finished = true;
return {
rows: writtenRows,
batches: writtenBatches,
bytes: writtenBytes,
};
});
},
};
}

View file

@ -5,56 +5,27 @@
* InfluxDB Line Protocol, SQL queries, and PostgreSQL wire protocol.
*/
export { QuestDBClient, readBars1m } from './client';
export { QuestDBClient } from './client';
export { QuestDBHealthMonitor } from './health';
export { QuestDBQueryBuilder } from './query-builder';
export { QuestDBInfluxWriter } from './influx-writer';
export {
createIlpV2BatchWriter,
DEFAULT_ILP_MAX_BATCH_BYTES,
DEFAULT_ILP_MAX_BATCH_ROWS,
encodeBar1mIlpV2,
encodeFx1mIlpV2,
ILP_V2_DOUBLE_TYPE,
IlpV2EncodeError,
type Bar1mIlpV2Row,
type Bar1mSession,
type Fx1mIlpV2Row,
type IlpV2BatchSink,
type IlpV2BatchWriter,
type IlpV2BatchWriterOptions,
type IlpV2BatchWriterStats,
type IlpV2EncodeErrorKind,
} from './ilp-v2-writer';
export {
formatCreateTableSQL,
getM2IntradayDDL,
M2_INTRADAY_SCHEMAS,
QuestDBSchemaManager,
type M2IntradayTableName,
} from './schema';
export { QuestDBSchemaManager } from './schema';
// Types
export type {
Bar1mRow,
ColumnSchema,
InsertResult,
LatestByOptions,
OHLCVData,
ParameterizedQuery,
PerformanceData,
QueryResult,
QuestDBClientConfig,
QuestDBConnectionOptions,
QuestDBHealthStatus,
QuestDBMetrics,
QuestDBQueryable,
QuoteData,
RiskMetrics,
TableNames,
TableSchema,
OHLCVData,
TradeData,
QuoteData,
IndicatorData,
PerformanceData,
RiskMetrics,
QueryResult,
InsertResult,
} from './types';
// Note: Factory functions removed - instantiate directly with new QuestDBClient()

View file

@ -11,9 +11,6 @@ interface QuestDBClientInterface {
*
* Provides high-performance data ingestion using InfluxDB Line Protocol
* which QuestDB supports natively for optimal time-series data insertion.
*
* @deprecated Legacy text-ILP writer. Use `createIlpV2BatchWriter` (from `./ilp-v2-writer`)
* for QuestDB ILP v2 binary-double ingestion into `bars_1m` and `fx_1m`.
*/
export class QuestDBInfluxWriter {
private readonly logger: ReturnType<typeof getLogger>;

View file

@ -1,272 +1,32 @@
import type { QueryResultRow } from 'pg';
import { getLogger } from '@stock-bot/logger';
import type {
ParameterizedQuery,
QueryResult,
QuestDBQueryable,
TableNames,
TimeRange,
} from './types';
import type { QueryResult, TableNames, TimeRange } from './types';
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;
// Interface to avoid circular dependency
interface QuestDBClientInterface {
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
}
/**
* QuestDB Query Builder
*
* Provides a fluent interface for building parameterized PGWire time-series queries
* with support for QuestDB 10.2.0 SQL clauses (`LATEST ON`, `SAMPLE BY`).
* Provides a fluent interface for building optimized time-series queries
* with support for QuestDB-specific functions and optimizations.
*/
export class QuestDBQueryBuilder {
private readonly logger: ReturnType<typeof getLogger>;
private query!: {
select: string[];
from: string;
where: WherePredicate[];
where: string[];
groupBy: string[];
orderBy: string[];
limit?: number;
sampleBy?: string;
latestOn?: LatestOnClause;
latestBy?: string[];
timeRange?: TimeRange;
};
constructor(private readonly client: QuestDBQueryable) {
constructor(private readonly client: QuestDBClientInterface) {
this.logger = getLogger('questdb-query-builder');
this.reset();
}
@ -281,263 +41,193 @@ export class QuestDBQueryBuilder {
where: [],
groupBy: [],
orderBy: [],
limit: undefined,
sampleBy: undefined,
latestOn: undefined,
latestBy: undefined,
timeRange: undefined,
};
return this;
}
/**
* Start a new query
*/
public static create(client: QuestDBQueryable): QuestDBQueryBuilder {
public static create(client: QuestDBClientInterface): QuestDBQueryBuilder {
return new QuestDBQueryBuilder(client);
}
/**
* Select columns (`*` or validated SQL identifiers)
* Select columns
*/
public select(...columns: string[]): QuestDBQueryBuilder {
const validated = columns.map(col => assertSelectColumn(col));
this.query.select.push(...validated);
this.query.select.push(...columns);
return this;
}
/**
* Select with aggregation functions.
* Aliases are validated as SQL identifiers; aggregation expressions are treated as trusted SQL fragments.
* Select with aggregation functions
*/
public selectAgg(aggregations: Record<string, string>): QuestDBQueryBuilder {
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}`;
Object.entries(aggregations).forEach(([alias, expression]) => {
this.query.select.push(`${expression} as ${alias}`);
});
this.query.select.push(...validatedEntries);
return this;
}
/**
* From table (validated SQL identifier)
* From table
*/
public from(table: TableNames | string): QuestDBQueryBuilder {
this.query.from = assertIdentifier(table, 'table name');
this.query.from = table;
return this;
}
/**
* Raw WHERE predicate (trusted SQL fragment escape hatch).
* Supports fragment-local `$1..$n` placeholders, which are renumbered automatically during build.
* Where condition
*/
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 });
public where(condition: string): QuestDBQueryBuilder {
this.query.where.push(condition);
return this;
}
/**
* Where symbol equals (bound parameter)
* Where symbol equals
*/
public whereSymbol(symbol: string): QuestDBQueryBuilder {
this.query.where.push({ sql: 'symbol = $1', params: [symbol] });
this.query.where.push(`symbol = '${symbol}'`);
return this;
}
/**
* Where symbols in list (one bound parameter per element; rejects empty lists)
* Where symbols in list
*/
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],
});
const symbolList = symbols.map(s => `'${s}'`).join(', ');
this.query.where.push(`symbol IN (${symbolList})`);
return this;
}
/**
* Where exchange equals (bound parameter)
* Where exchange equals
*/
public whereExchange(exchange: string): QuestDBQueryBuilder {
this.query.where.push({ sql: 'exchange = $1', params: [exchange] });
this.query.where.push(`exchange = '${exchange}'`);
return this;
}
/**
* Time range filter with inclusive bounds (bound UTC ISO-8601 parameters)
* Time range filter
*/
public whereTimeRange(startTime: Date, endTime: Date): QuestDBQueryBuilder {
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()],
});
this.query.timeRange = { startTime, endTime };
this.query.where.push(
`timestamp >= '${startTime.toISOString()}' AND timestamp <= '${endTime.toISOString()}'`
);
return this;
}
/**
* Last N hours (bound negative hour offset)
* Last N hours
*/
public whereLastHours(hours: number): QuestDBQueryBuilder {
const validHours = assertPositiveInteger(hours, 'hours');
this.query.where.push({
sql: "timestamp > dateadd('h', $1, now())",
params: [-validHours],
});
this.query.where.push(`timestamp > dateadd('h', -${hours}, now())`);
return this;
}
/**
* Last N days (bound negative day offset)
* Last N days
*/
public whereLastDays(days: number): QuestDBQueryBuilder {
const validDays = assertPositiveInteger(days, 'days');
this.query.where.push({
sql: "timestamp > dateadd('d', $1, now())",
params: [-validDays],
});
this.query.where.push(`timestamp > dateadd('d', -${days}, now())`);
return this;
}
/**
* Group by columns (validated SQL identifiers)
* Group by columns
*/
public groupBy(...columns: string[]): QuestDBQueryBuilder {
const validated = columns.map(col => assertIdentifier(col, 'GROUP BY column'));
this.query.groupBy.push(...validated);
this.query.groupBy.push(...columns);
return this;
}
/**
* Order by column (validated identifier and direction)
* Order by column
*/
public orderBy(column: string, direction: 'ASC' | 'DESC' = 'ASC'): QuestDBQueryBuilder {
const validColumn = assertIdentifier(column, 'ORDER BY column');
const validDirection = assertSortDirection(direction);
this.query.orderBy.push(`${validColumn} ${validDirection}`);
this.query.orderBy.push(`${column} ${direction}`);
return this;
}
/**
* Order by timestamp descending (most recent first)
*/
public orderByTimeDesc(timestampColumn: string = 'timestamp'): QuestDBQueryBuilder {
const validColumn = assertIdentifier(timestampColumn, 'ORDER BY column');
this.query.orderBy.push(`${validColumn} DESC`);
public orderByTimeDesc(): QuestDBQueryBuilder {
this.query.orderBy.push('timestamp DESC');
return this;
}
/**
* Limit results (bound non-negative integer parameter)
* Limit results
*/
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, validated interval)
* Sample by time interval (QuestDB specific)
*/
public sampleBy(interval: string): QuestDBQueryBuilder {
this.query.sampleBy = assertSampleInterval(interval);
this.query.sampleBy = interval;
return this;
}
/**
* QuestDB 10.2.0 `LATEST ON <timestamp> PARTITION BY <keys>` with explicit timestamp column.
* Latest by columns (QuestDB specific)
*/
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,
};
public latestBy(...columns: string[]): QuestDBQueryBuilder {
this.query.latestBy = columns;
return this;
}
/**
* 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
* Build and execute the query
*/
public async execute<T = QueryResultRow>(): Promise<QueryResult<T>> {
let built: ParameterizedQuery | undefined;
const sql = this.build();
this.logger.debug('Executing query', { sql });
try {
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);
const result = await this.client.query<T>(sql);
this.reset(); // Reset for next query
return result;
} catch (error) {
this.logger.error('Query execution failed', { sql: built?.sql, error });
this.logger.error('Query execution failed', { sql, error });
this.reset(); // Reset even on error
throw error;
} finally {
this.reset();
}
}
/**
* Build the parameterized SQL query and ordered parameter list (`$1..$n`).
* Build the SQL query string
*/
public buildParameterized(): ParameterizedQuery {
public build(): string {
if (!this.query.from) {
throw new Error('FROM clause is required');
}
const selectColumns = this.query.select.length > 0 ? this.query.select : ['*'];
const params: unknown[] = [];
let sql = `SELECT ${selectColumns.join(', ')} FROM ${this.query.from}`;
// Add WHERE clause with consecutively renumbered $1..$n placeholders
if (this.query.where.length > 0) {
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 ')}`;
if (this.query.select.length === 0) {
this.query.select.push('*');
}
// 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(', ')}`;
let sql = `SELECT ${this.query.select.join(', ')} FROM ${this.query.from}`;
// Add WHERE clause
if (this.query.where.length > 0) {
sql += ` WHERE ${this.query.where.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 SAMPLE BY (QuestDB specific)
@ -555,36 +245,27 @@ export class QuestDBQueryBuilder {
sql += ` ORDER BY ${this.query.orderBy.join(', ')}`;
}
// Add LIMIT (bound parameter)
if (this.query.limit !== undefined) {
params.push(this.query.limit);
sql += ` LIMIT $${params.length}`;
// Add LIMIT
if (this.query.limit) {
sql += ` LIMIT ${this.query.limit}`;
}
return { sql, params };
return sql;
}
/**
* Build the SQL query string (placeholder view of `buildParameterized().sql`)
*/
public build(): string {
return this.buildParameterized().sql;
}
/**
* Get the built query string without executing
* Get the built query 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: QuestDBQueryable,
client: QuestDBClientInterface,
symbols: string[],
exchange?: string
): QuestDBQueryBuilder {
@ -601,12 +282,11 @@ export class QuestDBQueryBuilder {
return builder;
}
/**
* Get OHLCV data with time sampling
*/
public static ohlcvTimeSeries(
client: QuestDBQueryable,
client: QuestDBClientInterface,
symbol: string,
interval: string,
hours: number = 24
@ -625,12 +305,11 @@ export class QuestDBQueryBuilder {
.sampleBy(interval)
.orderByTimeDesc();
}
/**
* Get market analytics data
*/
public static marketAnalytics(
client: QuestDBQueryable,
client: QuestDBClientInterface,
symbols: string[],
hours: number = 1
): QuestDBQueryBuilder {
@ -650,12 +329,11 @@ export class QuestDBQueryBuilder {
.orderBy('symbol')
.orderByTimeDesc();
}
/**
* Get performance metrics for a time range
*/
public static performanceMetrics(
client: QuestDBQueryable,
client: QuestDBClientInterface,
startTime: Date,
endTime: Date
): QuestDBQueryBuilder {
@ -670,12 +348,11 @@ export class QuestDBQueryBuilder {
.whereTimeRange(startTime, endTime)
.sampleBy('1m');
}
/**
* Get trade execution data
*/
public static tradeExecutions(
client: QuestDBQueryable,
client: QuestDBClientInterface,
symbol?: string,
hours: number = 24
): QuestDBQueryBuilder {

View file

@ -1,147 +1,11 @@
import type { QueryResultRow } from 'pg';
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import { assertIdentifier } from './query-builder';
import type { ColumnSchema, QuestDBQueryable, TableSchema } from './types';
import type { QueryResult, TableSchema } from './types';
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),
};
// Interface to avoid circular dependency
interface QuestDBClientInterface {
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
}
/**
@ -153,7 +17,7 @@ export function getM2IntradayDDL(): Record<M2IntradayTableName, string> {
export class QuestDBSchemaManager {
private readonly logger: ReturnType<typeof getLogger>;
private readonly schemas: Map<string, TableSchema> = new Map();
constructor(private readonly client: QuestDBQueryable) {
constructor(private readonly client: QuestDBClientInterface) {
this.logger = getLogger('questdb-schema-manager');
this.initializeSchemas();
}
@ -331,14 +195,13 @@ export class QuestDBSchemaManager {
* Drop a table
*/
public async dropTable(tableName: string): Promise<void> {
const validTable = assertIdentifier(tableName, 'table name');
const sql = `DROP TABLE IF EXISTS ${validTable}`;
const sql = `DROP TABLE IF EXISTS ${tableName}`;
try {
await this.client.query(sql);
this.logger.warn(`Table ${validTable} dropped`);
this.logger.warn(`Table ${tableName} dropped`);
} catch (error) {
this.logger.error(`Failed to drop table ${validTable}`, error);
this.logger.error(`Failed to drop table ${tableName}`, error);
throw error;
}
}
@ -348,12 +211,13 @@ export class QuestDBSchemaManager {
*/
public async tableExists(tableName: string): Promise<boolean> {
try {
const result = await this.client.query<{ count: number | string }>(
'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1',
[tableName]
);
const result = await this.client.query(`
SELECT COUNT(*) as count
FROM information_schema.tables
WHERE table_name = '${tableName}'
`);
return result.rows.length > 0 && Number(at(result.rows, 0).count) > 0;
return result.rows.length > 0 && at(result.rows, 0).count > 0;
} catch (error) {
this.logger.error(`Error checking if table exists: ${tableName}`, error);
return false;
@ -405,19 +269,18 @@ 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 ${validTable}
FROM ${tableName}
`);
return result.rows[0] || {};
} catch (error) {
this.logger.error(`Failed to get table stats for ${validTable}`, error);
this.logger.error(`Failed to get table stats for ${tableName}`, error);
throw error;
}
}
@ -426,12 +289,11 @@ 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 ${validTable}`);
this.logger.warn(`Table ${validTable} truncated`);
await this.client.query(`TRUNCATE TABLE ${tableName}`);
this.logger.warn(`Table ${tableName} truncated`);
} catch (error) {
this.logger.error(`Failed to truncate table ${validTable}`, error);
this.logger.error(`Failed to truncate table ${tableName}`, error);
throw error;
}
}
@ -449,7 +311,27 @@ export class QuestDBSchemaManager {
* Build CREATE TABLE SQL statement
*/
private buildCreateTableSQL(schema: TableSchema): string {
return formatCreateTableSQL(schema);
// 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;
}
/**

View file

@ -62,54 +62,7 @@ export type TableNames =
| 'risk_metrics'
| 'market_events'
| 'strategy_signals'
| '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;
}
| 'portfolio_snapshots';
/**
* Time-Series Data Types
@ -261,14 +214,12 @@ export interface TableSchema {
tableName: string;
columns: ColumnSchema[];
partitionBy?: 'NONE' | 'HOUR' | 'DAY' | 'MONTH' | 'YEAR';
wal?: boolean;
dedupUpsertKeys?: string[];
orderBy?: string[];
indices?: IndexDefinition[];
dedup?: boolean;
}
export interface ColumnSchema {
interface ColumnSchema {
name: string;
type:
| 'SYMBOL'
@ -284,7 +235,6 @@ export 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

@ -1,426 +0,0 @@
import { describe, expect, it } from 'bun:test';
import {
createIlpV2BatchWriter,
DEFAULT_ILP_MAX_BATCH_BYTES,
DEFAULT_ILP_MAX_BATCH_ROWS,
encodeBar1mIlpV2,
encodeFx1mIlpV2,
IlpV2EncodeError,
type Bar1mIlpV2Row,
type Bar1mSession,
type Fx1mIlpV2Row,
type IlpV2BatchSink,
} from '../src/index';
const encoder = new TextEncoder();
function asciiBytes(text: string): number[] {
return Array.from(encoder.encode(text));
}
function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
const total = chunks.reduce((sum, c) => sum + c.byteLength, 0);
const out = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
out.set(chunk, offset);
offset += chunk.byteLength;
}
return out;
}
function sampleBar(overrides: Partial<Bar1mIlpV2Row> = {}): Bar1mIlpV2Row {
return {
listing_id: 42,
ts: 1_736_951_400_000_000n,
known_at: 1_736_951_460_000_000n,
open: 123.45,
high: 125.75,
low: 122.125,
close: 124.5,
volume: 98_765.0,
session: 'RTH',
source: 'eod_unadj',
...overrides,
};
}
function sampleFx(overrides: Partial<Fx1mIlpV2Row> = {}): Fx1mIlpV2Row {
return {
pair: 'USD.CAD',
source: 'eod',
open: 1.3625,
high: 1.365,
low: 1.36125,
close: 1.364375,
ts: 1_736_951_400_000_000n,
...overrides,
};
}
function expectEncodeError(fn: () => unknown, kind: IlpV2EncodeError['kind'], field: string) {
let caught: unknown;
try {
fn();
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(IlpV2EncodeError);
expect((caught as IlpV2EncodeError).kind).toBe(kind);
expect((caught as IlpV2EncodeError).field).toBe(field);
}
describe('ILP v2 encoder edge cases', () => {
it('matches golden_bytes_literal_ieee754_little_endian_without_to_le_bytes with hand-written bytes', () => {
// Mirrors `golden_bytes_literal_ieee754_little_endian_without_to_le_bytes`
// in `tools/curate-etl/src/ilp_tests.rs` (key 7, source eod_unadj).
const actual = encodeBar1mIlpV2({
listing_id: 7,
ts: 1_700_000_000_000_000n,
known_at: 1_700_000_060_000_000n,
open: 1.0,
high: 2.0,
low: 0.5,
close: 1.5,
volume: 0.0,
session: 'RTH',
source: 'eod_unadj',
});
const expected = new Uint8Array([
...asciiBytes('bars_1m,listing_id=7,session=RTH,source=eod_unadj '),
...asciiBytes('open=='),
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xf0,
0x3f,
...asciiBytes(',high=='),
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x40,
...asciiBytes(',low=='),
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xe0,
0x3f,
...asciiBytes(',close=='),
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xf8,
0x3f,
...asciiBytes(',volume=='),
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
...asciiBytes(',known_at=1700000060000000t 1700000000000000t\n'),
]);
expect(actual).toEqual(expected);
});
it('preserves the negative-zero sign bit like Rust f64::to_le_bytes and emits -0 listing_id as 0', () => {
const bytes = encodeBar1mIlpV2(sampleBar({ listing_id: -0, volume: -0 }));
expect(Array.from(bytes.slice(0, 22))).toEqual(asciiBytes('bars_1m,listing_id=0,s'));
const volumePrefix = encoder.encode(',volume==');
const suffix = encoder.encode(',known_at=1736951460000000t 1736951400000000t\n');
const volStart = bytes.byteLength - suffix.byteLength - 9 - volumePrefix.byteLength;
expect(bytes.slice(volStart, volStart + volumePrefix.byteLength)).toEqual(volumePrefix);
expect(
Array.from(
bytes.slice(volStart + volumePrefix.byteLength, volStart + volumePrefix.byteLength + 9)
)
).toEqual([0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]);
});
it('encodes extreme finite doubles (MAX_VALUE, MIN_VALUE subnormal, negative) without rejection', () => {
const bytes = encodeFx1mIlpV2(
sampleFx({ open: Number.MAX_VALUE, high: Number.MIN_VALUE, low: -1.5, close: 0 })
);
const head = encoder.encode('fx_1m,pair=USD.CAD,source=eod open==');
expect(bytes.slice(0, head.byteLength)).toEqual(head);
let o = head.byteLength;
// MAX_VALUE = 0x7fefffffffffffff
expect(Array.from(bytes.slice(o, o + 9))).toEqual([
0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0x7f,
]);
o += 9 + ',high=='.length;
// MIN_VALUE = 0x0000000000000001
expect(Array.from(bytes.slice(o, o + 9))).toEqual([
0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
o += 9 + ',low=='.length;
// -1.5 = 0xbff8000000000000
expect(Array.from(bytes.slice(o, o + 9))).toEqual([
0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf,
]);
});
it('returns a fresh buffer per call so mutating one encoding cannot corrupt another', () => {
const row = sampleFx();
const a = encodeFx1mIlpV2(row);
const b = encodeFx1mIlpV2(row);
a.fill(0);
expect(b).toEqual(encodeFx1mIlpV2(row));
expect(b[0]).toBe(0x66); // 'f'
});
it('escapes a symbol consisting only of special characters', () => {
const bytes = encodeFx1mIlpV2(sampleFx({ pair: ' ,=\\\n\r' }));
const expected = encoder.encode('fx_1m,pair=\\ \\,\\=\\\\\\\n\\\r,source=eod open==');
expect(bytes.slice(0, expected.byteLength)).toEqual(expected);
});
it('rejects invalid or empty session tags with a typed error', () => {
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ session: 'rth' as Bar1mSession })),
'invalid-session',
'session'
);
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ session: 'RTH ' as Bar1mSession })),
'invalid-session',
'session'
);
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ session: '' as Bar1mSession })),
'empty-symbol',
'session'
);
});
it('rejects non-bigint timestamps (JS number) instead of silently encoding them', () => {
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ ts: 1_700_000_000_000_000 as unknown as bigint })),
'timestamp-out-of-range',
'ts'
);
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ known_at: 5 as unknown as bigint })),
'timestamp-out-of-range',
'known_at'
);
expectEncodeError(
() => encodeFx1mIlpV2(sampleFx({ ts: 0 as unknown as bigint })),
'timestamp-out-of-range',
'ts'
);
});
it('accepts the fx_1m designated timestamp at INT64_MAX', () => {
const max = 2n ** 63n - 1n;
const bytes = encodeFx1mIlpV2(sampleFx({ ts: max }));
const suffix = encoder.encode(` ${max.toString(10)}t\n`);
expect(bytes.slice(bytes.byteLength - suffix.byteLength)).toEqual(suffix);
});
});
describe('createIlpV2BatchWriter edge cases', () => {
it('rejects construction without a usable sink and rejects unsafe-integer limits', () => {
expect(() => createIlpV2BatchWriter(undefined as never)).toThrow(TypeError);
expect(() => createIlpV2BatchWriter({} as never)).toThrow(TypeError);
expect(() => createIlpV2BatchWriter({ sink: {} as IlpV2BatchSink })).toThrow(TypeError);
const sink: IlpV2BatchSink = { write: async () => {} };
expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 2 ** 53 })).toThrow(RangeError);
expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: '5' as unknown as number })).toThrow(
RangeError
);
expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 1, maxBatchRows: 1 })).not.toThrow();
});
it('flushes at DEFAULT_ILP_MAX_BATCH_ROWS when no limits are supplied', async () => {
const batches: Uint8Array[] = [];
const writer = createIlpV2BatchWriter({ sink: { write: async b => void batches.push(b) } });
const row = sampleFx({ ts: 0n });
const rowLen = encodeFx1mIlpV2(row).byteLength;
// Row size keeps 10_000 rows well below the 1 MiB default, so only the row limit triggers.
expect(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS).toBeLessThan(DEFAULT_ILP_MAX_BATCH_BYTES);
for (let i = 0; i < DEFAULT_ILP_MAX_BATCH_ROWS - 1; i++) {
await writer.writeFx1m(row);
}
expect(batches).toHaveLength(0);
await writer.writeFx1m(row);
expect(batches).toHaveLength(1);
expect(batches[0]!.byteLength).toBe(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS);
await writer.writeFx1m(row);
const stats = await writer.finish();
expect(stats).toEqual({
rows: DEFAULT_ILP_MAX_BATCH_ROWS + 1,
batches: 2,
bytes: rowLen * (DEFAULT_ILP_MAX_BATCH_ROWS + 1),
});
});
it('hands the sink a fresh batch buffer per flush so retained batches are never overwritten', async () => {
const retained: Uint8Array[] = [];
const writer = createIlpV2BatchWriter({
sink: { write: async b => void retained.push(b) },
maxBatchRows: 1,
});
const r1 = sampleBar({ listing_id: 1 });
const r2 = sampleBar({ listing_id: 2 });
await writer.writeBar1m(r1);
await writer.writeBar1m(r2);
await writer.finish();
expect(retained[0]).not.toBe(retained[1]);
expect(retained[0]!.buffer).not.toBe(retained[1]!.buffer);
expect(retained).toEqual([encodeBar1mIlpV2(r1), encodeBar1mIlpV2(r2)]);
});
it('a rejected row in the middle of overlapping writes does not block or reorder later queued rows', async () => {
const batches: Uint8Array[] = [];
const writer = createIlpV2BatchWriter({
sink: { write: async b => void batches.push(b.slice()) },
maxBatchRows: 2,
maxBatchBytes: 100_000,
});
const a = sampleBar({ listing_id: 1 });
const c = sampleFx({ pair: 'EUR.USD' });
const d = sampleBar({ listing_id: 4 });
const pa = writer.writeBar1m(a);
const pb = writer.writeBar1m(sampleBar({ high: Number.NaN }));
const pc = writer.writeFx1m(c);
const pd = writer.writeBar1m(d);
const pFinish = writer.finish();
await pa;
await expect(pb).rejects.toBeInstanceOf(IlpV2EncodeError);
await pc;
await pd;
const stats = await pFinish;
const expected = [encodeBar1mIlpV2(a), encodeFx1mIlpV2(c), encodeBar1mIlpV2(d)];
expect(batches).toEqual([concatBytes(expected.slice(0, 2)), expected[2]!]);
expect(stats).toEqual({
rows: 3,
batches: 2,
bytes: expected.reduce((s, e) => s + e.byteLength, 0),
});
});
it('treats a synchronously throwing sink like a rejected write and fails closed', async () => {
const boom = new Error('sync sink failure');
let calls = 0;
const sink: IlpV2BatchSink = {
write(): Promise<void> {
calls += 1;
throw boom;
},
};
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1 });
await expect(writer.writeBar1m(sampleBar())).rejects.toBe(boom);
await expect(writer.writeBar1m(sampleBar())).rejects.toThrow(/sink write failure/i);
await expect(writer.flush()).rejects.toThrow(/sink write failure/i);
expect(calls).toBe(1);
});
it('propagates a sink failure on the finish() tail flush, excludes it from stats, and stays closed', async () => {
const boom = new Error('tail failure');
let calls = 0;
const sink: IlpV2BatchSink = {
async write(): Promise<void> {
calls += 1;
if (calls === 2) {
throw boom;
}
},
};
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 });
await writer.writeBar1m(sampleBar({ listing_id: 1 }));
await writer.writeBar1m(sampleBar({ listing_id: 2 })); // batch 1 OK
await writer.writeBar1m(sampleBar({ listing_id: 3 })); // pending tail
await expect(writer.finish()).rejects.toBe(boom);
expect(calls).toBe(2);
const err = await writer.finish().then(
() => null,
(e: unknown) => e as Error
);
expect(err).toBeInstanceOf(Error);
expect(err!.message).toMatch(/sink write failure/i);
// The original sink error is preserved as the cause for diagnostics.
expect(err!.cause).toBe(boom);
expect(calls).toBe(2);
});
it('flush() on an explicit call propagates sink failure and blocks the tail on finish()', async () => {
const boom = new Error('flush failure');
let calls = 0;
const writer = createIlpV2BatchWriter({
sink: {
async write(): Promise<void> {
calls += 1;
throw boom;
},
},
});
await writer.writeFx1m(sampleFx());
await expect(writer.flush()).rejects.toBe(boom);
await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i);
await expect(writer.finish()).rejects.toThrow(/sink write failure/i);
expect(calls).toBe(1);
});
it('serializes an overlapping explicit flush() behind in-flight writes', async () => {
const order: string[] = [];
let release: (() => void) | null = null;
const writer = createIlpV2BatchWriter({
sink: {
write(b: Uint8Array): Promise<void> {
order.push(`write:${b.byteLength}`);
if (release === null) {
return new Promise<void>(resolve => {
release = resolve;
});
}
return Promise.resolve();
},
},
maxBatchRows: 1,
});
const row = sampleFx();
const len = encodeFx1mIlpV2(row).byteLength;
const p1 = writer.writeFx1m(row);
const pFlush = writer.flush().then(() => order.push('flushed'));
const p2 = writer.writeFx1m(row);
await Promise.resolve();
expect(order).toEqual([`write:${len}`]);
release!();
await Promise.all([p1, pFlush, p2]);
expect(order).toEqual([`write:${len}`, 'flushed', `write:${len}`]);
});
});

View file

@ -1,820 +0,0 @@
import { describe, expect, it } from 'bun:test';
import {
createIlpV2BatchWriter,
DEFAULT_ILP_MAX_BATCH_BYTES,
DEFAULT_ILP_MAX_BATCH_ROWS,
encodeBar1mIlpV2,
encodeFx1mIlpV2,
ILP_V2_DOUBLE_TYPE,
IlpV2EncodeError,
type Bar1mIlpV2Row,
type Fx1mIlpV2Row,
type IlpV2BatchSink,
} from '../src/index';
const encoder = new TextEncoder();
function asciiBytes(text: string): number[] {
return Array.from(encoder.encode(text));
}
function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
const total = chunks.reduce((sum, c) => sum + c.byteLength, 0);
const out = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
out.set(chunk, offset);
offset += chunk.byteLength;
}
return out;
}
function indexOfSubarray(haystack: Uint8Array, needle: Uint8Array): number {
outer: for (let i = 0; i <= haystack.length - needle.length; i++) {
for (let j = 0; j < needle.length; j++) {
if (haystack[i + j] !== needle[j]) {
continue outer;
}
}
return i;
}
return -1;
}
function sampleBar(overrides: Partial<Bar1mIlpV2Row> = {}): Bar1mIlpV2Row {
return {
listing_id: 42,
ts: 1_736_951_400_000_000n,
known_at: 1_736_951_460_000_000n,
open: 123.45,
high: 125.75,
low: 122.125,
close: 124.5,
volume: 98_765.0,
session: 'RTH',
source: 'eod_unadj',
...overrides,
};
}
function sampleFx(overrides: Partial<Fx1mIlpV2Row> = {}): Fx1mIlpV2Row {
return {
pair: 'USD.CAD',
source: 'eod',
open: 1.3625,
high: 1.365,
low: 1.36125,
close: 1.364375,
ts: 1_736_951_400_000_000n,
...overrides,
};
}
function createMemorySink(): { sink: IlpV2BatchSink; batches: Uint8Array[] } {
const batches: Uint8Array[] = [];
const sink: IlpV2BatchSink = {
async write(batch: Uint8Array): Promise<void> {
batches.push(batch.slice());
},
};
return { sink, batches };
}
describe('ILP v2 writer constants', () => {
it('matches Rust tools/curate-etl/src/ilp.rs constants', () => {
expect(ILP_V2_DOUBLE_TYPE).toBe(0x10);
expect(DEFAULT_ILP_MAX_BATCH_BYTES).toBe(1_048_576);
expect(DEFAULT_ILP_MAX_BATCH_ROWS).toBe(10_000);
});
});
describe('ILP v2 byte-parity with tools/curate-etl/src/ilp_tests.rs', () => {
it('matches golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract byte-for-byte', () => {
// Mirrors `golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract`
// in `tools/curate-etl/src/ilp_tests.rs`.
const row: Bar1mIlpV2Row = {
listing_id: 42,
ts: 1_736_951_400_000_000n,
known_at: 1_736_951_460_123_456n,
open: 150.25,
high: 151.75,
low: 149.5,
close: 151.125,
volume: 12_345.0,
session: 'RTH',
source: 'eod_unadj',
};
const actual = encodeBar1mIlpV2(row);
// Expected wire bytes written out literally (little-endian IEEE-754 doubles):
// 150.25 -> 0x4062c80000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x62, 0x40]
// 151.75 -> 0x4062f80000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x62, 0x40]
// 149.5 -> 0x4062b00000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xb0, 0x62, 0x40]
// 151.125 -> 0x4062e40000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xe4, 0x62, 0x40]
// 12345.0 -> 0x40c81c8000000000 -> [0x00, 0x00, 0x00, 0x00, 0x80, 0x1c, 0xc8, 0x40]
const expected = new Uint8Array([
...asciiBytes('bars_1m,listing_id=42,session=RTH,source=eod_unadj open=='),
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0xc8,
0x62,
0x40,
...asciiBytes(',high=='),
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0xf8,
0x62,
0x40,
...asciiBytes(',low=='),
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0xb0,
0x62,
0x40,
...asciiBytes(',close=='),
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0xe4,
0x62,
0x40,
...asciiBytes(',volume=='),
0x10,
0x00,
0x00,
0x00,
0x00,
0x80,
0x1c,
0xc8,
0x40,
...asciiBytes(',known_at=1736951460123456t 1736951400000000t\n'),
]);
expect(actual).toEqual(expected);
expect(indexOfSubarray(actual, encoder.encode('vwap'))).toBe(-1);
// Verify PRE and POST session tags as in the Rust golden test.
const preBytes = encodeBar1mIlpV2({ ...row, session: 'PRE' });
expect(
indexOfSubarray(preBytes, encoder.encode('bars_1m,listing_id=42,session=PRE,source=eod_unadj '))
).toBe(0);
const postBytes = encodeBar1mIlpV2({ ...row, session: 'POST' });
expect(
indexOfSubarray(
postBytes,
encoder.encode('bars_1m,listing_id=42,session=POST,source=eod_unadj ')
)
).toBe(0);
});
it('matches golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract byte-for-byte', () => {
// Mirrors `golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract`
// in `tools/curate-etl/src/ilp_tests.rs`.
const row: Fx1mIlpV2Row = {
pair: 'USD.CAD',
ts: 1_736_951_400_000_000n,
open: 1.3625,
high: 1.365,
low: 1.36125,
close: 1.364375,
source: 'eod',
};
const actual = encodeFx1mIlpV2(row);
// Expected wire bytes written out literally (little-endian IEEE-754 doubles):
// 1.3625 -> 0x3ff5cccccccccccc -> [0xcd, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xf5, 0x3f]
// 1.365 -> 0x3ff5d70a3d70a3d7 -> [0xd7, 0xa3, 0x70, 0x3d, 0x0a, 0xd7, 0xf5, 0x3f]
// 1.36125 -> 0x3ff5c7ae147ae148 -> [0x48, 0xe1, 0x7a, 0x14, 0xae, 0xc7, 0xf5, 0x3f]
// 1.364375 -> 0x3ff5d47ae147ae14 -> [0x14, 0xae, 0x47, 0xe1, 0x7a, 0xd4, 0xf5, 0x3f]
const expected = new Uint8Array([
...asciiBytes('fx_1m,pair=USD.CAD,source=eod open=='),
0x10,
0xcd,
0xcc,
0xcc,
0xcc,
0xcc,
0xcc,
0xf5,
0x3f,
...asciiBytes(',high=='),
0x10,
0xd7,
0xa3,
0x70,
0x3d,
0x0a,
0xd7,
0xf5,
0x3f,
...asciiBytes(',low=='),
0x10,
0x48,
0xe1,
0x7a,
0x14,
0xae,
0xc7,
0xf5,
0x3f,
...asciiBytes(',close=='),
0x10,
0x14,
0xae,
0x47,
0xe1,
0x7a,
0xd4,
0xf5,
0x3f,
...asciiBytes(' 1736951400000000t\n'),
]);
expect(actual).toEqual(expected);
expect(indexOfSubarray(actual, encoder.encode('known_at'))).toBe(-1);
expect(indexOfSubarray(actual, encoder.encode('volume'))).toBe(-1);
expect(indexOfSubarray(actual, encoder.encode('vwap'))).toBe(-1);
});
});
describe('ILP v2 escaping, timestamps, and atomic rejection', () => {
it('escapes all six ILP symbol characters and preserves UTF-8 and signed known_at', () => {
// Mirrors `symbol_escaping_and_non_finite_or_negative_ts_atomic_rejection`
// in `tools/curate-etl/src/ilp_tests.rs`.
const rawSym = 'a b,c=d\\e\nf\rg caf\u00e9';
const expectedEscaped = new Uint8Array([
...asciiBytes('a\\ b\\,c\\=d\\\\e\\\nf\\\rg\\ caf'),
0xc3,
0xa9,
]);
// Rust `encode_bar_1m` writes signed `known_at` via `write_i64_decimal` without rejecting < 0.
const barBytes = encodeBar1mIlpV2(
sampleBar({
listing_id: 7,
ts: 0n,
known_at: -1n,
source: rawSym,
})
);
const expectedBarPrefix = concatBytes([
encoder.encode('bars_1m,listing_id=7,session=RTH,source='),
expectedEscaped,
encoder.encode(' '),
]);
expect(barBytes.slice(0, expectedBarPrefix.byteLength)).toEqual(expectedBarPrefix);
const expectedBarSuffix = encoder.encode(',known_at=-1t 0t\n');
expect(barBytes.slice(barBytes.byteLength - expectedBarSuffix.byteLength)).toEqual(
expectedBarSuffix
);
// Also check signed 64-bit timestamp endpoints and INT32 listing_id endpoints.
const int64Min = -(2n ** 63n);
const int64Max = 2n ** 63n - 1n;
const endpointBar = encodeBar1mIlpV2(
sampleBar({
listing_id: -2_147_483_648,
known_at: int64Min,
ts: int64Max,
})
);
expect(
indexOfSubarray(endpointBar, encoder.encode('bars_1m,listing_id=-2147483648,session=RTH,'))
).toBe(0);
const endpointSuffix = encoder.encode(
`,known_at=${int64Min.toString(10)}t ${int64Max.toString(10)}t\n`
);
expect(endpointBar.slice(endpointBar.byteLength - endpointSuffix.byteLength)).toEqual(
endpointSuffix
);
const maxListingBar = encodeBar1mIlpV2(
sampleBar({
listing_id: 2_147_483_647,
known_at: int64Max,
ts: 0n,
})
);
expect(
indexOfSubarray(maxListingBar, encoder.encode('bars_1m,listing_id=2147483647,session=RTH,'))
).toBe(0);
// FX pair and source escaping.
const fxBytes = encodeFx1mIlpV2(
sampleFx({
pair: rawSym,
source: 'src=1,2 3\\4\n\r',
ts: 123n,
})
);
const expectedFxPrefix = concatBytes([
encoder.encode('fx_1m,pair='),
expectedEscaped,
encoder.encode(',source=src\\=1\\,2\\ 3\\\\4\\\n\\\r '),
]);
expect(fxBytes.slice(0, expectedFxPrefix.byteLength)).toEqual(expectedFxPrefix);
const expectedFxSuffix = encoder.encode(' 123t\n');
expect(fxBytes.slice(fxBytes.byteLength - expectedFxSuffix.byteLength)).toEqual(
expectedFxSuffix
);
});
it('throws typed IlpV2EncodeError for negative ts, int64 overflow, non-finite doubles, empty symbols, and non-int32 listing_id', () => {
const expectEncodeError = (
fn: () => unknown,
kind: IlpV2EncodeError['kind'],
field: string
) => {
try {
fn();
throw new Error('Expected IlpV2EncodeError to be thrown');
} catch (err) {
expect(err).toBeInstanceOf(IlpV2EncodeError);
const encodeErr = err as IlpV2EncodeError;
expect(encodeErr.kind).toBe(kind);
expect(encodeErr.field).toBe(field);
}
};
// Negative designated timestamps.
expectEncodeError(() => encodeBar1mIlpV2(sampleBar({ ts: -1n })), 'negative-timestamp', 'ts');
expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ ts: -42n })), 'negative-timestamp', 'ts');
// Signed 64-bit timestamp overflow / underflow.
const overInt64 = 2n ** 63n;
const underInt64 = -(2n ** 63n) - 1n;
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ ts: overInt64 })),
'timestamp-out-of-range',
'ts'
);
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ ts: underInt64 })),
'timestamp-out-of-range',
'ts'
);
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ known_at: overInt64 })),
'timestamp-out-of-range',
'known_at'
);
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ known_at: underInt64 })),
'timestamp-out-of-range',
'known_at'
);
expectEncodeError(
() => encodeFx1mIlpV2(sampleFx({ ts: overInt64 })),
'timestamp-out-of-range',
'ts'
);
// Non-finite doubles across every double column.
for (const badVal of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) {
for (const field of ['open', 'high', 'low', 'close', 'volume'] as const) {
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ [field]: badVal })),
'non-finite-double',
field
);
}
for (const field of ['open', 'high', 'low', 'close'] as const) {
expectEncodeError(
() => encodeFx1mIlpV2(sampleFx({ [field]: badVal })),
'non-finite-double',
field
);
}
}
// Empty symbols.
expectEncodeError(() => encodeBar1mIlpV2(sampleBar({ source: '' })), 'empty-symbol', 'source');
expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ pair: '' })), 'empty-symbol', 'pair');
expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ source: '' })), 'empty-symbol', 'source');
// Non-INT32 listing_id.
for (const badId of [
1.5,
-0.25,
2_147_483_648,
-2_147_483_649,
Number.NaN,
Number.POSITIVE_INFINITY,
]) {
expectEncodeError(
() => encodeBar1mIlpV2(sampleBar({ listing_id: badId })),
'invalid-listing-id',
'listing_id'
);
}
});
it('rejects invalid rows at a batch boundary without calling sink and preserves pending rows', async () => {
const validRow = sampleBar({ listing_id: 101 });
const validBytes = encodeBar1mIlpV2(validRow);
const { sink, batches } = createMemorySink();
// Limit allows 1 row to sit pending right at the byte boundary so a second valid row would flush.
const writer = createIlpV2BatchWriter({
sink,
maxBatchBytes: validBytes.byteLength + 1,
maxBatchRows: 2,
});
await writer.writeBar1m(validRow);
expect(batches).toHaveLength(0);
// Rejected bar and FX rows must not flush the pending row or write anything to sink.
await expect(writer.writeBar1m(sampleBar({ ts: -1n }))).rejects.toBeInstanceOf(
IlpV2EncodeError
);
await expect(writer.writeBar1m(sampleBar({ volume: Number.NaN }))).rejects.toBeInstanceOf(
IlpV2EncodeError
);
await expect(writer.writeBar1m(sampleBar({ source: '' }))).rejects.toBeInstanceOf(
IlpV2EncodeError
);
await expect(writer.writeBar1m(sampleBar({ listing_id: 3.14 }))).rejects.toBeInstanceOf(
IlpV2EncodeError
);
await expect(writer.writeFx1m(sampleFx({ pair: '' }))).rejects.toBeInstanceOf(IlpV2EncodeError);
await expect(writer.writeFx1m(sampleFx({ ts: -5n }))).rejects.toBeInstanceOf(IlpV2EncodeError);
expect(batches).toHaveLength(0);
// Pending valid row is still intact and flushes cleanly on finish().
const stats = await writer.finish();
expect(stats).toEqual({ rows: 1, batches: 1, bytes: validBytes.byteLength });
expect(batches).toEqual([validBytes]);
});
});
describe('createIlpV2BatchWriter batching, boundaries, and option validation', () => {
it('validates maxBatchBytes and maxBatchRows at construction', () => {
const { sink } = createMemorySink();
for (const invalid of [0, -1, -100, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: invalid })).toThrow(RangeError);
expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: invalid })).toThrow(RangeError);
}
});
it('flushes on exact maxBatchRows, exact maxBatchBytes, pre-overflow, oversized singleton, and explicit/empty flush', async () => {
// Include a finite double whose IEEE-754 LE payload contains 0x0a (LF) and a symbol with LF.
const lfDoubleBuf = new Uint8Array([0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x24, 0x40]);
const doubleWithLf = new DataView(lfDoubleBuf.buffer).getFloat64(0, true);
expect(Number.isFinite(doubleWithLf)).toBe(true);
const row = sampleBar({ open: doubleWithLf, source: 'eod\nwith_lf' });
const oneLine = encodeBar1mIlpV2(row);
const rowLen = oneLine.byteLength;
// 1. Exact row limit (maxBatchRows = 3) + 1 remainder row.
{
const { sink, batches } = createMemorySink();
const writer = createIlpV2BatchWriter({
sink,
maxBatchBytes: 100_000,
maxBatchRows: 3,
});
for (let i = 0; i < 7; i++) {
await writer.writeBar1m(row);
}
const stats = await writer.finish();
expect(stats).toEqual({ rows: 7, batches: 3, bytes: 7 * rowLen });
expect(batches).toHaveLength(3);
expect(batches[0]).toEqual(concatBytes([oneLine, oneLine, oneLine]));
expect(batches[1]).toEqual(concatBytes([oneLine, oneLine, oneLine]));
expect(batches[2]).toEqual(oneLine);
expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true);
}
// 2. Exact byte limit (2 * rowLen): flushes immediately when the 2nd and 4th rows hit the limit.
{
const { sink, batches } = createMemorySink();
const writer = createIlpV2BatchWriter({
sink,
maxBatchBytes: 2 * rowLen,
maxBatchRows: 100,
});
await writer.writeBar1m(row);
expect(batches).toHaveLength(0);
await writer.writeBar1m(row);
expect(batches).toHaveLength(1);
expect(batches[0]).toEqual(concatBytes([oneLine, oneLine]));
await writer.writeBar1m(row);
expect(batches).toHaveLength(1);
await writer.writeBar1m(row);
expect(batches).toHaveLength(2);
expect(batches[1]).toEqual(concatBytes([oneLine, oneLine]));
await writer.writeBar1m(row);
expect(batches).toHaveLength(2);
const stats = await writer.finish();
expect(stats).toEqual({ rows: 5, batches: 3, bytes: 5 * rowLen });
expect(batches).toHaveLength(3);
expect(batches[2]).toEqual(oneLine);
}
// 3. Row would exceed remaining capacity (2 * rowLen - 1): pre-flushes before appending.
{
const { sink, batches } = createMemorySink();
const writer = createIlpV2BatchWriter({
sink,
maxBatchBytes: 2 * rowLen - 1,
maxBatchRows: 100,
});
for (let i = 0; i < 3; i++) {
await writer.writeBar1m(row);
}
const stats = await writer.finish();
expect(stats).toEqual({ rows: 3, batches: 3, bytes: 3 * rowLen });
expect(batches).toEqual([oneLine, oneLine, oneLine]);
}
// 4. Individually oversized row (maxBatchBytes = 16 < rowLen): sent alone, never split.
{
const { sink, batches } = createMemorySink();
const writer = createIlpV2BatchWriter({
sink,
maxBatchBytes: 16,
maxBatchRows: 100,
});
await writer.writeBar1m(row);
await writer.writeBar1m(row);
const stats = await writer.finish();
expect(stats).toEqual({ rows: 2, batches: 2, bytes: 2 * rowLen });
expect(batches).toEqual([oneLine, oneLine]);
}
// 5. Empty flush, explicit flush, and zero-row finish.
{
const { sink, batches } = createMemorySink();
const writer = createIlpV2BatchWriter({ sink, maxBatchBytes: 100_000, maxBatchRows: 10 });
await writer.flush();
expect(batches).toHaveLength(0);
await writer.writeBar1m(row);
await writer.flush();
expect(batches).toEqual([oneLine]);
await writer.flush();
expect(batches).toHaveLength(1);
const stats = await writer.finish();
expect(stats).toEqual({ rows: 1, batches: 1, bytes: rowLen });
}
{
const { sink, batches } = createMemorySink();
const writer = createIlpV2BatchWriter({ sink });
const stats = await writer.finish();
expect(stats).toEqual({ rows: 0, batches: 0, bytes: 0 });
expect(batches).toHaveLength(0);
}
});
it('preserves mixed bars_1m and fx_1m input order and rejects writes after finish()', async () => {
const bar1 = sampleBar({ listing_id: 1, ts: 1_700_000_000_000_000n });
const fx1 = sampleFx({ pair: 'USD.CAD', ts: 1_700_000_060_000_000n });
const bar2 = sampleBar({ listing_id: 2, ts: 1_700_000_120_000_000n });
const fx2 = sampleFx({ pair: 'EUR.USD', ts: 1_700_000_180_000_000n });
const expectedAll = concatBytes([
encodeBar1mIlpV2(bar1),
encodeFx1mIlpV2(fx1),
encodeBar1mIlpV2(bar2),
encodeFx1mIlpV2(fx2),
]);
const { sink, batches } = createMemorySink();
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 });
await writer.writeBar1m(bar1);
await writer.writeFx1m(fx1);
await writer.writeBar1m(bar2);
await writer.writeFx1m(fx2);
const stats = await writer.finish();
expect(stats).toEqual({ rows: 4, batches: 2, bytes: expectedAll.byteLength });
expect(concatBytes(batches)).toEqual(expectedAll);
expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true);
// Writes, flush, and finish after finish() throw without calling sink.
await expect(writer.writeBar1m(bar1)).rejects.toThrow(/already finished/i);
await expect(writer.writeFx1m(fx1)).rejects.toThrow(/already finished/i);
await expect(writer.flush()).rejects.toThrow(/already finished/i);
await expect(writer.finish()).rejects.toThrow(/already finished/i);
expect(batches).toHaveLength(2);
});
});
describe('createIlpV2BatchWriter serialization and fail-closed sink errors', () => {
it('serializes overlapping writes and finish() without overlapping sink calls', async () => {
let inFlight = 0;
let maxInFlight = 0;
const batches: Uint8Array[] = [];
const resolvers: Array<() => void> = [];
const sink: IlpV2BatchSink = {
write(batch: Uint8Array): Promise<void> {
inFlight += 1;
maxInFlight = Math.max(maxInFlight, inFlight);
batches.push(batch.slice());
return new Promise<void>(resolve => {
resolvers.push(() => {
inFlight -= 1;
resolve();
});
});
},
};
const row1 = sampleBar({ listing_id: 1, ts: 1_700_000_000_000_000n });
const row2 = sampleFx({ pair: 'USD.CAD', ts: 1_700_000_060_000_000n });
const row3 = sampleBar({ listing_id: 3, ts: 1_700_000_120_000_000n });
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 });
// Launch overlapping operations without awaiting between calls.
const p1 = writer.writeBar1m(row1);
const p2 = writer.writeFx1m(row2);
const p3 = writer.writeBar1m(row3);
const pFinish = writer.finish();
// Drain queued manual resolutions one by one as each sink.write starts.
await Promise.resolve();
expect(resolvers).toHaveLength(1);
expect(inFlight).toBe(1);
resolvers[0]!();
await p1;
await Promise.resolve();
expect(resolvers).toHaveLength(2);
expect(inFlight).toBe(1);
resolvers[1]!();
await p2;
await Promise.resolve();
expect(resolvers).toHaveLength(3);
expect(inFlight).toBe(1);
resolvers[2]!();
await p3;
const stats = await pFinish;
expect(maxInFlight).toBe(1);
expect(stats).toEqual({
rows: 3,
batches: 3,
bytes:
encodeBar1mIlpV2(row1).byteLength +
encodeFx1mIlpV2(row2).byteLength +
encodeBar1mIlpV2(row3).byteLength,
});
expect(batches).toEqual([
encodeBar1mIlpV2(row1),
encodeFx1mIlpV2(row2),
encodeBar1mIlpV2(row3),
]);
});
it('snapshots row field values at submission when a caller reuses mutable row objects across overlapping writes', async () => {
const { sink, batches } = createMemorySink();
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 });
const mutableBar = sampleBar({
listing_id: 10,
ts: 1_700_000_000_000_000n,
known_at: 1_700_000_060_000_000n,
open: 100.0,
high: 101.0,
low: 99.5,
close: 100.5,
volume: 1_000,
session: 'PRE',
source: 'bar_one',
});
const expectedBar1 = encodeBar1mIlpV2(mutableBar);
const mutableFx = sampleFx({
pair: 'USD.CAD',
source: 'fx_one',
open: 1.35,
high: 1.36,
low: 1.34,
close: 1.355,
ts: 1_700_000_000_000_000n,
});
const expectedFx1 = encodeFx1mIlpV2(mutableFx);
// Submit first bar and FX row without awaiting, then mutate both objects in place.
const pBar1 = writer.writeBar1m(mutableBar);
const pFx1 = writer.writeFx1m(mutableFx);
mutableBar.listing_id = 11;
mutableBar.ts = 1_700_000_060_000_000n;
mutableBar.known_at = 1_700_000_120_000_000n;
mutableBar.open = 200.0;
mutableBar.high = 202.0;
mutableBar.low = 199.0;
mutableBar.close = 201.5;
mutableBar.volume = 2_000;
mutableBar.session = 'RTH';
mutableBar.source = 'bar_two';
const expectedBar2 = encodeBar1mIlpV2(mutableBar);
mutableFx.pair = 'EUR.USD';
mutableFx.source = 'fx_two';
mutableFx.open = 1.08;
mutableFx.high = 1.09;
mutableFx.low = 1.07;
mutableFx.close = 1.085;
mutableFx.ts = 1_700_000_060_000_000n;
const expectedFx2 = encodeFx1mIlpV2(mutableFx);
const pBar2 = writer.writeBar1m(mutableBar);
const pFx2 = writer.writeFx1m(mutableFx);
await Promise.all([pBar1, pFx1, pBar2, pFx2]);
const stats = await writer.finish();
expect(stats).toEqual({
rows: 4,
batches: 4,
bytes:
expectedBar1.byteLength +
expectedFx1.byteLength +
expectedBar2.byteLength +
expectedFx2.byteLength,
});
expect(batches).toEqual([expectedBar1, expectedFx1, expectedBar2, expectedFx2]);
});
it('propagates sink rejection and fails closed for queued and subsequent calls with zero extra sink writes', async () => {
const boom = new Error('simulated sink EPIPE');
let sinkCalls = 0;
const acceptedBatches: Uint8Array[] = [];
let rejectSecondWrite: ((err: Error) => void) | null = null;
const sink: IlpV2BatchSink = {
write(batch: Uint8Array): Promise<void> {
sinkCalls += 1;
if (sinkCalls === 1) {
acceptedBatches.push(batch.slice());
return Promise.resolve();
}
return new Promise<void>((_resolve, reject) => {
rejectSecondWrite = reject;
});
},
};
const row1 = sampleBar({ listing_id: 1 });
const row2 = sampleBar({ listing_id: 2 });
const row3 = sampleBar({ listing_id: 3 });
const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 });
// First batch succeeds.
await writer.writeBar1m(row1);
expect(sinkCalls).toBe(1);
expect(acceptedBatches).toEqual([encodeBar1mIlpV2(row1)]);
// Trigger second batch (in-flight) and queue a third write + finish behind it.
const failingWrite = writer.writeBar1m(row2);
const queuedWrite = writer.writeBar1m(row3);
const queuedFinish = writer.finish();
await Promise.resolve();
expect(sinkCalls).toBe(2);
expect(rejectSecondWrite).not.toBeNull();
rejectSecondWrite!(boom);
// Triggering call receives the exact original error.
await expect(failingWrite).rejects.toBe(boom);
// Queued operations fail closed without invoking sink.write again.
await expect(queuedWrite).rejects.toThrow(/sink write failure/i);
await expect(queuedFinish).rejects.toThrow(/sink write failure/i);
// Later calls also fail closed without invoking sink.write.
await expect(writer.writeBar1m(row3)).rejects.toThrow(/sink write failure/i);
await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i);
await expect(writer.flush()).rejects.toThrow(/sink write failure/i);
await expect(writer.finish()).rejects.toThrow(/sink write failure/i);
expect(sinkCalls).toBe(2);
});
});

View file

@ -1,305 +0,0 @@
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

@ -1,658 +0,0 @@
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,20 +252,19 @@ describe('QuestDB', () => {
const builder = new QuestDBQueryBuilder(mockClient);
const { sql, params } = builder
const query = builder
.select('symbol', 'close', 'volume')
.from('ohlcv_data')
.whereSymbol('AAPL')
.orderBy('timestamp', 'DESC')
.limit(100)
.buildParameterized();
.build();
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]);
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');
});
it('should build query with time range', () => {

View file

@ -74,303 +74,3 @@ Fixed-seed (`20260402`) end-to-end `analyzeSignal` benchmark covering `5,040` bu
- **Command:** `bun run libs/research/scripts/benchmark-signal-study.ts`
- **Observed (Bun 1.2.16):** `elapsedMs = 1691.13 ms`, `rowsPerSec = 8,940,793 rows/s` (`2,980 dates/s`, `nObs = 5040`, `meanRankIc = 0.057294`, `recencyGatePassed = true`)
## DuckDB Curated Parquet Query Planner & `MarketDataStore` Adapter
Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-store-duckdb` (`libs/research/src/market-data-store-duckdb.ts`). The module is dependency-free and browser-safe; DuckDB execution is injected via `DuckDbExecutor` (`{ run(sql), query(sql, params) }`) so parameter values are always bound separately from SQL text.
### API
- **`planBars1dQuery(q, ctx)`** — Plans a fenced query over `<curatedRoot>/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) for `timeframe: '1d'` and `adjustment: 'raw' | 'split' | 'total'`. Rejects `'1m' | '5m' | '1h'` with `MarketDataStoreNotImplementedError`. For `'split'` and `'total'`, requires a verified `point_in_time_fenced` `ctx.adjFactorsSnapshot` matching the query's effective `asOf` and Vault fence, and binds `read_parquet(...)` directly to `ctx.adjFactorsSnapshot.path`.
- **`planAdjFactorsMetadataQuery(adjPath)`** / **`parseAdjFactorsSnapshotMetadata(adjPath, kvRows)`** — Plans the `parquet_kv_metadata('<adjPath>')` query for `stock_bot.adj_factors.*` footer keys and strictly parses/validates them (mirroring `tools/curate-etl/src/curate_adj.rs`).
- **`planEventsQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `<curatedRoot>/events/year=*/part.parquet` (`hive_partitioning = true`) filtered by allow-listed `kinds` and optional `listingIds`, preserving the Parquet writer's total sort order `(listing_id, ts, kind, subtype, payload_json, known_at, known_at_source)`.
- **`planShortsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `<curatedRoot>/shorts/part.parquet`, binding UTC `YYYY-MM-DD` `report_date` bounds and microsecond UTC ISO-8601 `known_at <= ?`.
- **`planFundamentalsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` point-in-time query over `<curatedRoot>/fundamentals_pit/year=*/part.parquet` (`hive_partitioning = true`) selecting at most one latest snapshot (`effective_known_at <= asOf`, clamped strictly below `vaultCutoffTs`) per requested `listing_id` across allow-listed `FUNDAMENTALS_PIT_VALUE_FIELDS`, with `allowEstimatedLag` (default `true`) failing closed on snapshot-level `has_estimated_lag` without fallback and masking `ttm_*` values/date/currency when `ttm_has_estimated_lag` is `true`.
- **`planFx1dQuery(q, ctx)`** — Plans a `'vault_fenced'` query (with default `asOf = vaultCutoffTs * 1000 - 1` µs) over `<curatedRoot>/fx_1d/part.parquet` for `timeframe: '1d'`, mapping `'USD.CAD'` to the stored bound parameter `'USDCAD'`. Rejects `'1m'` with `MarketDataStoreNotImplementedError`.
- **`planUniverseQuery(q, ctx)`** — Plans a `'vault_fenced'`, survivorship-free query over `<curatedRoot>/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) returning `SELECT DISTINCT b.listing_id ... ORDER BY b.listing_id ASC` for supported `UNIVERSE_REFS` (`'US_EQ'`, `'CA_EQ'`, `'US_CA_EQ'`) within `[date - lookbackDays, date]` (default `DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7`, configurable via `ctx.universeLookbackDays`).
- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `<curatedRoot>/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls.
### Mandatory Vault, PIT, Microsecond & Boundary Validation Rules
- Every planner delegates unconditionally to `applyVaultFence`, binding `ts`/`report_date` bounds and `known_at <= ?` in UTC (`TZ`-invariant). Under `'vault_fenced'`, `from >= vaultCutoffTs` throws `VaultHoldoutFenceError` and `to`/`asOf` clamp strictly below `vaultCutoffTs`; `'vault_evaluation_only'` requires `vaultOperatorAuthorized === true` (only on `bars`; `events`, `shortsAsOf`, and `fx` are always `'vault_fenced'`).
- **Microsecond upper-bound precision:** Curated Parquet `ts` and `known_at` columns store UTC microseconds (`curate_fx_1d` stamps `23:59:59.999999Z`). Date-only `YYYY-MM-DD` upper bounds (`to`, `asOf`) and default or clamped Vault upper bounds expand to the last included Parquet microsecond (`.999999Z` / `vaultCutoffTs * 1000 - 1`), while explicit time-of-day bounds preserve their caller-specified precision. Under `'vault_fenced'`, every planned upper bound remains strictly `< vaultCutoffTs`.
- `curatedRoot` (and optional `adjFactorsPath`) are the only values embedded in SQL text and must be absolute POSIX paths free of control characters (`<= 0x1f`, `0x7f`), `'`, `;`, and glob metacharacters (`*`, `?`, `[`, `]`).
- All caller values (`listingIds` as `INT32` safe integers, allow-listed `kinds`, `'USD.CAD' -> 'USDCAD'`, and UTC date/timestamp bounds) are validated upfront and passed strictly as bound `?` parameters.
### `bars` 1d Adjustment Formulas & Verified Fenced `adj_factors` Requirement
`bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share `volume`. Because `adj_factors` stores right-to-left cumulative suffix products (`cum_split_factor`, `cum_total_factor`), slicing a retrospective `adj_factors` file with `known_at <= asOf` would still embed future or held-out Vault splits/dividends into earlier cumulative factors.
- **`'raw'`**: OHLC, `vwap`, and `volume` are returned unadjusted (`adj_factors` is not read).
- **`'split'` / `'total'`**: Require a verified `point_in_time_fenced` `adj_factors` Parquet artifact (published by `curate_and_write_adj_factors_as_of` with `stock_bot.adj_factors.*` footer metadata) whose effective inclusive microsecond fence matches the query's effective `asOf` and Vault cutoff. Retrospective, unverified, or mismatched-fence files are rejected with `AdjFactorsSnapshotError` before any `bars` query runs. To prevent TOCTOU races when `curate-etl` atomically replaces `<curatedRoot>/adj_factors/part.parquet` between footer verification and the factor scan, `createDuckDbMarketDataStore` requires either `pinAdjFactorsArtifact` (binding a stable handle such as `/proc/self/fd/<fd>`, `/dev/fd/<fd>`, or a private hardlink/copy for both queries and releasing it in `finally`) or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable published path; unpinned mutable paths fail closed with `AdjFactorsSnapshotError('unpinned_mutable_path')`.
- Against the verified `adj_factors` file, `bars_1d` is joined via `ASOF LEFT JOIN` (filtered to `listing_id IN (...) AND known_at <= ?`) on `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (matching the first `adj_factors` row with `ex_date > session_date` per `tools/curate-etl/README.md`):
- **`'split'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_split_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`.
- **`'total'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_total_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`.
### `universe`
`planUniverseQuery` and `createDuckDbMarketDataStore().universe({ ref, date })` resolve the survivorship-free set of active `INT32` `listing_id`s on a UTC calendar `date` (`YYYY-MM-DD`) directly from curated `bars_1d` Parquet (`hive_partitioning = true`):
- **Provisional M1 bar-currency membership rule:** Supported `UNIVERSE_REFS` (`'US_EQ'`, `'CA_EQ'`, `'US_CA_EQ'`, matching `trial_ledger.universe_market`) filter `bars_1d.currency` using bound `?` parameters (`'USD'`, `'CAD'`, or `IN ('USD', 'CAD')`). Because membership is provisionally determined by bar quote currency before security-master MIC joins are added, USD-quoted TSX listings land in `'US_EQ'`. `'FX'` and any other ref throw `MarketDataStoreValidationError` (`field: 'ref'`) with zero executor calls.
- **Active-listing lookback window:** A listing is active on `date` when it has at least one `bars_1d` row with `session_date` in `[date - lookbackDays, date]` (calendar days; default `DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7`, optional positive-integer `universeLookbackDays` on context/store options). No row after `date` is ever read, so delisted listings appear only while they traded.
- **Mandatory Vault & PIT fence:** `date` is always routed through `applyVaultFence` under `'vault_fenced'` scope (`date >= vaultCutoffTs` throws `VaultHoldoutFenceError` with zero executor calls, even when `vaultOperatorAuthorized: true`), and every planned query binds both `b.ts <= ?` and `b.known_at <= ?` strictly below `vaultCutoffTs`.
### Local Query-Planner Benchmark
Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across `bars` 1d (`raw`/`split`/`total`), `events` (with and without `listingIds`), `shortsAsOf`, and `fx` 1d, plus a fixed-seed (`20261129`) `universe` case exercising `createDuckDbMarketDataStore().universe()` (plan + adapter mapping) over `200` calls × `15,000` listing IDs (`3,000,000` mapped IDs) via an in-memory executor (checksums verified outside the timed sections):
- **Command:** `bun run libs/research/scripts/benchmark-market-data-store-duckdb.ts`
- **Observed (Bun 1.2.16):**
- **Mixed planners (`120,000` queries):** `elapsedMs = 225.79 ms`, `queriesPerSec = 531,470 queries/s` (`758,061` bound params, pinned checksum `8606c98c`)
- **`universe` plan + adapter mapping (`200` calls × `15,000` listings):** `elapsedMs = 23.44 ms`, `callsPerSec = 8,534 calls/s`, `rowsPerSec = 128,011,137 rows/s` (`3,000,000` mapped IDs, pinned checksum `ef5f1136`)
## Routed `MarketDataStore` (DuckDB Daily + QuestDB `1m` Intraday)
Exported from `@stock-bot/research` and `@stock-bot/research/market-data-store-routed` (`libs/research/src/market-data-store-routed.ts`). The QuestDB intraday reader is also exported from `@stock-bot/research/market-data-store-questdb`. Both modules are pure, dependency-free, and browser-safe.
- **`createRoutedMarketDataStore({ daily, intraday })`** — Composes a full daily `MarketDataStore` (e.g. `createDuckDbMarketDataStore`) with an intraday `bars` reader (`Pick<MarketDataStore, 'bars'>`, e.g. `createQuestDbIntradayBarsReader`).
- `bars(q)` with `timeframe: '1m'` delegates directly to `intraday.bars(q)` (preserving lazy iteration, receiver, query identity, and error propagation). Note that `createQuestDbIntradayBarsReader` supports split-unadjusted raw (`adjustment: 'raw'`) `1m` bars.
- `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed inputs) and all other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly to `daily`.
- **Shared Vault fence requirement:** The router adds no Vault logic of its own; each delegate enforces its own fence. Always construct `daily` and `intraday` with the exact same `vaultCutoffTs` and `vaultOperatorAuthorized`, and pass that same `vaultCutoffTs` to `createQueryDataTool` (which is always Vault-fenced and accepts only `{ vaultCutoffTs }`):
```ts
const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0);
const vaultOperatorAuthorized = false;
const daily = createDuckDbMarketDataStore({
executor: duckDbExecutor,
curatedRoot: '/mnt/data/stockbot/curated',
vaultCutoffTs,
vaultOperatorAuthorized,
});
const intraday = createQuestDbIntradayBarsReader({
executor: questDbExecutor,
vaultCutoffTs,
vaultOperatorAuthorized,
});
const store = createRoutedMarketDataStore({ daily, intraday });
const queryDataTool = createQueryDataTool({
store,
vaultContext: { vaultCutoffTs },
});
```
## Signal Panel Builder
Exported from both `@stock-bot/research` and `@stock-bot/research/signal-panel` (`libs/research/src/signal-panel.ts`). The module is pure, synchronous (except `collectBars`), dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers).
### API
- **`buildForwardReturnPanel({ bars, signals, horizonSessions, vaultCutoffDate, maxSignalAgeSessions? })`** — Joins daily `BarRecord[]` (caller-supplied `'total'`-adjusted closes in any order) with point-in-time `SignalObservation[]` (`{ listingId, knownAt, value }`) into Vault-safe `SignalCrossSection[]` slices ready for `analyzeSignal`. Returns `{ panel, sessionDates, diagnostics }` with strictly ascending `date`s, `ids: Int32Array` sorted ascending by `listingId`, and `signal` / `forwardReturn` as `Float64Array`, deterministic under any input permutation and without mutating caller inputs.
- **`shortsTableToSignalRows(table, field)`** — Maps a `MarketDataStore.shortsAsOf` `Table` into `SignalObservation[]` for `field: 'shares_short' | 'net_change' | 'pct_float'`, skipping `null` cells, normalizing `-0` to `0`, and rejecting missing columns or malformed rows with `SignalPanelError`.
- **`collectBars(iterable)`** — Drains `AsyncIterable<BarBatch>` (such as `MarketDataStore.bars`) into a flat `BarRecord[]` using indexed loops without mutating yielded batches.
### UTC Session Calendar, PIT Alignment & Vault Rules
- **UTC session calendar:** Daily curated bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or `21:00 UTC`), so the integer UTC day key `Math.floor(bar.ts / 86_400_000)` maps 1:1 to the exchange session date `YYYY-MM-DD`.
- **Strict point-in-time (`knownAt <= bar.ts`):** For each listing and session `d`, the active signal is the latest row with `knownAt <= bar.ts` (ties on identical `(listingId, knownAt)` break deterministically by `value ASC` so the highest value wins regardless of input order). A signal known after the close (e.g. `17:00 ET`) is never applied on `d` and first takes effect on `d + 1`.
- **Signal staleness (`maxSignalAgeSessions`):** When set (`>= 0`), age is measured in calendar sessions elapsed since the first actionable session where `sessionMaxTs[s] >= knownAt` (so a `17:00 ET` after-close signal has age `0` on the next trading day). Expired observations are dropped and counted in `diagnostics.droppedStaleSignal`.
- **Exact horizon alignment & close validation:** `forwardReturn = close[d + h] / close[d] - 1` uses the listing's own bar exactly `horizonSessions` calendar sessions ahead; missing forward bars are dropped (`diagnostics.droppedMissingForwardBar`) and never shifted to `d + h + 1`. Non-positive or non-finite closes (`<= 0`, `NaN`, `±Infinity`) drop cleanly into `diagnostics.droppedNonPositiveClose` without throwing. Exact pre-cutoff duplicate bars (`ts` and `close` identical) are deduplicated into `diagnostics.duplicateBars`; conflicting duplicates on the same `(listingId, date)` throw `SignalPanelError('duplicate_bar')`.
- **Vault holdout fence:** `sessionDates` contains only dates strictly `< vaultCutoffDate`. No cross-section is emitted when either `d` or its forward session `d + horizonSessions` reaches or exceeds `vaultCutoffDate` (counted in `diagnostics.vaultExcludedDates`), and `bar.close` is never accessed for any bar on or after `vaultCutoffDate`.
### `SignalPanelError` Codes
| Code | Meaning |
| --- | --- |
| `'invalid_input'` | Non-object input envelope, non-array `bars`/`signals`, invalid `AsyncIterable`, invalid shorts field, or missing required table columns |
| `'invalid_horizon'` | `horizonSessions` is not a safe integer `>= 1` |
| `'invalid_option'` | `maxSignalAgeSessions` is defined and not a safe integer `>= 0` |
| `'invalid_date'` | `vaultCutoffDate` is not a valid strict calendar `YYYY-MM-DD` date |
| `'invalid_bar'` | Malformed bar record, invalid `INT32` `listingId`, invalid epoch-ms `ts`/`knownAt`, non-number pre-cutoff `close`, or malformed `BarBatch` |
| `'invalid_signal'` | Malformed signal or shorts table row, invalid `listingId`/`knownAt`, or non-finite non-null signal value |
| `'duplicate_bar'` | Two pre-cutoff bars for the same `(listingId, date)` disagree on `ts` or `close` |
### Local In-Memory Benchmark (`buildForwardReturnPanel`)
Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3,000` listings (`15,120,000` input bars, `720,000` monthly-ish `17:00 ET` signal rows, `horizonSessions = 5`, `vaultCutoffDate = '2025-03-31'`):
- **Command:** `bun run libs/research/scripts/benchmark-signal-panel.ts`
- **Observed (Bun 1.2.16):** `elapsedMs = 817.24 ms`, `rowsPerSec = 18,501,301 rows/s` (`5,014` emitted panel dates, `15,042,000` emitted observations, `25` Vault-excluded dates, pinned checksum `f0f28bdf`)
## Event Study Panel Builder
Exported from both `@stock-bot/research` and `@stock-bot/research/event-panel` (`libs/research/src/event-panel.ts`). The module is pure, synchronous, dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers).
### API
- **`eventsTableToEventRows(table, filter?)`** — Maps a `MarketDataStore.events` `Table` into point-in-time `EventObservation[]` (`{ listingId, knownAt, kind, subtype }`), validating every row upfront (before applying optional exact-match `filter.kinds` / `filter.subtypes` allow-lists), normalizing `-0` to `0`, and rejecting missing columns, empty filter arrays, or malformed rows with `EventPanelError`.
- **`buildEventStudyInput({ bars, events, vaultCutoffDate, exchangeCalendars, benchmark? })`** — Transforms daily `BarRecord[]` (caller-supplied `'total'`-adjusted closes in any order) and `EventObservation[]` rows into a Vault-safe `EventStudyInput` (`{ sessionDates, entityReturns, benchmarkReturns?, events }`) plus `EventPanelDiagnostics` ready for `runEventStudy` / `eventStudy`. Output is deterministic under any input permutation (entities inserted in ascending `listingId` order; events sorted by `(dayIndex ASC, entityId ASC)`) without mutating caller inputs.
- `exchangeCalendars: { calendars, listingCalendarId }` (**required**): caller-supplied exchange close calendars (`{ date, closeTs }[]` per calendar ID, plus `listingId -> calendarId` mapping). Every pre-Vault listing in `bars` must be mapped to a calendar that covers all of its pre-Vault bar dates (coverage gaps or missing mappings throw `EventPanelError('invalid_option')`). Each listing's events are anchored against its exchange's actual pre-Vault session close timestamps (e.g. `13:00 ET` on NYSE half-days vs `16:00 ET` on TSX) rather than curated `bars_1d.ts` (`16:00 ET`), and the eligible session date is then mapped onto the shared `sessionDates` index.
- `benchmark?: 'equal_weight' | 'none'` (default `'none'` when omitted/`undefined`; `null` or any other value throws `EventPanelError('invalid_option')`): `'none'` omits `benchmarkReturns`; `'equal_weight'` sets `benchmarkReturns[d]` to the mean of finite `entityReturns` on session `d` (`NaN` when none).
### UTC Session Calendar, PIT Anchoring, `NaN` Returns & Vault Rules
- **UTC session calendar:** Daily curated bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or `21:00 UTC`), so the integer UTC day key `Math.floor(bar.ts / 86_400_000)` maps 1:1 to the exchange session date `YYYY-MM-DD`.
- **Consecutive-session returns & `NaN` contract (`eventStudy`):** For each listing, `entityReturns` is a `Float64Array` aligned to `sessionDates`. Simple close-to-close return `close[d] / close[d - 1] - 1` is computed strictly when the listing has bars on consecutive exchange-calendar sessions (`currCalIdx === prevCalIdx + 1`) and both closes are finite and `> 0` with a finite ratio. Session `0`, missing-bar sessions (including an open exchange session missing for all listings), the first resumption session after a gap, and non-positive/non-finite/overflowing transitions (counted in `diagnostics.nonPositiveCloseReturns`) are written as `NaN` (never `±Infinity`), matching `eventStudy`'s contract in `libs/calculations/src/analytics/event-study.ts` (which rejects `±Infinity` with `NON_FINITE_RETURN` and cleanly drops events with any `NaN` in `[-preDays, +postDays]`).
- **Duplicate-bar policy:** Exact pre-cutoff duplicate bars (`ts` and `close` identical, including `NaN === NaN`) are deduplicated into `diagnostics.duplicateBars`; conflicting duplicates on the same `(listingId, date)` throw `EventPanelError('duplicate_bar')`.
- **Strict PIT event anchoring & drop precedence:** Each event is classified in strict order: (1) `knownAt >= vaultCutoffDate (00:00:00.000Z)` → `diagnostics.vaultExcludedEvents`; (2) listing has no pre-Vault bars → `diagnostics.droppedUnknownListing`; (3) `knownAt` is after the listing's last pre-Vault exchange close (or its eligible calendar date exceeds the last pre-Vault bar date) → `diagnostics.droppedAfterLastSession`; (4) eligible pre-Vault exchange session dates absent from `sessionDates` → `diagnostics.droppedMissingCalendarSession`; (5) lower-bound binary search over the listing's exchange close timestamps, matching `eventDayIndex` semantics so after-close and post-half-day-close filings always anchor to the next trading session. Exact duplicate `(listingId, dayIndex)` events collapse to one (`diagnostics.duplicateEvents`), preserving `events.length === emitted + vaultExcludedEvents + droppedUnknownListing + droppedAfterLastSession + droppedMissingCalendarSession + duplicateEvents`.
- **Vault holdout fence:** `sessionDates` contains only dates strictly `< vaultCutoffDate` (post-cutoff dates are counted in `diagnostics.vaultExcludedDates`), and `bar.close` is never accessed for any bar on or after `vaultCutoffDate`.
### `EventPanelError` Codes
| Code | Meaning |
| --- | --- |
| `'invalid_input'` | Non-object input envelope, non-array `bars`/`events`, malformed `Table`, or missing required columns (`listing_id`, `known_at`, `kind`, `subtype`) |
| `'invalid_date'` | `vaultCutoffDate` or an `exchangeCalendars` session `date` is not a valid strict calendar `YYYY-MM-DD` date |
| `'invalid_bar'` | Malformed bar record, invalid `INT32` `listingId`, invalid epoch-ms `ts`/`knownAt`, or non-number pre-cutoff `close` |
| `'invalid_event'` | Malformed event or table row, invalid `listingId`/`knownAt`, `kind` outside `EVENT_KINDS`, or non-string/non-null `subtype` |
| `'invalid_option'` | Invalid `benchmark` mode, missing/malformed/incomplete `exchangeCalendars` (including pre-Vault bar coverage gaps), or invalid/empty `eventsTableToEventRows` filter (`kinds`/`subtypes`) |
| `'duplicate_bar'` | Two pre-cutoff bars for the same `(listingId, date)` disagree on `ts` or `close` |
### Local In-Memory Benchmark (`buildEventStudyInput`)
Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3,000` listings (`15,120,000` input bars, `240,000` after-close `17:00 ET` filing events at stride `63`, `vaultCutoffDate = '2025-03-31'`, `benchmark: 'equal_weight'`, `XNYS`/`XTSE` exchange calendars):
- **Command:** `bun run libs/research/scripts/benchmark-event-panel.ts`
- **Observed (Bun 1.2.16):** `elapsedMs = 731.06 ms`, `barsPerSec = 20,682,279 bars/s`, `eventsPerSec = 328,290 events/s` (`5,020` pre-Vault sessions, `240,000` anchored events, `20` Vault-excluded dates, pinned checksum `01b356d3`)
## MCP Copilot Core
Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported via the `@stock-bot/research/mcp` subpath (`libs/research/src/mcp/index.ts`). It is intentionally **not** re-exported from the browser-safe `@stock-bot/research` default entrypoint.
### Registering Tools & Running Stdio Framing
- **`defineMcpTool({ name, description, inputSchema, jsonSchema?, handler })`** — Registers a strict Zod-validated tool, converts `inputSchema` into a strict JSON Schema (`additionalProperties: false`, or uses an explicit `jsonSchema` override), returns `isError: true` on invalid arguments without calling the handler, and sanitizes thrown handler errors so stack traces never leak.
- **`createMcpServer({ name, version, tools })`** — Transport-agnostic JSON-RPC 2.0 dispatcher implementing `initialize`, `notifications/initialized`, `ping`, `tools/list`, and `tools/call` via `handleMessage(raw: string): Promise<string | null>`. Rejects duplicate tool names at creation time.
- **`runStdioServer(server, { input?, output?, maxLineBytes? })`** — Newline-delimited JSON-RPC stdio transport over injectable streams (defaulting to `process.stdin` / `process.stdout`), with streaming UTF-8 decoding across arbitrary chunk boundaries, strict sequential dispatch in arrival order, `maxLineBytes` frame-size protection (default `4 MiB`), and zero non-protocol bytes on `output`.
### `query_data` Tool (Vault-Fenced)
- **`createQueryDataTool({ store, vaultContext })`** — Wraps an injected `MarketDataStore` for explicit `listingIds` (max `QUERY_DATA_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref, with bounded output rows (`QUERY_DATA_DEFAULT_LIMIT = 500`, hard max `QUERY_DATA_MAX_LIMIT = 5_000`).
- Always enforces `scope: 'vault_fenced'` via `applyVaultFence` before any store call, omits `scope` / `vault_evaluation_only` from the strict schema (rejecting unknown keys with zero store calls), drops any post-cutoff row (`ts >= vaultCutoffTs` or `knownAt >= vaultCutoffTs`) as defense in depth, and maps `VaultHoldoutFenceError`, `VaultScopeNotAuthorizedError`, `MarketDataStoreValidationError`, `MarketDataStoreNotImplementedError`, and `AdjFactorsSnapshotError` to `isError: true` responses naming the error class.
### `event_study` Tool (Vault-Fenced)
- **`createEventStudyTool({ store, ledger, vaultContext, principalId, resolveExchangeCalendars })`** — Runs a Vault-fenced event study over daily bars and point-in-time `events` (`filing`, `earnings`, `ceo_post`, `corporate_action`, with optional exact `subtypes` filter capped at `EVENT_STUDY_MAX_SUBTYPES = 100` entries and `EVENT_STUDY_MAX_SUBTYPE_LENGTH = 128` chars each) for explicit `listingIds` (max `EVENT_STUDY_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref matching `universeMarket`, across `[-preDays, +postDays]` (`0–60` sessions each; `horizonBucket` must match `postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'`).
- **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`.
### PostgreSQL Symbol Search Adapter
- **`createPostgresSymbolSearchPort({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `SymbolSearchExecutor` and `PostgresSymbolSearchError`) implements `SymbolSearchPort` over the M1 PostgreSQL security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`) in one read-only parameterized `SELECT` with zero runtime `pg` dependency.
- **Inputs & schema:** Validates that `executor` exposes a callable `query(text, params?)` method (`INVALID_EXECUTOR`), validates optional `schema` against `^[a-z_][a-z0-9_]*$` before quoting table identifiers (`INVALID_SCHEMA`; defaults to the executor's `search_path`), validates `q.vaultCutoffTs` (epoch milliseconds) and converts it to a UTC calendar date (`YYYY-MM-DD`), escapes `%`, `_`, and `\` before building the `ILIKE` pattern, and rejects malformed/non-integer IDs or invalid/impossible `YYYY-MM-DD` dates returned by the executor (`INVALID_ROW`).
- **As-of ticker resolution & root suppression:** Excludes listings with `listed_from > cutoff` (retaining `listed_from IS NULL`). Defines `root_is_future` per listing when `listing_symbol_history` has at least one row with `upper(ticker) = upper(listing.ticker_root)` and none with `valid_from <= cutoff`. Resolves one ticker per listing (breaking same-`valid_from` ties by `ticker ASC`) in strict order: (1) latest history row valid at cutoff (`valid_from <= cutoff AND (valid_to IS NULL OR valid_to >= cutoff)`), (2) `listing.ticker_root` when `NOT root_is_future`, (3) latest history row with `valid_from <= cutoff` even if its `valid_to < cutoff`, (4) otherwise excludes the listing so future tickers never leak via fallback or name/ISIN lookup.
- **`delistedAt` derivation:** Projects `delistedAt` as `listing.listed_to` (`YYYY-MM-DD`) when `delist_reason IS NOT NULL AND delist_reason <> 'active'`, else `null`. When `q.includeDelisted === false`, rows with non-null `delistedAt <= cutoff` are filtered out while future delistings (`delistedAt > cutoff`) remain eligible as of the cutoff.
- **Port matching vs. MCP ranking:** The adapter matches on resolved as-of ticker (`ILIKE`), `listing.ticker_root` (`ILIKE`, gated by `NOT root_is_future`), `instrument.canonical_name` (`ILIKE`), or case-insensitive exact `instrument.primary_isin`, ignores `q.limit`, and returns all candidates ordered by `listing_id ASC`. When composed with `createSearchSymbolsTool`, the MCP tool applies Vault clamping/masking, ranks by exact ticker > ticker prefix > company name substring (tie-breaking by `listingId ASC`), and truncates to `limit` — so callers needing ticker-substring, root-only, or exact-ISIN lookups should call the port directly, while MCP tool callers should query by ticker or company name.
### PostgreSQL Findings & Provider Caveats Adapter
- **`createPostgresFindingWritePort({ executor, schema? })`** and **`createPostgresKnowledgeReaders({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `PostgresFindingsExecutor`, `PostgresFindingsOptions`, `PostgresKnowledgeReaders`, `PostgresFindingsError`, and `PostgresFindingsErrorCode`) back `file_finding` (`FindingWritePort`) and the `findings` / `provider_caveats` halves of `read_knowledge` (`Pick<KnowledgePort, 'listFindings' | 'listProviderCaveats'>`) over `37-research-findings.sql` with zero runtime `pg` dependency.
- **Inputs, schema & row validation:** Validates `executor.query` (`INVALID_EXECUTOR`) and optional `schema` against `^[a-z_][a-z0-9_]*$` (`INVALID_SCHEMA`; defaults to the executor's `search_path`), binds every caller value via `$n` parameters, issues zero `UPDATE`/`DELETE` statements, and fails closed (`INVALID_ROW`) on malformed result envelopes, non-1D/non-string ref arrays, unknown `kind`, or invalid timestamps (converting PostgreSQL `Date` values or strictly parsed timezone-qualified ISO-8601 strings to UTC ISO-8601 output).
- **Atomic idempotency & autocommit requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass an autocommit, fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` or explicit `BEGIN` transaction unless the executor rolls back a `SAVEPOINT` before rethrowing errors) so concurrent callers observe the committed winner and `23505` retry lookups do not hit `25P02`.
- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`) for ASCII queries, and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`) for ASCII provider filters while retaining non-ASCII stored rows as candidates (and omitting SQL casing filters for non-ASCII selectors), then applying JavaScript `.toLowerCase()` matching after row validation so PostgreSQL libc/C collation casing (e.g., Greek final sigma or `BİST` / `K`) never drops `read_knowledge` matches. All eligible rows are returned ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing.
### Exchange Calendar Resolver
- **`createPostgresListingCalendarPort({ executor, schema? })`** and **`createExchangeCalendarResolver({ listingCalendars, sessionDates, earlyCloses? })`** (exported from `@stock-bot/research/mcp` alongside `ListingCalendarPort`, `SessionDatesPort`, `EarlyCloseOverrides`, `PostgresListingCalendarError`, and `ExchangeCalendarResolverError`) implement `EventStudyExchangeCalendarResolver` for `createEventStudyTool` with zero `node:*` imports and zero runtime `pg` dependency.
- **Injected ports & fail-closed validation:** `createPostgresListingCalendarPort` issues one read-only parameterized `SELECT` joining `listing.mic` to `exchange.mic` (`WHERE l.listing_id = ANY($1::integer[])`), validating `executor.query` (`INVALID_EXECUTOR`), optional `schema` (`^[a-z_][a-z0-9_]*$`, `INVALID_SCHEMA`), and returned rows (`INVALID_ROW`). `SessionDatesPort.listSessionDates({ calendarCode, fromDate, toDate })` is called once per distinct calendar code in sorted order; the resolver fails closed with no partial result on missing, unrequested, or conflicting listing mappings or on malformed, duplicate, unsorted, or out-of-window session dates. Empty `listingIds` returns empty `{ calendars, listingCalendarId }` with zero port calls.
- **Supported DST range & default half-day close:** Session close timestamps convert Eastern Time (`America/New_York` / `America/Toronto`) to UTC epoch milliseconds across `1976-01-01` through `2030-12-31` inclusive (matching `tools/curate-etl/src/session_close.rs` across the `1976–1986`, `1987–2006`, and `2007–2030` DST eras) and throw `ExchangeCalendarResolverError('UNSUPPORTED_DATE')` outside that range. Optional `earlyCloses` (`{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, integer minutes in `1..=960`, e.g. `780` for `13:00 ET`) overrides the close on listed dates; when `earlyCloses` is omitted, every session closes at `16:00 ET` and exchange half-days are treated as full `16:00 ET` trading days.
- **Bar-derived `SessionDatesPort` (`createBarSessionDatesPort({ store, referenceListingIds })`):** Exported from `@stock-bot/research/mcp` alongside `BarSessionDatesPortOptions` and `BarSessionDatesError`. Keys in `referenceListingIds` are exact `exchange.calendar_code` strings (e.g. `XNYS`, `XTSE`) mapped to non-empty, duplicate-free arrays of positive INT32 reference listing IDs whose daily bars define that exchange's session dates; the caller owns reference-listing coverage so gaps do not omit real sessions. Each `listSessionDates` call queries `store.bars({ listingIds, timeframe: '1d', from, to, adjustment: 'raw' })` once with `scope` and `asOf` omitted so the store's default `'vault_fenced'` scope applies (`'vault_evaluation_only'` is never passed), propagates store errors (including `VaultHoldoutFenceError`) unchanged, derives UTC session dates from `BarRecord.ts` (`Math.floor(ts / MS_PER_DAY)`), and fails closed on unknown calendars, malformed queries, or invalid bars.
### Filesystem Library Cards Adapter
- **`createLibraryCardReader({ root, fs })`** (exported from `@stock-bot/research/mcp` alongside `createNodeLibraryCardFs`, `LibraryCardFs`, `LibraryCardDirHandle`, `LibraryCardDirEntry`, `LibraryCardReaderOptions`, `LibraryCardReader`, `LibraryCardError`, and `LibraryCardErrorCode`) implements `Pick<KnowledgePort, 'listLibraryCards'>` over a configured read-only library root (`<root>/library.yml` and `<root>/cards/<sectionId>/<slug>.md`) with zero new dependencies.
- **Read-only boundary, fresh reads & symlink safety:** Resolves `root` once at construction, reads `library.yml` and eligible cards fresh on every call (no cache), requires anchored directory operations (`LibraryCardFs.openDir`, backed by `/proc/self/fd/<fd>` in `createNodeLibraryCardFs()`) with no pathname fallback, enforces `O_NOFOLLOW` on every component below the configured root with `fstat` regular-file/directory verification, and fails closed if the adapter or runtime cannot enforce that boundary.
- **Exact-ID narrowing & unverified-card assumption:** Returns all eligible cards in manifest section order and code-unit slug order without pre-slicing or truncating text, narrowing only on exact case-sensitive `q.id` (malformed or unknown IDs return an empty frozen array without opening card files) so `createReadKnowledgeTool` owns `query`/`tags` filtering, ranking, truncation, and `limit`. All eligible cards are returned regardless of `verified` status, and callers must bind `root` to a research-visible corpus free of holdout or Vault-only observations.
### Copilot Server
- **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions.
- **`createPostgresResearchCopilotServer(options)`** (exported from `@stock-bot/research/mcp` alongside `PostgresResearchCopilotServerOptions` and `PostgresResearchCopilotExecutor`) wires one shared PostgreSQL executor into `createPostgresSymbolSearchPort`, `createPostgresTrialRefPort`, `createPostgresFindingWritePort`, `createPostgresKnowledgeReaders`, `createPostgresListingCalendarPort` + `createExchangeCalendarResolver`, and `trial_ledger`, while keeping `store`, `listLibraryCards`, `sessionDates` (with optional `earlyCloses`), `newId`, and `now` caller-supplied. `vaultContext.vaultCutoffTs` is the single authoritative Vault cutoff for all Vault-fenced tools and `trial_ledger` visibility lookups. When `schema` is supplied, the schema-aware adapters qualify their tables with `"<schema>".`, while `trial_ledger` writes and cluster DSR reads resolve through the executor's `search_path`.
### Stdio Host Composition
- **`parseResearchCopilotHostConfig(env)`** and **`runResearchCopilotStdioHost(deps)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotHostConfig`, `ResearchCopilotHostConfigError`, `ResearchCopilotStdioHostDeps`, `RESEARCH_COPILOT_HOST_NAME`, and `RESEARCH_COPILOT_HOST_VERSION`) provide a pure, dependency-free stdio host layer (`libs/research/src/mcp/host/stdio-host.ts`) with no `pg`, DuckDB, `node:*`, or bare `process` references.
- **Environment variables (`RESEARCH_MCP_*`):** Unrelated keys are ignored; unknown `RESEARCH_MCP_*` keys, missing required variables, blank values, and malformed fields throw `ResearchCopilotHostConfigError` naming the variable without exposing raw values or credentials.
| Variable | Required | Format |
| --- | --- | --- |
| `RESEARCH_MCP_POSTGRES_URL` | Yes | `postgres://` or `postgresql://` URL with non-empty host (never echoed in errors) |
| `RESEARCH_MCP_POSTGRES_SCHEMA` | No | PostgreSQL identifier `^[a-z_][a-z0-9_]*$` |
| `RESEARCH_MCP_CURATED_ROOT` | Yes | Non-blank path string for curated Parquet datasets (validated by the store factory) |
| `RESEARCH_MCP_VAULT_CUTOFF_TS` | Yes | Strict ISO-8601 UTC instant with seconds and `Z` suffix, optional ms (e.g. `2025-06-01T00:00:00Z`) |
| `RESEARCH_MCP_PRINCIPAL_ID` | Yes | `operator` or `agent:<lowercase-uuid>` (UUID v1–8, RFC variant) |
| `RESEARCH_MCP_LIBRARY_ROOT` | Yes | Non-blank directory path containing `library.yml` (validated by the reader factory) |
| `RESEARCH_MCP_SESSION_REFERENCE_LISTINGS` | Yes | JSON object `{ "<calendarCode>": [<positive INT32>, ...] }` (non-empty, distinct IDs), e.g. `{"XNYS":[101,102],"XTSE":[201]}` |
| `RESEARCH_MCP_EARLY_CLOSES` | No | JSON object `{ "<calendarCode>": { "<YYYY-MM-DD>": <1..960 ET min> } }` within `1976-01-01..=2030-12-31`, e.g. `{"XNYS":{"2024-11-29":780}}` |
- **Usage, single Vault cutoff & cleanup ownership:** Pass the parsed `config` to `runResearchCopilotStdioHost({ config, openExecutor, openStore, createLibraryCardReader, newId, now, stdio? })`. The host acquires `openExecutor` → `openStore` → `createLibraryCardReader`, builds `createBarSessionDatesPort` and `createPostgresResearchCopilotServer` (`stock-bot-research-copilot` / `0.1.0`) with `vaultContext: { vaultCutoffTs: config.vaultCutoffTs }`, and starts `runStdioServer` only after all setup succeeds. Callers' `openStore(config)` factory must configure its `MarketDataStore` with the same `config.vaultCutoffTs` so store queries and session-date derivation share one cutoff. Each factory owns internal cleanup on its own failed startup; once a handle is returned, the host awaits `close()` on every acquired handle exactly once in reverse acquisition order on EOF or error, preserving safe primary errors and replacing credential-bearing or uninspectable failures with fixed stage-specific errors. Keep all startup and runtime diagnostics off `stdout` (use `stderr` or structured logs outside stdio) so `stdout` carries only newline-delimited JSON-RPC frames.
### Remaining M2 MCP Items (Later Tasks)
- 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.
## `marimo check`-Gated Notebook Snapshot Exporter
Exported from `@stock-bot/research` (`libs/research/src/notebook-snapshot.ts`). Subprocess execution and filesystem access are injected via `NotebookCommandRunner` and `NotebookSnapshotFs`, and `node:crypto` is loaded lazily at call time so the shared package barrel remains browser-bundleable. Command flags and JSON report validation are confirmed against **marimo `0.26.0`** (pinned in `python/uv.lock`).
### API & Ports
- **`exportNotebookSnapshot(options)`** — Validates options and paths, confirms `notebookPath` is an existing regular `.py` file, gates on `marimo check --format=json <notebookPath>`, and only on a clean check reserves a unique sibling `.html` temp file via `fs.createExclusive` and runs `marimo export html <notebookPath> -o <tempPath> --force` before computing byte length and lowercase SHA-256 and atomically publishing via `fs.rename(tempPath, outputPath)`.
- **Frozen receipt (`NotebookSnapshotReceipt`)** — Returns `Object.freeze({ notebookPath, outputPath, bytes, sha256, checkDiagnostics })`, where `checkDiagnostics` is the deep-frozen marimo JSON report (or `null` when `marimo check` exits `0` with empty stdout).
- **`NotebookCommandRunner`** — Must execute `command` directly with `args` as an argv array (never a shell string). On timeout (default `120_000` ms per command), implementations must terminate the subprocess and reject with `code: 'ETIMEDOUT'` **only after the process has exited and stopped writing** so cleanup cannot race with late writes.
- **`NotebookSnapshotFs`** — Minimal port requiring `stat`, `createExclusive` (must throw `code: 'EEXIST'` on collision), `readBytes`, `rename`, and idempotent `remove`. On any export, read, or publish failure, only the owned temp file is removed and any pre-existing `outputPath` keeps its original bytes.
- **Fail-closed error codes (`NotebookSnapshotError`)** — `INVALID_OPTION`, `INVALID_PATH`, `NOTEBOOK_NOT_FOUND`, `CHECK_FAILED` (nonzero check exit, `summary.errored === true`, `type: 'error'`, or `severity: 'breaking'`), `CHECK_OUTPUT_INVALID` (non-JSON stdout on exit `0` or malformed `{ issues, summary }` / `summary.total_files !== 1`), `EXPORT_FAILED`, `EXPORT_EMPTY`, and `TIMEOUT`. Formatting and runtime advisories may accompany a clean check.
- **Lexical roots & execution notice:** `allowedNotebookRoot` and `allowedOutputRoot` enforce lexical POSIX path-component containment (blocking `..` traversal and same-prefix sibling escapes); callers must supply trusted directories and keep the notebook file stable between check and export. Note that `marimo export html` **executes notebook cells**.
### Node/Bun Adapters (`@stock-bot/research/notebook-snapshot-node`)
Server-only adapters backed by `node:child_process` and `node:fs/promises` are exported exclusively from the `@stock-bot/research/notebook-snapshot-node` subpath (`libs/research/src/notebook-snapshot-node.ts`) so the default `@stock-bot/research` entrypoint remains browser-bundleable:
- **`createNodeNotebookCommandRunner(options?)`** — Implements `NotebookCommandRunner` via `spawn(command, [...args], { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] })`. Captures stdout and stderr independently up to `NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES` (`16 MiB` by default, configurable via `options.maxOutputBytes`), kills with `SIGKILL` on timeout (`ETIMEDOUT`) or overflow (`EOUTPUTLIMIT`), and settles only after `close`.
- **`createNodeNotebookSnapshotFs()`** — Implements `NotebookSnapshotFs` over `node:fs/promises` (`stat` mapping only `ENOENT` to `null`, `open(..., 'wx')` exclusive create, binary `readFile`, atomic `rename`, and non-recursive `rm(..., { force: true })`).
```ts
import { exportNotebookSnapshot } from '@stock-bot/research';
import {
createNodeNotebookCommandRunner,
createNodeNotebookSnapshotFs,
} from '@stock-bot/research/notebook-snapshot-node';
const receipt = await exportNotebookSnapshot({
notebookPath: '/abs/path/to/study.py',
outputPath: '/abs/path/to/study.html',
runner: createNodeNotebookCommandRunner(),
fs: createNodeNotebookSnapshotFs(),
});
```
### Manual Host Smoke Check (Director / Host Only)
Automated tests use fakes and never spawn `marimo`. On a host with the pinned `python/` `uv` environment (`marimo 0.26.0`):
1. Ensure `STOCK_BOT_TRIAL_LEDGER_DSN` is **unset** so the smoke check does not append trial rows to `trial_ledger`.
2. Target `research/notebooks/ca_shorts_filings_study.py` against a fixed Vault-fenced dataset and run `exportNotebookSnapshot` (or the two commands it issues: `uv run --project python marimo check --format=json research/notebooks/ca_shorts_filings_study.py` followed by `uv run --project python marimo export html research/notebooks/ca_shorts_filings_study.py -o <out.html> --force`).
3. Record the pinned inputs, whether `marimo check` reported 0 errors, and whether the exported HTML opens cleanly. Quant owns any research claims (including notebook revision, dataset ID, sample window, Vault cutoff, baseline, and cost assumptions); any paper or live write access requires a separate scope decision.

View file

@ -10,16 +10,8 @@
".": "./src/index.ts",
"./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",
"./market-data-store-questdb": "./src/market-data-store-questdb.ts",
"./market-data-store-routed": "./src/market-data-store-routed.ts",
"./mcp": "./src/mcp/index.ts",
"./notebook-snapshot-node": "./src/notebook-snapshot-node.ts",
"./results": "./src/results.ts",
"./signal-panel": "./src/signal-panel.ts",
"./signal-study": "./src/signal-study.ts",
"./strategy-api": "./src/strategy-api.ts",
"./trial-ledger": "./src/trial-ledger.ts"

View file

@ -1,230 +0,0 @@
import {
type EventObservation,
type EventStudyExchangeCalendars,
buildEventStudyInput,
} from '../src/event-panel';
import type { BarRecord } from '../src/market-data-store';
const SEED = 20261129;
const SESSIONS = 5_040;
const LISTINGS = 3_000;
const EVENT_STRIDE_SESSIONS = 63; // 5040 / 63 = 80 filings/listing -> 240,000 total events
const PRE_CUTOFF_SESSIONS = 5_020;
function createMulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
};
}
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
function generateBusinessCalendar(count: number, startYear: number): {
dates: string[];
closeTs: Float64Array;
afterCloseTs: Float64Array;
} {
const dates: string[] = new Array<string>(count);
const closeTs = new Float64Array(count);
const afterCloseTs = new Float64Array(count);
let year = startYear;
let month = 1;
let day = 1;
// 2006-01-01 was a Sunday (dow = 0)
let dow = 0;
let produced = 0;
while (produced < count) {
if (dow !== 0 && dow !== 6) {
const yyyy = String(year).padStart(4, '0');
const mm = String(month).padStart(2, '0');
const dd = String(day).padStart(2, '0');
dates[produced] = `${yyyy}-${mm}-${dd}`;
closeTs[produced] = Date.UTC(year, month - 1, day, 21, 0, 0, 0); // 16:00 ET
afterCloseTs[produced] = Date.UTC(year, month - 1, day, 22, 0, 0, 0); // 17:00 ET
produced += 1;
}
dow = (dow + 1) % 7;
day += 1;
const baseDays = DAYS_IN_MONTH[month] ?? 31;
const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays;
if (day > maxDay) {
day = 1;
month += 1;
if (month > 12) {
month = 1;
year += 1;
}
}
}
return { dates, closeTs, afterCloseTs };
}
function fnv1aByte(hash: number, byte: number): number {
return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0;
}
function fnv1aUint32(hash: number, value: number): number {
const v = value >>> 0;
let h = fnv1aByte(hash, v & 0xff);
h = fnv1aByte(h, (v >>> 8) & 0xff);
h = fnv1aByte(h, (v >>> 16) & 0xff);
h = fnv1aByte(h, (v >>> 24) & 0xff);
return h;
}
function fnv1aBytes(hash: number, bytes: Uint8Array): number {
let h = hash >>> 0;
for (let i = 0; i < bytes.length; i += 1) {
h = Math.imul((h ^ (bytes[i] as number)) >>> 0, 0x01000193) >>> 0;
}
return h;
}
const rng = createMulberry32(SEED);
const calendar = generateBusinessCalendar(SESSIONS, 2006);
const vaultCutoffDate = calendar.dates[PRE_CUTOFF_SESSIONS] as string;
const totalBars = SESSIONS * LISTINGS;
const bars: BarRecord[] = new Array<BarRecord>(totalBars);
const eventsPerListing = Math.ceil(SESSIONS / EVENT_STRIDE_SESSIONS);
const totalEvents = LISTINGS * eventsPerListing;
const events: EventObservation[] = new Array<EventObservation>(totalEvents);
let barIdx = 0;
let evIdx = 0;
for (let l = 0; l < LISTINGS; l += 1) {
const listingId = l + 1;
const subtype = l % 2 === 0 ? '10-q' : 'interim_financial_statements';
let price = 10 + (l % 200) * 0.5;
for (let t = 0; t < SESSIONS; t += 1) {
const ts = calendar.closeTs[t] as number;
price = Math.max(1, price * (1 + (rng() - 0.4995) * 0.02));
bars[barIdx++] = {
listingId,
ts,
open: price,
high: price,
low: price,
close: price,
volume: 10_000,
vwap: price,
knownAt: ts,
};
if (t % EVENT_STRIDE_SESSIONS === 0) {
events[evIdx++] = {
listingId,
knownAt: calendar.afterCloseTs[t] as number,
kind: 'filing',
subtype,
};
}
}
}
const sessionCloses = calendar.dates.map((date, idx) => ({
date,
closeTs: calendar.closeTs[idx] as number,
}));
const listingCalendarId = new Map<number, string>();
for (let l = 0; l < LISTINGS; l += 1) {
listingCalendarId.set(l + 1, l % 2 === 0 ? 'XNYS' : 'XTSE');
}
const exchangeCalendars: EventStudyExchangeCalendars = {
calendars: new Map([
['XNYS', sessionCloses],
['XTSE', sessionCloses],
]),
listingCalendarId,
};
// Timed section: pure buildEventStudyInput execution (no fixture generation or checksum).
const started = performance.now();
const result = buildEventStudyInput({
bars,
events,
vaultCutoffDate,
benchmark: 'equal_weight',
exchangeCalendars,
});
const elapsedMs = performance.now() - started;
// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, returns, and events.
let checksum = 0x811c9dc5;
checksum = fnv1aUint32(checksum, result.input.sessionDates.length);
checksum = fnv1aUint32(checksum, result.input.entityReturns.size);
checksum = fnv1aUint32(checksum, result.input.events.length);
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates);
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedEvents);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedUnknownListing);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedAfterLastSession);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedMissingCalendarSession);
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateEvents);
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars);
checksum = fnv1aUint32(checksum, result.diagnostics.nonPositiveCloseReturns);
if (result.input.benchmarkReturns !== undefined) {
const bench = result.input.benchmarkReturns as Float64Array;
checksum = fnv1aBytes(checksum, new Uint8Array(bench.buffer, bench.byteOffset, bench.byteLength));
}
for (const [entityId, series] of result.input.entityReturns) {
checksum = fnv1aUint32(checksum, Number(entityId));
const arr = series as Float64Array;
checksum = fnv1aBytes(checksum, new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength));
}
for (let i = 0; i < result.input.events.length; i += 1) {
const ev = result.input.events[i];
if (ev === undefined) {
continue;
}
checksum = fnv1aUint32(checksum, ev.dayIndex);
checksum = fnv1aUint32(checksum, Number(ev.entityId));
}
const checksumHex = checksum.toString(16).padStart(8, '0');
const EXPECTED_CHECKSUM = '01b356d3';
if (checksumHex !== EXPECTED_CHECKSUM) {
throw new Error(
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
);
}
const elapsedSec = elapsedMs / 1000;
const barsPerSec = Math.round(totalBars / elapsedSec);
const eventsPerSec = Math.round(totalEvents / elapsedSec);
console.log(
JSON.stringify(
{
seed: SEED,
sessions: SESSIONS,
listings: LISTINGS,
vaultCutoffDate,
inputBars: totalBars,
inputEvents: totalEvents,
sessionDates: result.input.sessionDates.length,
anchoredEvents: result.input.events.length,
elapsedMs: Number(elapsedMs.toFixed(2)),
barsPerSec,
eventsPerSec,
diagnostics: result.diagnostics,
checksum: checksumHex,
},
null,
2
)
);

View file

@ -1,352 +0,0 @@
import {
type AdjFactorsSnapshotMetadata,
BARS_ADJUSTMENTS,
type BarsQuery,
type DuckDbExecutor,
type DuckDbParam,
type DuckDbPlanContext,
EVENT_KINDS,
type EventsQuery,
type FxQuery,
type PlannedDuckDbQuery,
type ShortsAsOfQuery,
UNIVERSE_REFS,
type UniverseQuery,
createDuckDbMarketDataStore,
planBars1dQuery,
planEventsQuery,
planFx1dQuery,
planShortsAsOfQuery,
} from '../src/market-data-store-duckdb';
import { type TableRow, applyVaultFence } from '../src/market-data-store';
const SEED = 20261129;
const QUERY_COUNT = 120_000;
const CURATED_ROOT = '/mnt/data/stockbot/curated';
const ADJ_PATH = `${CURATED_ROOT}/adj_factors/part.parquet`;
const VAULT_CUTOFF_TS = Date.UTC(2026, 4, 28, 0, 0, 0, 0);
const VAULT_CUTOFF_MICROS = VAULT_CUTOFF_TS * 1000;
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
const BASE_CTX: DuckDbPlanContext = {
curatedRoot: CURATED_ROOT,
vaultCutoffTs: VAULT_CUTOFF_TS,
};
function createMulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
};
}
type WorkloadItem =
| { readonly kind: 'bars'; readonly q: BarsQuery; readonly ctx: DuckDbPlanContext }
| { readonly kind: 'events'; readonly q: EventsQuery }
| { readonly kind: 'shorts'; readonly q: ShortsAsOfQuery }
| { readonly kind: 'fx'; readonly q: FxQuery };
const rng = createMulberry32(SEED);
const startBaseMs = Date.UTC(2016, 0, 1, 0, 0, 0, 0);
const preCutoffSpanMs = VAULT_CUTOFF_TS - startBaseMs - 86_400_000;
const postCutoffSpanMs = 180 * 86_400_000;
function randomDateOrIso(epochMs: number): string {
const iso = new Date(epochMs).toISOString();
return rng() < 0.5 ? iso.slice(0, 10) : iso;
}
function randomListingIds(): number[] {
const count = 1 + Math.floor(rng() * 4);
const ids: number[] = new Array(count);
for (let i = 0; i < count; i += 1) {
ids[i] = 1 + Math.floor(rng() * 50_000);
}
return ids;
}
function buildVerifiedSnapshotForBarsQuery(
from: string,
to: string,
asOf: string | undefined
): AdjFactorsSnapshotMetadata {
const fenced = applyVaultFence(
{ from, to, asOf, scope: 'vault_fenced' },
{ vaultCutoffTs: VAULT_CUTOFF_TS }
);
const subMs = fenced.clampedAsOf || asOf === undefined || DATE_ONLY_RE.test(asOf) ? 999 : 0;
const effectiveAsOfMicros = fenced.asOfMs * 1000 + subMs;
return {
path: ADJ_PATH,
formatVersion: 1,
snapshotKind: 'point_in_time_fenced',
fence: {
asOfMicros: effectiveAsOfMicros,
vaultCutoffMicros: VAULT_CUTOFF_MICROS,
},
rowsWritten: 1000,
snapshotChecksum: '0x024ec73a1afe7e6b',
};
}
const workload: WorkloadItem[] = new Array(QUERY_COUNT);
for (let i = 0; i < QUERY_COUNT; i += 1) {
const fromMs = startBaseMs + Math.floor(rng() * preCutoffSpanMs);
const toMs = fromMs + Math.floor(rng() * (VAULT_CUTOFF_TS - fromMs + postCutoffSpanMs));
const asOfMs =
rng() < 0.35
? undefined
: startBaseMs + Math.floor(rng() * (VAULT_CUTOFF_TS - startBaseMs + postCutoffSpanMs));
const from = randomDateOrIso(fromMs);
const to = randomDateOrIso(toMs);
const asOf = asOfMs === undefined ? undefined : randomDateOrIso(asOfMs);
const slot = i % 7;
if (slot < 3) {
const adjustment = BARS_ADJUSTMENTS[slot] ?? 'raw';
const ctx: DuckDbPlanContext =
adjustment === 'raw'
? BASE_CTX
: {
...BASE_CTX,
adjFactorsSnapshot: buildVerifiedSnapshotForBarsQuery(from, to, asOf),
};
workload[i] = {
kind: 'bars',
q: {
listingIds: randomListingIds(),
timeframe: '1d',
from,
to,
adjustment,
asOf,
},
ctx,
};
} else if (slot === 3 || slot === 4) {
const kindA = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'filing';
const kindB = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'earnings';
workload[i] = {
kind: 'events',
q: {
kinds: slot === 3 ? [kindA] : [kindA, kindB],
listingIds: slot === 3 ? randomListingIds() : undefined,
from,
to,
asOf,
},
};
} else if (slot === 5) {
workload[i] = {
kind: 'shorts',
q: {
listingIds: randomListingIds(),
from,
to,
asOf,
},
};
} else {
workload[i] = {
kind: 'fx',
q: {
pair: 'USD.CAD',
timeframe: '1d',
from,
to,
},
};
}
}
function planWorkloadItem(item: WorkloadItem): PlannedDuckDbQuery {
switch (item.kind) {
case 'bars':
return planBars1dQuery(item.q, item.ctx);
case 'events':
return planEventsQuery(item.q, BASE_CTX);
case 'shorts':
return planShortsAsOfQuery(item.q, BASE_CTX);
case 'fx':
return planFx1dQuery(item.q, BASE_CTX);
}
}
function fnv1aByte(hash: number, byte: number): number {
return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0;
}
function fnv1aString(hash: number, str: string): number {
let h = fnv1aByte(hash, str.length & 0xff);
h = fnv1aByte(h, (str.length >>> 8) & 0xff);
for (let i = 0; i < str.length; i += 1) {
const code = str.charCodeAt(i);
h = fnv1aByte(h, code & 0xff);
if (code > 0xff) {
h = fnv1aByte(h, (code >>> 8) & 0xff);
}
}
return h;
}
function fnv1aParam(hash: number, param: DuckDbParam): number {
if (param === null) {
return fnv1aByte(hash, 0x00);
}
if (typeof param === 'string') {
return fnv1aString(fnv1aByte(hash, 0x01), param);
}
if (typeof param === 'number') {
return fnv1aString(fnv1aByte(hash, 0x02), String(param));
}
return fnv1aByte(fnv1aByte(hash, 0x03), param ? 1 : 0);
}
// Timed section: pure query planning only (no checksum hashing overhead).
let totalParams = 0;
const started = performance.now();
for (const item of workload) {
const planned = planWorkloadItem(item);
totalParams += planned.params.length;
}
const elapsedMs = performance.now() - started;
const queriesPerSec = Math.round(QUERY_COUNT / (elapsedMs / 1000));
// Untimed verification pass: hash full SQL text and ordered parameter values for all queries.
let checksum = 0x811c9dc5;
for (const item of workload) {
const planned = planWorkloadItem(item);
checksum = fnv1aString(checksum, planned.sql);
checksum = fnv1aByte(checksum, planned.params.length);
for (const param of planned.params) {
checksum = fnv1aParam(checksum, param);
}
}
const checksumHex = checksum.toString(16).padStart(8, '0');
const EXPECTED_CHECKSUM = '8606c98c';
if (checksumHex !== EXPECTED_CHECKSUM) {
throw new Error(
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
);
}
// Fixed-seed universe benchmark: plan + adapter mapping for 15,000 listing IDs via in-memory executor.
const UNIVERSE_LISTING_COUNT = 15_000;
const UNIVERSE_CALL_COUNT = 200;
async function runUniverseBenchmark() {
const universeRng = createMulberry32(SEED);
const listingRows: TableRow[] = new Array(UNIVERSE_LISTING_COUNT);
let nextListingId = 1;
for (let i = 0; i < UNIVERSE_LISTING_COUNT; i += 1) {
listingRows[i] = { listing_id: nextListingId };
nextListingId += 1 + Math.floor(universeRng() * 5);
}
const universeQueries: UniverseQuery[] = new Array(UNIVERSE_CALL_COUNT);
for (let i = 0; i < UNIVERSE_CALL_COUNT; i += 1) {
const ref = UNIVERSE_REFS[i % UNIVERSE_REFS.length] ?? 'US_EQ';
const dateMs = startBaseMs + Math.floor(universeRng() * preCutoffSpanMs);
const date = new Date(dateMs).toISOString().slice(0, 10);
universeQueries[i] = { ref, date };
}
const timedExecutor: DuckDbExecutor = {
async run(): Promise<void> {},
async query(): Promise<readonly TableRow[]> {
return listingRows;
},
};
const timedStore = createDuckDbMarketDataStore({
executor: timedExecutor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
// Timed section: universe query planning + adapter row validation/mapping.
let totalListingsMapped = 0;
const uStarted = performance.now();
for (const q of universeQueries) {
const ids = await timedStore.universe(q);
totalListingsMapped += ids.length;
}
const uElapsedMs = performance.now() - uStarted;
const uCallsPerSec = Math.round(UNIVERSE_CALL_COUNT / (uElapsedMs / 1000));
const uRowsPerSec = Math.round(totalListingsMapped / (uElapsedMs / 1000));
// Untimed verification pass: hash SQL, ordered params, and mapped listing IDs.
let uChecksum = 0x811c9dc5;
const verifyExecutor: DuckDbExecutor = {
async run(): Promise<void> {},
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
uChecksum = fnv1aString(uChecksum, sql);
uChecksum = fnv1aByte(uChecksum, params.length);
for (const param of params) {
uChecksum = fnv1aParam(uChecksum, param);
}
return listingRows;
},
};
const verifyStore = createDuckDbMarketDataStore({
executor: verifyExecutor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
for (const q of universeQueries) {
const ids = await verifyStore.universe(q);
for (let i = 0; i < ids.length; i += 1) {
const id = ids[i] ?? 0;
uChecksum = fnv1aByte(uChecksum, id & 0xff);
uChecksum = fnv1aByte(uChecksum, (id >>> 8) & 0xff);
uChecksum = fnv1aByte(uChecksum, (id >>> 16) & 0xff);
uChecksum = fnv1aByte(uChecksum, (id >>> 24) & 0xff);
}
}
const uChecksumHex = uChecksum.toString(16).padStart(8, '0');
const EXPECTED_UNIVERSE_CHECKSUM = 'ef5f1136';
if (uChecksumHex !== EXPECTED_UNIVERSE_CHECKSUM) {
throw new Error(
`Universe benchmark checksum mismatch: expected ${EXPECTED_UNIVERSE_CHECKSUM}, got ${uChecksumHex}.`
);
}
return {
seed: SEED,
calls: UNIVERSE_CALL_COUNT,
listingsPerCall: UNIVERSE_LISTING_COUNT,
totalListingsMapped,
elapsedMs: Number(uElapsedMs.toFixed(2)),
callsPerSec: uCallsPerSec,
rowsPerSec: uRowsPerSec,
checksum: uChecksumHex,
};
}
runUniverseBenchmark()
.then((universe) => {
console.log(
JSON.stringify(
{
seed: SEED,
queries: QUERY_COUNT,
totalParams,
elapsedMs: Number(elapsedMs.toFixed(2)),
queriesPerSec,
checksum: checksumHex,
universe,
},
null,
2
)
);
})
.catch((err: unknown) => {
console.error(err);
process.exitCode = 1;
});

View file

@ -1,196 +0,0 @@
import type { BarRecord } from '../src/market-data-store';
import { type SignalObservation, buildForwardReturnPanel } from '../src/signal-panel';
const SEED = 20261129;
const SESSIONS = 5_040;
const LISTINGS = 3_000;
const SIGNAL_STRIDE_SESSIONS = 21;
const HORIZON_SESSIONS = 5;
const PRE_CUTOFF_SESSIONS = 5_020;
function createMulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
};
}
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
function generateBusinessCalendar(count: number, startYear: number): {
dates: string[];
closeTs: Float64Array;
afterCloseTs: Float64Array;
} {
const dates: string[] = new Array<string>(count);
const closeTs = new Float64Array(count);
const afterCloseTs = new Float64Array(count);
let year = startYear;
let month = 1;
let day = 1;
// 2006-01-01 was a Sunday (dow = 0)
let dow = 0;
let produced = 0;
while (produced < count) {
if (dow !== 0 && dow !== 6) {
const yyyy = String(year).padStart(4, '0');
const mm = String(month).padStart(2, '0');
const dd = String(day).padStart(2, '0');
dates[produced] = `${yyyy}-${mm}-${dd}`;
closeTs[produced] = Date.UTC(year, month - 1, day, 21, 0, 0, 0); // 16:00 ET
afterCloseTs[produced] = Date.UTC(year, month - 1, day, 22, 0, 0, 0); // 17:00 ET
produced += 1;
}
dow = (dow + 1) % 7;
day += 1;
const baseDays = DAYS_IN_MONTH[month] ?? 31;
const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays;
if (day > maxDay) {
day = 1;
month += 1;
if (month > 12) {
month = 1;
year += 1;
}
}
}
return { dates, closeTs, afterCloseTs };
}
function fnv1aByte(hash: number, byte: number): number {
return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0;
}
function fnv1aUint32(hash: number, value: number): number {
const v = value >>> 0;
let h = fnv1aByte(hash, v & 0xff);
h = fnv1aByte(h, (v >>> 8) & 0xff);
h = fnv1aByte(h, (v >>> 16) & 0xff);
h = fnv1aByte(h, (v >>> 24) & 0xff);
return h;
}
function fnv1aBytes(hash: number, bytes: Uint8Array): number {
let h = hash >>> 0;
for (let i = 0; i < bytes.length; i += 1) {
h = Math.imul((h ^ (bytes[i] as number)) >>> 0, 0x01000193) >>> 0;
}
return h;
}
const rng = createMulberry32(SEED);
const calendar = generateBusinessCalendar(SESSIONS, 2006);
const vaultCutoffDate = calendar.dates[PRE_CUTOFF_SESSIONS] as string;
const totalBars = SESSIONS * LISTINGS;
const bars: BarRecord[] = new Array<BarRecord>(totalBars);
const signalsPerListing = Math.ceil(SESSIONS / SIGNAL_STRIDE_SESSIONS);
const signals: SignalObservation[] = new Array<SignalObservation>(LISTINGS * signalsPerListing);
let barIdx = 0;
let sigIdx = 0;
for (let l = 0; l < LISTINGS; l += 1) {
const listingId = l + 1;
let price = 10 + (l % 200) * 0.5;
for (let t = 0; t < SESSIONS; t += 1) {
const ts = calendar.closeTs[t] as number;
price = Math.max(1, price * (1 + (rng() - 0.4995) * 0.02));
bars[barIdx++] = {
listingId,
ts,
open: price,
high: price,
low: price,
close: price,
volume: 10_000,
vwap: price,
knownAt: ts,
};
if (t % SIGNAL_STRIDE_SESSIONS === 0) {
signals[sigIdx++] = {
listingId,
knownAt: calendar.afterCloseTs[t] as number,
value: rng() * 2 - 1,
};
}
}
}
// Timed section: pure buildForwardReturnPanel execution (no fixture generation or checksum).
const started = performance.now();
const result = buildForwardReturnPanel({
bars,
signals,
horizonSessions: HORIZON_SESSIONS,
vaultCutoffDate,
});
const elapsedMs = performance.now() - started;
// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, and typed-array bytes.
let checksum = 0x811c9dc5;
checksum = fnv1aUint32(checksum, result.panel.length);
checksum = fnv1aUint32(checksum, result.sessionDates.length);
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedNoSignal);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedStaleSignal);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedMissingForwardBar);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedNonPositiveClose);
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars);
let emittedObservations = 0;
for (let i = 0; i < result.panel.length; i += 1) {
const slice = result.panel[i];
if (slice === undefined) {
continue;
}
const ids = slice.ids as Int32Array;
const sig = slice.signal as Float64Array;
const ret = slice.forwardReturn as Float64Array;
emittedObservations += ids.length;
checksum = fnv1aBytes(checksum, new Uint8Array(ids.buffer, ids.byteOffset, ids.byteLength));
checksum = fnv1aBytes(checksum, new Uint8Array(sig.buffer, sig.byteOffset, sig.byteLength));
checksum = fnv1aBytes(checksum, new Uint8Array(ret.buffer, ret.byteOffset, ret.byteLength));
}
const checksumHex = checksum.toString(16).padStart(8, '0');
const EXPECTED_CHECKSUM = 'f0f28bdf';
if (checksumHex !== EXPECTED_CHECKSUM) {
throw new Error(
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
);
}
const rowsPerSec = Math.round(totalBars / (elapsedMs / 1000));
console.log(
JSON.stringify(
{
seed: SEED,
sessions: SESSIONS,
listings: LISTINGS,
horizonSessions: HORIZON_SESSIONS,
vaultCutoffDate,
inputBars: totalBars,
inputSignals: signals.length,
panelDates: result.panel.length,
emittedObservations,
elapsedMs: Number(elapsedMs.toFixed(2)),
rowsPerSec,
diagnostics: result.diagnostics,
checksum: checksumHex,
},
null,
2
)
);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,5 @@
// 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 './market-data-store-questdb';
export * from './market-data-store-routed';
export * from './notebook-snapshot';
export * from './signal-panel';
export * from './signal-study';
export * from './trial-ledger';

File diff suppressed because it is too large Load diff

View file

@ -1,462 +0,0 @@
/**
* Pure, dependency-free QuestDB `bars_1m` query planner and injected-executor
* intraday reader for `MarketDataStore.bars` (`timeframe: '1m'`,
* `design/DATA-CONTRACTS.md` §3.B & §4).
*
* Browser-safe and dependency-free: zero `node:*` imports, zero `pg` or
* `@stock-bot/questdb` dependency, zero bare `process` access. SQL execution
* is injected via {@link QuestDbQueryExecutor}, which is structurally
* compatible with `QuestDBClient.query(sql, params)`.
*
* Storage and point-in-time semantics:
* - `bars_1m` stores split-unadjusted raw 1-minute OHLCV, nullable `vwap`,
* `listing_id` (`SYMBOL`, canonical positive decimal string), `known_at`
* (`TIMESTAMP`), and designated timestamp `ts` (`TIMESTAMP`,
* `PARTITION BY MONTH`).
* - Only `adjustment: 'raw'` is supported; `'split'` and `'total'` throw
* {@link MarketDataStoreNotImplementedError}.
* - Query bounds are Vault-fenced via {@link applyVaultFence} before SQL
* planning. Every user-supplied value is bound via `$1..$n` placeholders;
* only ordinal placeholder tokens are generated in SQL text.
* - `ts` and `known_at` are projected as `CAST(... AS LONG)` (UTC epoch
* microseconds) and verified in exact microseconds against the fenced bounds
* before converting to epoch milliseconds or yielding any batch.
*/
import {
type BarBatch,
type BarRecord,
type FencedTimeRange,
type MarketDataStore,
MarketDataStoreValidationError,
type VaultFenceContext,
applyVaultFence,
} from './market-data-store';
import { MarketDataStoreNotImplementedError } from './market-data-store-duckdb';
const INT32_MAX = 2_147_483_647;
const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
const CANONICAL_POSITIVE_INT_RE = /^[1-9]\d*$/;
const CANONICAL_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/;
/** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */
export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000;
/** Input query type derived from `MarketDataStore['bars']`. */
export type QuestDbBars1mQuery = Parameters<MarketDataStore['bars']>[0];
/**
* Injected PGWire SQL executor port, structurally compatible with
* `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`.
*/
export interface QuestDbQueryExecutor {
query(
sql: string,
params: readonly unknown[]
): Promise<{ readonly rows: readonly Record<string, unknown>[] }>;
}
/** Pure output of {@link planBars1mQuery}. */
export interface PlannedQuestDbBars1mQuery {
readonly sql: string;
readonly params: readonly string[];
readonly fence: FencedTimeRange;
}
/** Configuration for {@link createQuestDbIntradayBarsReader}. */
export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext {
readonly executor: QuestDbQueryExecutor;
/** Maximum number of bars per yielded `BarBatch`. Defaults to `50_000`. */
readonly batchSize?: number;
}
interface InternalPlannedBars1mQuery {
readonly planned: PlannedQuestDbBars1mQuery;
readonly requestedListingIds: ReadonlySet<number>;
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function validateVaultCutoffTs(vaultCutoffTs: unknown): number {
if (
typeof vaultCutoffTs !== 'number' ||
!Number.isSafeInteger(vaultCutoffTs) ||
Math.abs(vaultCutoffTs) > MAX_ECMASCRIPT_EPOCH_MS ||
vaultCutoffTs <= -MAX_ECMASCRIPT_EPOCH_MS
) {
throw new MarketDataStoreValidationError(
`Invalid epoch millisecond timestamp for "vaultCutoffTs": ${String(vaultCutoffTs)}.`,
'vaultCutoffTs'
);
}
return vaultCutoffTs === 0 ? 0 : vaultCutoffTs;
}
function validatePositiveInt32ListingIds(raw: unknown): number[] {
if (!Array.isArray(raw) || raw.length === 0) {
throw new MarketDataStoreValidationError(
'Expected a non-empty array of positive INT32 listing IDs for "listingIds".',
'listingIds'
);
}
const seen = new Set<number>();
const normalized: number[] = [];
for (let i = 0; i < raw.length; i += 1) {
const id: unknown = raw[i];
if (
typeof id !== 'number' ||
!Number.isSafeInteger(id) ||
id < 1 ||
id > INT32_MAX
) {
throw new MarketDataStoreValidationError(
`Invalid positive INT32 listing ID at listingIds[${i}]: ${String(id)}.`,
'listingIds'
);
}
if (!seen.has(id)) {
seen.add(id);
normalized.push(id);
}
}
normalized.sort((a, b) => a - b);
return normalized;
}
function formatUtcIsoMs(epochMs: number): string {
return new Date(epochMs).toISOString();
}
function planBars1mQueryInternal(
q: QuestDbBars1mQuery,
ctx: VaultFenceContext
): InternalPlannedBars1mQuery {
if (!isPlainRecord(ctx)) {
throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx');
}
if (!isPlainRecord(q)) {
throw new MarketDataStoreValidationError('Expected a bars query object.', 'query');
}
const timeframe: unknown = q.timeframe;
if (timeframe !== '1m') {
throw new MarketDataStoreValidationError(
`Invalid bars timeframe "${String(timeframe)}". Expected '1m'.`,
'timeframe'
);
}
const adjustment: unknown = q.adjustment;
if (adjustment === 'split' || adjustment === 'total') {
throw new MarketDataStoreNotImplementedError(
'bars',
`Adjustment '${adjustment}' is not supported for intraday '1m' bars; bars_1m stores raw split-unadjusted values.`
);
}
if (adjustment !== 'raw') {
throw new MarketDataStoreValidationError(
`Invalid bars adjustment "${String(adjustment)}". Expected 'raw'.`,
'adjustment'
);
}
const sortedListingIds = validatePositiveInt32ListingIds(q.listingIds);
const fence = applyVaultFence(
{
from: q.from,
to: q.to,
asOf: q.asOf,
scope: q.scope,
},
{
vaultCutoffTs: ctx.vaultCutoffTs,
vaultOperatorAuthorized: ctx.vaultOperatorAuthorized === true,
}
);
const listingPlaceholders = sortedListingIds.map((_, index) => `$${index + 3}`).join(', ');
const asOfPlaceholder = `$${sortedListingIds.length + 3}`;
const sql =
'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' +
'FROM bars_1m ' +
`WHERE ts >= $1 AND ts <= $2 AND listing_id IN (${listingPlaceholders}) AND known_at <= ${asOfPlaceholder} ` +
'ORDER BY ts, listing_id';
const params: string[] = [
formatUtcIsoMs(fence.fromMs),
formatUtcIsoMs(fence.toMs),
...sortedListingIds.map(id => String(id)),
formatUtcIsoMs(fence.asOfMs),
];
return {
planned: { sql, params, fence },
requestedListingIds: new Set(sortedListingIds),
};
}
/**
* Pure, Vault-fenced, parameterized SQL planner for QuestDB `bars_1m`.
*
* Binds `from`, `to`, and `asOf` as exact millisecond UTC ISO-8601 strings and
* deduplicated, numerically sorted positive INT32 `listingIds` as canonical
* decimal `SYMBOL` strings.
*/
export function planBars1mQuery(
q: QuestDbBars1mQuery,
ctx: VaultFenceContext
): PlannedQuestDbBars1mQuery {
return planBars1mQueryInternal(q, ctx).planned;
}
function parseListingIdSymbol(
row: Record<string, unknown>,
rowIndex: number,
requestedListingIds: ReadonlySet<number>
): number {
const raw = row.listing_id;
if (typeof raw !== 'string' || !CANONICAL_POSITIVE_INT_RE.test(raw)) {
throw new MarketDataStoreValidationError(
`Invalid bars_1m listing_id SYMBOL in result row ${rowIndex}: ${String(raw)}.`,
'listing_id'
);
}
const parsed = Number(raw);
if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > INT32_MAX) {
throw new MarketDataStoreValidationError(
`Out-of-range bars_1m listing_id SYMBOL in result row ${rowIndex}: "${raw}".`,
'listing_id'
);
}
if (!requestedListingIds.has(parsed)) {
throw new MarketDataStoreValidationError(
`Unexpected unrequested listing_id ${parsed} in bars_1m result row ${rowIndex}.`,
'listing_id'
);
}
return parsed;
}
function parseTimestampMicros(
row: Record<string, unknown>,
column: 'ts_us' | 'known_at_us',
field: 'ts' | 'known_at',
rowIndex: number
): bigint {
const raw = row[column];
if (typeof raw === 'bigint') {
return raw;
}
if (typeof raw === 'string' && CANONICAL_SIGNED_INT_RE.test(raw)) {
return BigInt(raw);
}
if (typeof raw === 'number' && Number.isSafeInteger(raw)) {
return BigInt(raw);
}
throw new MarketDataStoreValidationError(
`Invalid bars_1m timestamp column "${column}" in result row ${rowIndex}: ${String(raw)}.`,
field
);
}
function microsToEpochMs(
us: bigint,
field: 'ts' | 'known_at',
rowIndex: number,
rounding: 'floor' | 'ceil'
): number {
const quotient = us / 1000n;
const remainder = us % 1000n;
const msBigInt =
rounding === 'ceil'
? remainder > 0n
? quotient + 1n
: quotient
: remainder < 0n
? quotient - 1n
: quotient;
const ms = Number(msBigInt);
if (!Number.isSafeInteger(ms) || Math.abs(ms) > MAX_ECMASCRIPT_EPOCH_MS) {
throw new MarketDataStoreValidationError(
`Out-of-range bars_1m timestamp "${field}" (${us.toString()} us) in result row ${rowIndex}.`,
field
);
}
return ms === 0 ? 0 : ms;
}
function readRequiredFiniteNumber(
row: Record<string, unknown>,
key: 'open' | 'high' | 'low' | 'close' | 'volume',
rowIndex: number
): number {
const val = row[key];
if (typeof val !== 'number' || !Number.isFinite(val)) {
throw new MarketDataStoreValidationError(
`Invalid numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`,
key
);
}
return val === 0 ? 0 : val;
}
function readNullableFiniteNumber(
row: Record<string, unknown>,
key: 'vwap',
rowIndex: number
): number | null {
const val = row[key];
if (val === null || val === undefined) {
return null;
}
if (typeof val !== 'number' || !Number.isFinite(val)) {
throw new MarketDataStoreValidationError(
`Invalid nullable numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`,
key
);
}
return val === 0 ? 0 : val;
}
function mapBars1mRows(
rows: readonly Record<string, unknown>[],
fence: FencedTimeRange,
requestedListingIds: ReadonlySet<number>
): BarRecord[] {
const fromUs = BigInt(fence.fromMs) * 1000n;
const toUs = BigInt(fence.toMs) * 1000n;
const asOfUs = BigInt(fence.asOfMs) * 1000n;
const out: BarRecord[] = new Array(rows.length);
for (let i = 0; i < rows.length; i += 1) {
const raw = rows[i];
if (!isPlainRecord(raw)) {
throw new MarketDataStoreValidationError(
`Executor returned a non-object bar row at index ${i}.`,
'rows'
);
}
const listingId = parseListingIdSymbol(raw, i, requestedListingIds);
const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i);
if (tsUs < fromUs || tsUs > toUs) {
throw new MarketDataStoreValidationError(
`Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us.`,
'ts'
);
}
const knownAtUs = parseTimestampMicros(raw, 'known_at_us', 'known_at', i);
if (knownAtUs > asOfUs) {
throw new MarketDataStoreValidationError(
`Row ${i} availability timestamp known_at (${knownAtUs.toString()} us) exceeds fenced asOf (${asOfUs.toString()} us).`,
'known_at'
);
}
out[i] = {
listingId,
ts: microsToEpochMs(tsUs, 'ts', i, 'floor'),
open: readRequiredFiniteNumber(raw, 'open', i),
high: readRequiredFiniteNumber(raw, 'high', i),
low: readRequiredFiniteNumber(raw, 'low', i),
close: readRequiredFiniteNumber(raw, 'close', i),
volume: readRequiredFiniteNumber(raw, 'volume', i),
vwap: readNullableFiniteNumber(raw, 'vwap', i),
// Round sub-millisecond availability up so replay never treats a bar as known before arrival.
knownAt: microsToEpochMs(knownAtUs, 'known_at', i, 'ceil'),
};
}
return out;
}
/**
* Creates a read-only intraday `bars` reader backed by an injected
* {@link QuestDbQueryExecutor} over QuestDB `bars_1m`.
*
* Validates all inputs and applies the Vault fence before invoking
* `executor.query(...)`. Validates and maps all returned rows (including
* exact-microsecond defence-in-depth checks against `fence`) before yielding
* batches of at most `batchSize` rows (default `50_000`).
*/
export function createQuestDbIntradayBarsReader(
options: QuestDbIntradayBarsReaderOptions
): Pick<MarketDataStore, 'bars'> {
if (!isPlainRecord(options)) {
throw new MarketDataStoreValidationError(
'Expected a QuestDbIntradayBarsReaderOptions object.',
'options'
);
}
const executor: unknown = options.executor;
if (!isPlainRecord(executor) || typeof executor.query !== 'function') {
throw new MarketDataStoreValidationError(
'Expected `executor` with a `query(sql, params)` method.',
'executor'
);
}
const typedExecutor = executor as unknown as QuestDbQueryExecutor;
const vaultCutoffTs = validateVaultCutoffTs(options.vaultCutoffTs);
if (
options.vaultOperatorAuthorized !== undefined &&
typeof options.vaultOperatorAuthorized !== 'boolean'
) {
throw new MarketDataStoreValidationError(
`Invalid vaultOperatorAuthorized "${String(options.vaultOperatorAuthorized)}". Expected a boolean.`,
'vaultOperatorAuthorized'
);
}
const batchSize =
options.batchSize === undefined ? DEFAULT_QUESTDB_BARS_BATCH_SIZE : options.batchSize;
if (typeof batchSize !== 'number' || !Number.isSafeInteger(batchSize) || batchSize < 1) {
throw new MarketDataStoreValidationError(
`Invalid batchSize "${String(options.batchSize)}". Expected a positive safe integer.`,
'batchSize'
);
}
const planCtx: VaultFenceContext = {
vaultCutoffTs,
vaultOperatorAuthorized: options.vaultOperatorAuthorized === true,
};
return {
async *bars(q: QuestDbBars1mQuery): AsyncIterable<BarBatch> {
const { planned, requestedListingIds } = planBars1mQueryInternal(q, planCtx);
const result: unknown = await typedExecutor.query(planned.sql, [...planned.params]);
if (!isPlainRecord(result) || !Array.isArray(result.rows)) {
throw new MarketDataStoreValidationError(
'Executor returned a malformed result; expected `{ rows: Record<string, unknown>[] }`.',
'rows'
);
}
const mapped = mapBars1mRows(
result.rows as readonly Record<string, unknown>[],
planned.fence,
requestedListingIds
);
if (mapped.length === 0) {
return;
}
if (mapped.length <= batchSize) {
yield { rows: mapped };
return;
}
for (let offset = 0; offset < mapped.length; offset += batchSize) {
yield { rows: mapped.slice(offset, offset + batchSize) };
}
},
};
}

View file

@ -1,192 +0,0 @@
/**
* Pure, dependency-free `MarketDataStore` router that dispatches intraday
* `bars` queries (`timeframe: '1m'`) to an injected intraday reader (such as
* {@link createQuestDbIntradayBarsReader}) and routes every other `bars`
* timeframe and all other `MarketDataStore` methods to the injected daily
* store (such as {@link createDuckDbMarketDataStore}).
*
* Browser-safe and dependency-free: zero `node:*` imports, zero bare `process`
* access, and no database or filesystem I/O.
*
* Vault & point-in-time semantics:
* - This router adds no Vault logic of its own; each delegate continues to
* enforce its own Vault holdout fence and point-in-time predicates.
* - Callers MUST construct both `daily` and `intraday` with the exact same
* `vaultCutoffTs` and `vaultOperatorAuthorized` values (and pass the same
* `vaultCutoffTs` to MCP tools such as `createQueryDataTool`, which is
* always Vault-fenced) so the holdout boundary is identical across
* timeframes.
* - The QuestDB intraday reader (`createQuestDbIntradayBarsReader`) supports
* split-unadjusted `adjustment: 'raw'` `1m` bars; non-`'raw'` `1m` requests
* and unsupported timeframes (`'5m'`, `'1h'`) are handled by the respective
* delegate without modification.
*/
import { type MarketDataStore, MarketDataStoreValidationError } from './market-data-store';
/** Configuration for {@link createRoutedMarketDataStore}. */
export interface RoutedMarketDataStoreOptions {
/** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */
readonly daily: MarketDataStore;
/** Backing intraday reader for `bars` queries with `timeframe: '1m'`. */
readonly intraday: Pick<MarketDataStore, 'bars'>;
}
const REQUIRED_DAILY_METHODS = [
'bars',
'crossSection',
'fundamentalsAsOf',
'events',
'shortsAsOf',
'macroAsOf',
'fx',
'universe',
] as const satisfies readonly (keyof MarketDataStore)[];
function isPlainObject(value: unknown): value is Record<string, unknown> {
if (typeof value !== 'object' || value === null) {
return false;
}
const proto: unknown = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function isDelegateObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isIntraday1mBarsQuery(q: unknown): boolean {
return (
typeof q === 'object' &&
q !== null &&
!Array.isArray(q) &&
(q as { readonly timeframe?: unknown }).timeframe === '1m'
);
}
/**
* Composes a daily `MarketDataStore` and an intraday `bars` reader into a
* single read-only `MarketDataStore`.
*
* Routing rules:
* - `bars(q)` with `q.timeframe === '1m'` delegates directly to
* `options.intraday.bars(q)` and returns its `AsyncIterable<BarBatch>`
* unchanged (preserving receiver, query identity, lazy iteration, and error
* timing).
* - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed
* runtime inputs) delegates directly to `options.daily.bars(q)`.
* - All other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`,
* `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly
* to `options.daily` and return its original promise.
*
* Vault fence note:
* Both `daily` and `intraday` MUST be constructed with the exact same
* `vaultCutoffTs` and `vaultOperatorAuthorized` settings. The QuestDB intraday
* reader serves raw (`adjustment: 'raw'`) `1m` bars.
*
* @example
* ```ts
* const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0);
* const vaultOperatorAuthorized = false;
*
* const daily = createDuckDbMarketDataStore({
* executor: duckDbExecutor,
* curatedRoot: '/mnt/data/stockbot/curated',
* vaultCutoffTs,
* vaultOperatorAuthorized,
* });
* const intraday = createQuestDbIntradayBarsReader({
* executor: questDbExecutor,
* vaultCutoffTs,
* vaultOperatorAuthorized,
* });
* const store = createRoutedMarketDataStore({ daily, intraday });
* // `createQueryDataTool` is always Vault-fenced and accepts only `vaultCutoffTs`.
* const queryDataTool = createQueryDataTool({
* store,
* vaultContext: { vaultCutoffTs },
* });
* ```
*/
export function createRoutedMarketDataStore(
options: RoutedMarketDataStoreOptions
): MarketDataStore {
if (!isPlainObject(options)) {
throw new MarketDataStoreValidationError(
'Expected a plain RoutedMarketDataStoreOptions object.',
'options'
);
}
const rawDaily: unknown = options.daily;
if (!isDelegateObject(rawDaily)) {
throw new MarketDataStoreValidationError(
'Expected `daily` to be a MarketDataStore object.',
'daily'
);
}
for (const method of REQUIRED_DAILY_METHODS) {
if (typeof rawDaily[method] !== 'function') {
throw new MarketDataStoreValidationError(
`Expected \`daily.${method}\` to be a function.`,
`daily.${method}`
);
}
}
const rawIntraday: unknown = options.intraday;
if (!isDelegateObject(rawIntraday)) {
throw new MarketDataStoreValidationError(
'Expected `intraday` to be an object with a `bars` method.',
'intraday'
);
}
if (typeof rawIntraday.bars !== 'function') {
throw new MarketDataStoreValidationError(
'Expected `intraday.bars` to be a function.',
'intraday.bars'
);
}
const daily = options.daily;
const intraday = options.intraday;
return {
bars(q) {
if (isIntraday1mBarsQuery(q)) {
return intraday.bars(q);
}
return daily.bars(q);
},
crossSection(q) {
return daily.crossSection(q);
},
fundamentalsAsOf(q) {
return daily.fundamentalsAsOf(q);
},
events(q) {
return daily.events(q);
},
shortsAsOf(q) {
return daily.shortsAsOf(q);
},
macroAsOf(q) {
return daily.macroAsOf(q);
},
fx(q) {
return daily.fx(q);
},
universe(q) {
return daily.universe(q);
},
};
}

View file

@ -1,278 +0,0 @@
/**
* Bar-derived {@link SessionDatesPort} adapter for the MCP copilot `event_study`
* exchange-calendar resolver (`createExchangeCalendarResolver`).
*
* Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare
* `process` access, no `pg` dependency, and no DuckDB driver import.
*
* Daily bar timestamp convention:
* - In `libs/research/src/market-data-store-duckdb.ts`, `planBars1dQuery`
* projects `epoch_ms(b.ts) AS ts` and `mapBarRows` validates it as an integer
* UTC epoch millisecond value on `BarRecord.ts`.
* - In `tools/curate-etl/src/curate_bars.rs`, curated daily bars are stamped at
* `16:00:00 America/New_York` (`16:00 ET`), which converts to `20:00:00Z`
* (EDT) or `21:00:00Z` (EST) on the same UTC calendar date.
* - Therefore, `Math.floor(bar.ts / MS_PER_DAY)` yields the session's integer
* UTC day key (`formatDayKeyUtc`). Close timestamps and optional early-close
* overrides remain owned by `createExchangeCalendarResolver`.
*
* Vault fence behavior:
* - Queries `store.bars` with `timeframe: '1d'` and `adjustment: 'raw'`,
* omitting `scope` and `asOf` so the injected store applies its default
* `'vault_fenced'` scope. Never passes `'vault_evaluation_only'`.
* - Errors thrown by the store (including `VaultHoldoutFenceError`) propagate
* unchanged.
*/
import type { MarketDataStore } from '../../market-data-store';
import {
MS_PER_DAY,
formatDayKeyUtc,
isPlainRecord,
isValidEpochMs,
isValidInt32,
parseCalendarDayKey,
} from '../../panel-shared';
import type { SessionDatesPort, SessionDatesQuery } from './exchange-calendars';
/** Error codes thrown by {@link BarSessionDatesError}. */
export type BarSessionDatesErrorCode =
| 'invalid_options'
| 'unknown_calendar'
| 'invalid_query'
| 'invalid_bar';
/** Optional error constructor metadata for {@link BarSessionDatesError}. */
export interface BarSessionDatesErrorOptions {
readonly cause?: unknown;
}
/** Typed fail-closed error thrown by {@link createBarSessionDatesPort}. */
export class BarSessionDatesError extends RangeError {
readonly code: BarSessionDatesErrorCode;
override readonly cause?: unknown;
constructor(
code: BarSessionDatesErrorCode,
message: string,
options?: BarSessionDatesErrorOptions
) {
super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
this.name = 'BarSessionDatesError';
this.code = code;
if (options?.cause !== undefined) {
this.cause = options.cause;
}
Object.setPrototypeOf(this, new.target.prototype);
}
}
/** Factory options for {@link createBarSessionDatesPort}. */
export interface BarSessionDatesPortOptions {
readonly store: Pick<MarketDataStore, 'bars'>;
/**
* Caller-configured reference listing IDs per `exchange.calendar_code`
* (e.g. `XNYS`, `XTSE`). The union of their daily bars defines the exchange's
* session dates.
*/
readonly referenceListingIds: Readonly<Record<string, readonly number[]>>;
}
interface CalendarReferenceConfig {
readonly listingIds: readonly number[];
readonly listingIdSet: ReadonlySet<number>;
}
function isPlainObjectRecord(value: unknown): value is Record<string, unknown> {
if (typeof value !== 'object' || value === null) {
return false;
}
const proto: unknown = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function parseQueryDayKey(value: unknown, field: string): number {
return parseCalendarDayKey(value, field, (message, cause) =>
new BarSessionDatesError(
'invalid_query',
message,
cause !== undefined ? { cause } : undefined
)
);
}
function validateOptions(options: BarSessionDatesPortOptions): {
readonly store: Pick<MarketDataStore, 'bars'>;
readonly calendars: ReadonlyMap<string, CalendarReferenceConfig>;
} {
if (!isPlainRecord(options)) {
throw new BarSessionDatesError(
'invalid_options',
'Invalid options: expected an object with store and referenceListingIds.'
);
}
const { store, referenceListingIds } = options;
if (typeof store !== 'object' || store === null || typeof store.bars !== 'function') {
throw new BarSessionDatesError(
'invalid_options',
'Invalid "store": expected an object with a callable bars(query) method.'
);
}
if (!isPlainObjectRecord(referenceListingIds)) {
throw new BarSessionDatesError(
'invalid_options',
'Invalid "referenceListingIds": expected a plain object mapping calendar codes to positive INT32 listing ID arrays.'
);
}
const calendars = new Map<string, CalendarReferenceConfig>();
const entries = Object.entries(referenceListingIds);
for (let i = 0; i < entries.length; i += 1) {
const [calendarCode, rawIds] = entries[i] as [string, unknown];
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
throw new BarSessionDatesError(
'invalid_options',
`Invalid "referenceListingIds" calendar code "${calendarCode}": expected a non-empty trimmed string.`
);
}
if (!Array.isArray(rawIds) || rawIds.length === 0) {
throw new BarSessionDatesError(
'invalid_options',
`Invalid "referenceListingIds.${calendarCode}": expected a non-empty array of positive 32-bit integer listing IDs.`
);
}
const copiedIds: number[] = [];
const idSet = new Set<number>();
for (let j = 0; j < rawIds.length; j += 1) {
const id: unknown = rawIds[j];
if (!isValidInt32(id) || id <= 0) {
throw new BarSessionDatesError(
'invalid_options',
`Invalid "referenceListingIds.${calendarCode}[${j}]": expected a positive 32-bit integer, got ${String(id)}.`
);
}
if (idSet.has(id)) {
throw new BarSessionDatesError(
'invalid_options',
`Duplicate listing ID ${id} in "referenceListingIds.${calendarCode}".`
);
}
idSet.add(id);
copiedIds.push(id);
}
calendars.set(calendarCode, {
listingIds: copiedIds,
listingIdSet: idSet,
});
}
return { store, calendars };
}
/**
* Creates a {@link SessionDatesPort} backed by Vault-fenced daily bars
* (`timeframe: '1d'`, `adjustment: 'raw'`) for caller-configured reference
* listings per `exchange.calendar_code`.
*/
export function createBarSessionDatesPort(
options: BarSessionDatesPortOptions
): SessionDatesPort {
const { store, calendars } = validateOptions(options);
return {
async listSessionDates(query: SessionDatesQuery): Promise<readonly string[]> {
if (!isPlainRecord(query)) {
throw new BarSessionDatesError(
'invalid_query',
'Invalid query: expected an object with calendarCode, fromDate, and toDate.'
);
}
if (typeof query.calendarCode !== 'string') {
throw new BarSessionDatesError(
'invalid_query',
'Invalid "calendarCode": expected a string.'
);
}
const config = calendars.get(query.calendarCode);
if (config === undefined) {
throw new BarSessionDatesError(
'unknown_calendar',
`No reference listings configured for calendarCode "${query.calendarCode}".`
);
}
const fromDayKey = parseQueryDayKey(query.fromDate, 'fromDate');
const toDayKey = parseQueryDayKey(query.toDate, 'toDate');
if (fromDayKey > toDayKey) {
throw new BarSessionDatesError(
'invalid_query',
`Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".`
);
}
const dayKeys = new Set<number>();
const stream = store.bars({
listingIds: config.listingIds.slice(),
timeframe: '1d',
from: query.fromDate,
to: query.toDate,
adjustment: 'raw',
});
for await (const batch of stream) {
if (!isPlainRecord(batch) || !Array.isArray(batch.rows)) {
throw new BarSessionDatesError(
'invalid_bar',
'Invalid bar batch: expected an object with a rows array.'
);
}
const rows = batch.rows;
for (let i = 0; i < rows.length; i += 1) {
const bar: unknown = rows[i];
if (!isPlainRecord(bar)) {
throw new BarSessionDatesError(
'invalid_bar',
`Invalid bar row at index ${i}: expected a plain object.`
);
}
if (!isValidEpochMs(bar.ts)) {
throw new BarSessionDatesError(
'invalid_bar',
`Invalid bar timestamp at index ${i}: expected a finite integer epoch ms, got ${String(bar.ts)}.`
);
}
if (!isValidInt32(bar.listingId) || !config.listingIdSet.has(bar.listingId)) {
throw new BarSessionDatesError(
'invalid_bar',
`Unexpected bar listingId ${String(bar.listingId)} for calendarCode "${query.calendarCode}".`
);
}
const dayKey = Math.floor(bar.ts / MS_PER_DAY);
if (dayKey >= fromDayKey && dayKey <= toDayKey) {
dayKeys.add(dayKey);
}
}
}
if (dayKeys.size === 0) {
return [];
}
const sortedDayKeys = Array.from(dayKeys).sort((a, b) => a - b);
return sortedDayKeys.map(formatDayKeyUtc);
},
};
}

View file

@ -1,749 +0,0 @@
/**
* Exchange-calendar resolver and read-only PostgreSQL listing-calendar adapter
* for the MCP copilot `event_study` tool (`EventStudyExchangeCalendarResolver`).
*
* Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare
* `process` access, and no runtime `pg` dependency.
*
* Eastern Time DST schedule (`1976-01-01..=2030-12-31`, matching
* `tools/curate-etl/src/session_close.rs` for `America/New_York` /
* `America/Toronto`):
* - `1976..=1986`: last Sunday of April -> last Sunday of October.
* - `1987..=2006`: first Sunday of April -> last Sunday of October.
* - `2007..=2030`: second Sunday of March -> first Sunday of November.
*
* Using the session-date convention (inclusive spring boundary, exclusive fall
* boundary), EDT is `UTC-4` and EST is `UTC-5`.
*/
import type {
EventStudyExchangeCalendars,
ExchangeSessionClose,
} from '../../event-panel';
import {
MS_PER_DAY,
isPlainRecord,
isValidInt32,
parseCalendarDayKey,
} from '../../panel-shared';
import type {
EventStudyExchangeCalendarQuery,
EventStudyExchangeCalendarResolver,
} from '../tools/event-study';
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
const MS_PER_MINUTE = 60_000;
const EDT_UTC_OFFSET_MINUTES = 4 * 60;
const EST_UTC_OFFSET_MINUTES = 5 * 60;
/** First Gregorian year supported by the Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR = 1976;
/** Last Gregorian year supported by the Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR = 2030;
/** Inclusive lower bound (`YYYY-MM-DD`) of the supported Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE = '1976-01-01';
/** Inclusive upper bound (`YYYY-MM-DD`) of the supported Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE = '2030-12-31';
/** Default Eastern Time close minute of day (`16:00 ET` = `960`). */
export const EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET = 16 * 60;
/** Minimum allowed Eastern Time early-close override minute of day (`00:01 ET`). */
export const EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET = 1;
/** Maximum allowed Eastern Time close minute of day (`16:00 ET`). */
export const EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET = 16 * 60;
/** Epoch day for `1976-01-01` (`Date.UTC(1976, 0, 1) / MS_PER_DAY`). */
const MIN_SUPPORTED_DAY_KEY = 2_191;
/** Epoch day for `2030-12-31` (`Date.UTC(2030, 11, 31) / MS_PER_DAY`). */
const MAX_SUPPORTED_DAY_KEY = 22_279;
const SUPPORTED_YEAR_COUNT =
EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR + 1;
/** Error codes thrown by {@link PostgresListingCalendarError}. */
export type PostgresListingCalendarErrorCode =
| 'INVALID_EXECUTOR'
| 'INVALID_SCHEMA'
| 'INVALID_ROW';
/** Typed validation error thrown by the PostgreSQL listing-calendar adapter. */
export class PostgresListingCalendarError extends RangeError {
readonly code: PostgresListingCalendarErrorCode;
constructor(code: PostgresListingCalendarErrorCode, message: string) {
super(message);
this.name = 'PostgresListingCalendarError';
this.code = code;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/** Error codes thrown by {@link ExchangeCalendarResolverError}. */
export type ExchangeCalendarResolverErrorCode =
| 'INVALID_OPTION'
| 'INVALID_QUERY'
| 'UNSUPPORTED_DATE'
| 'INVALID_LISTING_CALENDAR_ROW'
| 'MISSING_LISTING_CALENDAR'
| 'UNEXPECTED_LISTING_CALENDAR'
| 'CONFLICTING_LISTING_CALENDAR'
| 'INVALID_SESSION_DATES';
/** Optional error constructor metadata for {@link ExchangeCalendarResolverError}. */
export interface ExchangeCalendarResolverErrorOptions {
readonly cause?: unknown;
}
/** Typed validation and fail-closed integrity error thrown by {@link createExchangeCalendarResolver}. */
export class ExchangeCalendarResolverError extends RangeError {
readonly code: ExchangeCalendarResolverErrorCode;
override readonly cause?: unknown;
constructor(
code: ExchangeCalendarResolverErrorCode,
message: string,
options?: ExchangeCalendarResolverErrorOptions
) {
super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
this.name = 'ExchangeCalendarResolverError';
this.code = code;
if (options?.cause !== undefined) {
this.cause = options.cause;
}
Object.setPrototypeOf(this, new.target.prototype);
}
}
/**
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module
* has no runtime dependency on `pg` and is unit-testable with a fake executor.
*/
export interface ListingCalendarExecutor {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }>;
}
/** Factory options for {@link createPostgresListingCalendarPort}. */
export interface PostgresListingCalendarPortOptions {
readonly executor: ListingCalendarExecutor;
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
readonly schema?: string;
}
/** One listing-to-exchange-calendar mapping row returned by {@link ListingCalendarPort}. */
export interface ListingCalendarRow {
readonly listingId: number;
readonly calendarCode: string;
}
/** Injected port resolving `listingId` -> `exchange.calendar_code`. */
export interface ListingCalendarPort {
getListingCalendars(
listingIds: readonly number[]
): Promise<readonly ListingCalendarRow[]> | readonly ListingCalendarRow[];
}
/** Query passed to {@link SessionDatesPort.listSessionDates}. */
export interface SessionDatesQuery {
readonly calendarCode: string;
readonly fromDate: string;
readonly toDate: string;
}
/**
* Injected port supplying strictly ascending, unique `YYYY-MM-DD` exchange session
* dates inside `[fromDate, toDate]` for one exchange calendar code.
*/
export interface SessionDatesPort {
listSessionDates(query: SessionDatesQuery): Promise<readonly string[]> | readonly string[];
}
/**
* Optional caller-supplied early-close overrides keyed by
* `{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, where
* `minuteOfDayEastern` is an integer in `(0, 960]` (e.g. `780` = `13:00 ET`).
*/
export type EarlyCloseOverrides = Readonly<Record<string, Readonly<Record<string, number>>>>;
/** Factory options for {@link createExchangeCalendarResolver}. */
export interface ExchangeCalendarResolverOptions {
readonly listingCalendars: ListingCalendarPort;
readonly sessionDates: SessionDatesPort;
readonly earlyCloses?: EarlyCloseOverrides;
}
interface RawListingCalendarRow {
readonly listing_id: unknown;
readonly calendar_code: unknown;
}
interface DstBoundsTable {
readonly startDay: Int32Array;
readonly endDay: Int32Array;
}
let cachedDstBounds: DstBoundsTable | null = null;
/** ISO-8601 weekday for an epoch day: `1 = Monday`, ..., `7 = Sunday`. */
function isoWeekday(epochDay: number): number {
// 1970-01-01 (epochDay === 0) was Thursday (ISO 4).
return (((epochDay + 3) % 7) + 7) % 7 + 1;
}
function ymdToEpochDay(year: number, month: number, day: number): number {
return Date.UTC(year, month - 1, day) / MS_PER_DAY;
}
function nthSundayOfMonth(year: number, month: number, nth: number): number {
const first = ymdToEpochDay(year, month, 1);
const firstWd = isoWeekday(first);
const delta = (7 - firstWd) % 7;
return first + delta + (nth - 1) * 7;
}
function lastSundayOfMonth(year: number, month: number): number {
const nextYear = month === 12 ? year + 1 : year;
const nextMonth = month === 12 ? 1 : month + 1;
const last = ymdToEpochDay(nextYear, nextMonth, 1) - 1;
const lastWd = isoWeekday(last);
return last - (lastWd % 7);
}
function getDstBoundsTable(): DstBoundsTable {
if (cachedDstBounds !== null) {
return cachedDstBounds;
}
const startDay = new Int32Array(SUPPORTED_YEAR_COUNT);
const endDay = new Int32Array(SUPPORTED_YEAR_COUNT);
for (
let year = EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR;
year <= EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR;
year += 1
) {
let dstStart: number;
let dstEnd: number;
if (year <= 1986) {
dstStart = lastSundayOfMonth(year, 4);
dstEnd = lastSundayOfMonth(year, 10);
} else if (year <= 2006) {
dstStart = nthSundayOfMonth(year, 4, 1);
dstEnd = lastSundayOfMonth(year, 10);
} else {
dstStart = nthSundayOfMonth(year, 3, 2);
dstEnd = nthSundayOfMonth(year, 11, 1);
}
const idx = year - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR;
startDay[idx] = dstStart;
endDay[idx] = dstEnd;
}
cachedDstBounds = { startDay, endDay };
return cachedDstBounds;
}
function assertSupportedDayKey(dayKey: number, dateStr: string, field: string): void {
if (dayKey < MIN_SUPPORTED_DAY_KEY || dayKey > MAX_SUPPORTED_DAY_KEY) {
throw new ExchangeCalendarResolverError(
'UNSUPPORTED_DATE',
`Unsupported "${field}" date "${dateStr}": must fall within ${EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE}..=${EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE}.`
);
}
}
function easternSessionCloseUtcMs(dayKey: number, closeMinuteEt: number): number {
const year = new Date(dayKey * MS_PER_DAY).getUTCFullYear();
const table = getDstBoundsTable();
const idx = year - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR;
const isEdt =
dayKey >= (table.startDay[idx] as number) && dayKey < (table.endDay[idx] as number);
const utcOffsetMinutes = isEdt ? EDT_UTC_OFFSET_MINUTES : EST_UTC_OFFSET_MINUTES;
return dayKey * MS_PER_DAY + (closeMinuteEt + utcOffsetMinutes) * MS_PER_MINUTE;
}
function defineDataProperty<T>(target: Record<string, T>, key: string, value: T): void {
Object.defineProperty(target, key, {
value,
enumerable: true,
writable: true,
configurable: true,
});
}
function buildListingCalendarSql(schemaPrefix: string): string {
const listingTable = `${schemaPrefix}listing`;
const exchangeTable = `${schemaPrefix}exchange`;
return [
'SELECT',
' l.listing_id AS listing_id,',
' e.calendar_code AS calendar_code',
`FROM ${listingTable} l`,
`INNER JOIN ${exchangeTable} e ON e.mic = l.mic`,
'WHERE l.listing_id = ANY($1::integer[])',
'ORDER BY l.listing_id ASC',
].join('\n');
}
function validatePostgresFactoryOptions(options: PostgresListingCalendarPortOptions): {
readonly executor: ListingCalendarExecutor;
readonly schemaPrefix: string;
} {
if (typeof options !== 'object' || options === null) {
throw new PostgresListingCalendarError(
'INVALID_EXECUTOR',
'Invalid options: expected an object with a ListingCalendarExecutor.'
);
}
const { executor, schema } = options;
if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') {
throw new PostgresListingCalendarError(
'INVALID_EXECUTOR',
'Invalid executor: expected an object with a callable query(text, params?) method.'
);
}
if (schema === undefined) {
return { executor, schemaPrefix: '' };
}
if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) {
throw new PostgresListingCalendarError(
'INVALID_SCHEMA',
'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.'
);
}
return { executor, schemaPrefix: `"${schema}".` };
}
function mapRawListingCalendarRow(raw: unknown): ListingCalendarRow {
if (!isPlainRecord(raw)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid security-master row: expected a non-null plain object.'
);
}
const row = raw as unknown as RawListingCalendarRow;
if (!isValidInt32(row.listing_id)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid security-master row: "listing_id" must be a safe 32-bit integer.'
);
}
if (typeof row.calendar_code !== 'string' || row.calendar_code.trim().length === 0) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid security-master row: "calendar_code" must be a non-empty string.'
);
}
return {
listingId: row.listing_id,
calendarCode: row.calendar_code.trim(),
};
}
/**
* Creates a read-only PostgreSQL {@link ListingCalendarPort} backed by the M1
* security master (`listing` joined to `exchange` on `mic`), binding listing IDs
* as a single `$1::integer[]` parameter.
*/
export function createPostgresListingCalendarPort(
options: PostgresListingCalendarPortOptions
): ListingCalendarPort {
const { executor, schemaPrefix } = validatePostgresFactoryOptions(options);
const sql = buildListingCalendarSql(schemaPrefix);
return {
async getListingCalendars(
listingIds: readonly number[]
): Promise<readonly ListingCalendarRow[]> {
if (!Array.isArray(listingIds)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid listingIds: expected an array of 32-bit integers.'
);
}
const boundIds: number[] = [];
for (let i = 0; i < listingIds.length; i += 1) {
const id = listingIds[i];
if (!isValidInt32(id)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
`Invalid listingIds[${i}]: expected a safe 32-bit integer.`
);
}
boundIds.push(id);
}
if (boundIds.length === 0) {
return [];
}
const result = await executor.query<RawListingCalendarRow>(sql, [boundIds]);
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid executor response: expected an object with a rows array.'
);
}
const mapped: ListingCalendarRow[] = [];
for (let i = 0; i < result.rows.length; i += 1) {
mapped.push(mapRawListingCalendarRow(result.rows[i]));
}
return mapped;
},
};
}
function parseResolverDayKey(
value: unknown,
field: string,
code: 'INVALID_OPTION' | 'INVALID_QUERY' | 'INVALID_SESSION_DATES'
): number {
return parseCalendarDayKey(value, field, (message, cause) =>
new ExchangeCalendarResolverError(
code,
message,
cause !== undefined ? { cause } : undefined
)
);
}
function isPlainObjectRecord(value: unknown): value is Record<string, unknown> {
if (typeof value !== 'object' || value === null) {
return false;
}
const proto: unknown = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function parseEarlyCloses(
raw: unknown
): Map<string, Map<string, number>> {
const result = new Map<string, Map<string, number>>();
if (raw === undefined) {
return result;
}
if (!isPlainObjectRecord(raw)) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid "earlyCloses": expected a plain object mapping calendarCode to { [YYYY-MM-DD]: minuteOfDay }.'
);
}
const calendarEntries = Object.entries(raw);
for (let i = 0; i < calendarEntries.length; i += 1) {
const [calendarCode, rawDates] = calendarEntries[i] as [string, unknown];
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
`Invalid "earlyCloses" calendar code "${calendarCode}": expected a non-blank trimmed string.`
);
}
if (!isPlainObjectRecord(rawDates)) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
`Invalid "earlyCloses.${calendarCode}": expected a plain object mapping YYYY-MM-DD dates to Eastern close minutes.`
);
}
const dateOverrides = new Map<string, number>();
const dateEntries = Object.entries(rawDates);
for (let j = 0; j < dateEntries.length; j += 1) {
const [dateStr, minute] = dateEntries[j] as [string, unknown];
const field = `earlyCloses.${calendarCode}["${dateStr}"]`;
const dayKey = parseResolverDayKey(dateStr, field, 'INVALID_OPTION');
assertSupportedDayKey(dayKey, dateStr, field);
if (
typeof minute !== 'number' ||
!Number.isSafeInteger(minute) ||
minute < EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET ||
minute > EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET
) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
`Invalid "${field}": expected an integer Eastern minute in (${EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET - 1}, ${EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET}], got ${String(minute)}.`
);
}
dateOverrides.set(dateStr, minute);
}
result.set(calendarCode, dateOverrides);
}
return result;
}
function validateResolverOptions(options: ExchangeCalendarResolverOptions): {
readonly listingCalendars: ListingCalendarPort;
readonly sessionDates: SessionDatesPort;
readonly earlyCloseMap: Map<string, Map<string, number>>;
} {
if (!isPlainRecord(options)) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid options: expected an object with listingCalendars and sessionDates ports.'
);
}
const { listingCalendars, sessionDates, earlyCloses } = options;
if (
typeof listingCalendars !== 'object' ||
listingCalendars === null ||
typeof listingCalendars.getListingCalendars !== 'function'
) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid "listingCalendars": expected an object with a callable getListingCalendars(listingIds) method.'
);
}
if (
typeof sessionDates !== 'object' ||
sessionDates === null ||
typeof sessionDates.listSessionDates !== 'function'
) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid "sessionDates": expected an object with a callable listSessionDates({ calendarCode, fromDate, toDate }) method.'
);
}
const earlyCloseMap = parseEarlyCloses(earlyCloses);
return { listingCalendars, sessionDates, earlyCloseMap };
}
function compareAscii(a: string, b: string): number {
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* Creates an {@link EventStudyExchangeCalendarResolver} over injected
* {@link ListingCalendarPort} and {@link SessionDatesPort} implementations,
* converting each validated exchange session date into its UTC epoch-ms close
* timestamp (`16:00 ET` by default, or caller-supplied `earlyCloses` override).
*/
export function createExchangeCalendarResolver(
options: ExchangeCalendarResolverOptions
): EventStudyExchangeCalendarResolver {
const { listingCalendars, sessionDates, earlyCloseMap } = validateResolverOptions(options);
return async function resolveExchangeCalendars(
query: EventStudyExchangeCalendarQuery
): Promise<EventStudyExchangeCalendars> {
if (!isPlainRecord(query)) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
'Invalid query: expected a plain object with listingIds, fromDate, and toDate.'
);
}
if (!Array.isArray(query.listingIds)) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
'Invalid "listingIds": expected an array of 32-bit integer listing IDs.'
);
}
if (query.listingIds.length === 0) {
return {
calendars: {},
listingCalendarId: {},
};
}
const fromDayKey = parseResolverDayKey(query.fromDate, 'fromDate', 'INVALID_QUERY');
const toDayKey = parseResolverDayKey(query.toDate, 'toDate', 'INVALID_QUERY');
if (fromDayKey > toDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
`Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".`
);
}
assertSupportedDayKey(fromDayKey, query.fromDate, 'fromDate');
assertSupportedDayKey(toDayKey, query.toDate, 'toDate');
const requestedSet = new Set<number>();
for (let i = 0; i < query.listingIds.length; i += 1) {
const id: unknown = query.listingIds[i];
if (!isValidInt32(id)) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
`Invalid "listingIds[${i}]": expected a safe 32-bit integer.`
);
}
requestedSet.add(id);
}
const sortedListingIds = Array.from(requestedSet).sort((a, b) => a - b);
const rawMappings = await listingCalendars.getListingCalendars(sortedListingIds);
if (!Array.isArray(rawMappings)) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
'Invalid listingCalendars response: expected an array of { listingId, calendarCode } rows.'
);
}
const listingToCalendar = new Map<number, string>();
for (let i = 0; i < rawMappings.length; i += 1) {
const row: unknown = rawMappings[i];
if (!isPlainRecord(row)) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
`Invalid listingCalendars[${i}]: expected a plain object.`
);
}
const listingId = row.listingId;
const calendarCode = row.calendarCode;
if (!isValidInt32(listingId)) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
`Invalid listingCalendars[${i}].listingId: expected a safe 32-bit integer.`
);
}
if (
typeof calendarCode !== 'string' ||
calendarCode.trim().length === 0 ||
calendarCode !== calendarCode.trim()
) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
`Invalid listingCalendars[${i}].calendarCode: expected a non-blank trimmed string.`
);
}
if (!requestedSet.has(listingId)) {
throw new ExchangeCalendarResolverError(
'UNEXPECTED_LISTING_CALENDAR',
`Listing calendar port returned unrequested listingId ${listingId}.`
);
}
const existing = listingToCalendar.get(listingId);
if (existing !== undefined && existing !== calendarCode) {
throw new ExchangeCalendarResolverError(
'CONFLICTING_LISTING_CALENDAR',
`Conflicting calendar codes for listingId ${listingId}: "${existing}" vs "${calendarCode}".`
);
}
listingToCalendar.set(listingId, calendarCode);
}
const missingIds: number[] = [];
for (let i = 0; i < sortedListingIds.length; i += 1) {
const id = sortedListingIds[i] as number;
if (!listingToCalendar.has(id)) {
missingIds.push(id);
}
}
if (missingIds.length > 0) {
throw new ExchangeCalendarResolverError(
'MISSING_LISTING_CALENDAR',
`Missing exchange calendar mapping for listingId(s): ${missingIds.join(', ')}.`
);
}
const distinctCalendars = Array.from(new Set(listingToCalendar.values())).sort(compareAscii);
const sessionsByCalendar = new Map<string, readonly ExchangeSessionClose[]>();
for (let c = 0; c < distinctCalendars.length; c += 1) {
const calendarCode = distinctCalendars[c] as string;
const rawDates = await sessionDates.listSessionDates({
calendarCode,
fromDate: query.fromDate,
toDate: query.toDate,
});
if (!Array.isArray(rawDates)) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Invalid session dates for "${calendarCode}": expected an array of YYYY-MM-DD strings.`
);
}
const overrides = earlyCloseMap.get(calendarCode);
const sessions: ExchangeSessionClose[] = [];
let prevDayKey = Number.NEGATIVE_INFINITY;
for (let i = 0; i < rawDates.length; i += 1) {
const dateStr: unknown = rawDates[i];
const field = `sessionDates["${calendarCode}"][${i}]`;
const dayKey = parseResolverDayKey(dateStr, field, 'INVALID_SESSION_DATES');
const validDate = dateStr as string;
assertSupportedDayKey(dayKey, validDate, field);
if (dayKey < fromDayKey || dayKey > toDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Session date "${validDate}" for "${calendarCode}" is outside requested window [${query.fromDate}, ${query.toDate}].`
);
}
if (dayKey === prevDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Duplicate session date "${validDate}" for "${calendarCode}".`
);
}
if (dayKey < prevDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Session dates for "${calendarCode}" must be strictly ascending (saw "${validDate}" out of order).`
);
}
prevDayKey = dayKey;
const closeMinuteEt =
overrides?.get(validDate) ?? EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET;
sessions.push({
date: validDate,
closeTs: easternSessionCloseUtcMs(dayKey, closeMinuteEt),
});
}
sessionsByCalendar.set(calendarCode, sessions);
}
const calendars: Record<string, readonly ExchangeSessionClose[]> = {};
for (let c = 0; c < distinctCalendars.length; c += 1) {
const calendarCode = distinctCalendars[c] as string;
defineDataProperty(
calendars,
calendarCode,
sessionsByCalendar.get(calendarCode) as readonly ExchangeSessionClose[]
);
}
const listingCalendarId: Record<number, string> = {};
for (let i = 0; i < sortedListingIds.length; i += 1) {
const id = sortedListingIds[i] as number;
defineDataProperty(
listingCalendarId as unknown as Record<string, string>,
String(id),
listingToCalendar.get(id) as string
);
}
return {
calendars,
listingCalendarId,
};
};
}

View file

@ -1,883 +0,0 @@
/**
* Read-only filesystem adapter for the MCP copilot `read_knowledge` tool,
* implementing {@link KnowledgePort.listLibraryCards} over `<root>/library.yml`
* and `<root>/cards/<sectionId>/<slug>.md`.
*
* Filesystem access is injected via {@link LibraryCardFs} for hermetic testing,
* with {@link createNodeLibraryCardFs} provided for Node/Bun composition.
*/
import { constants as fsConstants } from 'node:fs';
import { type FileHandle, open, readdir, stat } from 'node:fs/promises';
import path from 'node:path';
import type { KnowledgePort, LibraryCardQuery, LibraryCardRecord } from '../tools/read-knowledge';
const SAFE_IDENT_RE = /^[a-z0-9][a-z0-9-]*$/;
const LIBRARY_ID_RE = /^[a-z0-9][a-z0-9_-]*$/;
const PLAIN_YAML_KEY_RE = /^[^?:,[\]{}#&*!|>'"%@`\s](?:(?:[^,[\]{}#\s]| )*[^,[\]{}#\s])?$/;
const BLOCK_SCALAR_RE = /^[|>][+-]?$/;
/** Error codes thrown by {@link LibraryCardError}. */
export type LibraryCardErrorCode =
| 'INVALID_FS'
| 'INVALID_ROOT'
| 'INVALID_LIBRARY'
| 'INVALID_CARD';
/** Typed validation and I/O error thrown by the library card filesystem adapter. */
export class LibraryCardError extends RangeError {
readonly code: LibraryCardErrorCode;
constructor(code: LibraryCardErrorCode, message: string) {
super(message);
this.name = 'LibraryCardError';
this.code = code;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/** Directory entry metadata returned by {@link LibraryCardFs.listDir}. */
export interface LibraryCardDirEntry {
readonly name: string;
readonly isFile: boolean;
readonly isDirectory: boolean;
}
/** Anchored read-only directory handle for symlink-safe traversal below a configured root. */
export interface LibraryCardDirHandle {
listDir(): Promise<readonly LibraryCardDirEntry[]>;
openSubdir(name: string): Promise<LibraryCardDirHandle>;
readTextFile(name: string): Promise<string>;
close(): Promise<void>;
}
/** Minimal read-only filesystem port injected into {@link createLibraryCardReader}. */
export interface LibraryCardFs {
readTextFile(filePath: string): Promise<string>;
listDir(dirPath: string): Promise<readonly LibraryCardDirEntry[]>;
openDir(dirPath: string): Promise<LibraryCardDirHandle>;
}
/** Factory options for {@link createLibraryCardReader}. */
export interface LibraryCardReaderOptions {
readonly root: string;
readonly fs: LibraryCardFs;
}
/** Library-card subset of {@link KnowledgePort}. */
export type LibraryCardReader = Pick<KnowledgePort, 'listLibraryCards'>;
interface ParsedLibraryManifest {
readonly id: string;
readonly sections: readonly string[];
}
type FrontMatterValue = string | readonly string[];
function compareCodeUnits(a: string, b: string): number {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
function isEnoentError(err: unknown): boolean {
return (
typeof err === 'object' &&
err !== null &&
(err as { readonly code?: unknown }).code === 'ENOENT'
);
}
function invalidLibrary(reason: string): LibraryCardError {
return new LibraryCardError('INVALID_LIBRARY', `Invalid library.yml: ${reason}`);
}
function invalidCard(relPath: string, reason: string): LibraryCardError {
return new LibraryCardError('INVALID_CARD', `Invalid card "${relPath}": ${reason}`);
}
function validateFactoryOptions(options: LibraryCardReaderOptions): {
readonly resolvedRoot: string;
readonly fs: LibraryCardFs;
} {
if (typeof options !== 'object' || options === null) {
throw new LibraryCardError(
'INVALID_ROOT',
'Invalid options: expected an object with root and fs.'
);
}
const { root, fs } = options;
if (typeof root !== 'string' || root.trim().length === 0 || root.includes('\0')) {
throw new LibraryCardError(
'INVALID_ROOT',
'Invalid root: expected a non-empty filesystem path without null bytes.'
);
}
if (
typeof fs !== 'object' ||
fs === null ||
typeof fs.readTextFile !== 'function' ||
typeof fs.listDir !== 'function' ||
typeof fs.openDir !== 'function'
) {
throw new LibraryCardError(
'INVALID_FS',
'Invalid fs: expected a LibraryCardFs implementing readTextFile, listDir, and openDir.'
);
}
return {
resolvedRoot: path.resolve(root),
fs,
};
}
function parseLibraryScalar(rawValue: string): string {
if (rawValue.length === 0 || rawValue.startsWith('#')) {
throw invalidLibrary('"id" must not be empty.');
}
if (rawValue.startsWith("'")) {
throw invalidLibrary('single-quoted "id" values are not supported.');
}
if (rawValue.startsWith('"')) {
let parsed: unknown;
try {
parsed = JSON.parse(rawValue);
} catch {
throw invalidLibrary('invalid double-quoted "id" value.');
}
if (typeof parsed !== 'string') {
throw invalidLibrary('invalid double-quoted "id" value.');
}
return parsed;
}
if (rawValue.startsWith('[') || rawValue.startsWith('{') || BLOCK_SCALAR_RE.test(rawValue)) {
throw invalidLibrary('"id" must be a scalar string.');
}
return rawValue;
}
function parseLibraryManifest(content: string): ParsedLibraryManifest {
const lines = content.split(/\r?\n/);
let libraryId: string | undefined;
let sawSections = false;
let sectionsIndent: number | null = null;
let currentTopLevelKey: string | null = null;
const seenSectionKeys = new Set<string>();
const validSections: string[] = [];
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i] as string;
const trimmed = line.trim();
if (trimmed.length === 0 || trimmed.startsWith('#')) {
continue;
}
let indent = 0;
while (indent < line.length && line[indent] === ' ') {
indent += 1;
}
if (line[indent] === '\t') {
throw invalidLibrary('tab indentation is not supported.');
}
if (indent === 0) {
const colonIdx = line.indexOf(':');
if (colonIdx <= 0) {
throw invalidLibrary('malformed top-level entry.');
}
const key = line.slice(0, colonIdx).trim();
const rawValue = line.slice(colonIdx + 1).trim();
if (key.length === 0 || /\s/.test(key)) {
throw invalidLibrary('invalid top-level key.');
}
currentTopLevelKey = key;
if (key === 'id') {
if (libraryId !== undefined) {
throw invalidLibrary('duplicate "id" declaration.');
}
const parsedId = parseLibraryScalar(rawValue);
if (!LIBRARY_ID_RE.test(parsedId)) {
throw invalidLibrary('"id" must match ^[a-z0-9][a-z0-9_-]*$.');
}
libraryId = parsedId;
} else if (key === 'sections') {
if (sawSections) {
throw invalidLibrary('duplicate "sections" declaration.');
}
if (rawValue.length > 0) {
throw invalidLibrary('"sections" must be an indented map.');
}
sawSections = true;
sectionsIndent = null;
}
continue;
}
if (currentTopLevelKey === null) {
throw invalidLibrary('indented entry before any top-level declaration.');
}
if (currentTopLevelKey === 'id') {
throw invalidLibrary('"id" must be a single-line scalar.');
}
if (currentTopLevelKey !== 'sections') {
continue;
}
if (sectionsIndent === null) {
sectionsIndent = indent;
} else if (indent !== sectionsIndent) {
throw invalidLibrary('inconsistent indentation inside "sections" map.');
}
const body = line.slice(indent);
if (body === '-' || body.startsWith('- ') || body.startsWith('-\t')) {
throw invalidLibrary('sequence entries are not supported inside "sections" map.');
}
const colonIdx = body.indexOf(':');
if (colonIdx <= 0) {
throw invalidLibrary('malformed entry inside "sections" map.');
}
const rawKey = body.slice(0, colonIdx);
const sectionKey = rawKey.trim();
const afterColon = body.slice(colonIdx + 1);
if (
rawKey !== sectionKey ||
!PLAIN_YAML_KEY_RE.test(sectionKey) ||
(afterColon.length > 0 && afterColon[0] !== ' ' && afterColon[0] !== '\t')
) {
throw invalidLibrary('malformed entry inside "sections" map.');
}
const sectionTitle = afterColon.trim();
if (sectionTitle.length === 0 || sectionTitle.startsWith('#')) {
throw invalidLibrary('empty key or title inside "sections" map.');
}
if (seenSectionKeys.has(sectionKey)) {
throw invalidLibrary('duplicate key inside "sections" map.');
}
seenSectionKeys.add(sectionKey);
if (SAFE_IDENT_RE.test(sectionKey)) {
validSections.push(sectionKey);
}
}
if (libraryId === undefined) {
throw invalidLibrary('missing "id" declaration.');
}
if (!sawSections || seenSectionKeys.size === 0) {
throw invalidLibrary('missing or empty "sections" map.');
}
return {
id: libraryId,
sections: validSections,
};
}
function parseFrontMatterValue(rawValue: string, relPath: string): FrontMatterValue {
if (rawValue.length === 0 || rawValue.startsWith('#')) {
throw invalidCard(relPath, 'empty or multiline front-matter value.');
}
if (BLOCK_SCALAR_RE.test(rawValue)) {
throw invalidCard(relPath, 'multiline front-matter values are not supported.');
}
if (rawValue.startsWith("'")) {
throw invalidCard(relPath, 'single-quoted front-matter values are not supported.');
}
if (rawValue.startsWith('{')) {
throw invalidCard(relPath, 'object front-matter values are not supported.');
}
if (rawValue.startsWith('"')) {
let parsed: unknown;
try {
parsed = JSON.parse(rawValue);
} catch {
throw invalidCard(relPath, 'invalid double-quoted front-matter string.');
}
if (typeof parsed !== 'string') {
throw invalidCard(relPath, 'invalid double-quoted front-matter string.');
}
return parsed;
}
if (rawValue.startsWith('[')) {
let parsed: unknown;
try {
parsed = JSON.parse(rawValue);
} catch {
throw invalidCard(relPath, 'invalid front-matter array.');
}
if (!Array.isArray(parsed)) {
throw invalidCard(relPath, 'invalid front-matter array.');
}
const items: string[] = [];
for (let i = 0; i < parsed.length; i += 1) {
const entry: unknown = parsed[i];
if (typeof entry !== 'string') {
throw invalidCard(relPath, 'front-matter array entries must be strings.');
}
items.push(entry);
}
return items;
}
return rawValue;
}
function parseCardDocument(
content: string,
libraryId: string,
sectionId: string,
slug: string
): LibraryCardRecord {
const relPath = `cards/${sectionId}/${slug}.md`;
const lines = content.split(/\r?\n/);
if (lines[0] !== '---') {
throw invalidCard(relPath, 'missing opening front-matter delimiter.');
}
let closingIndex = -1;
for (let i = 1; i < lines.length; i += 1) {
if (lines[i] === '---') {
closingIndex = i;
break;
}
}
if (closingIndex === -1) {
throw invalidCard(relPath, 'missing closing front-matter delimiter.');
}
const fields = new Map<string, FrontMatterValue>();
for (let i = 1; i < closingIndex; i += 1) {
const line = lines[i] as string;
const trimmed = line.trim();
if (trimmed.length === 0 || trimmed.startsWith('#')) {
continue;
}
if (line[0] === ' ' || line[0] === '\t') {
throw invalidCard(relPath, 'multiline or indented front-matter values are not supported.');
}
const colonIdx = line.indexOf(':');
if (colonIdx <= 0) {
throw invalidCard(relPath, 'malformed front-matter entry.');
}
const key = line.slice(0, colonIdx).trim();
if (key.length === 0 || /\s/.test(key)) {
throw invalidCard(relPath, 'invalid front-matter key.');
}
if (fields.has(key)) {
throw invalidCard(relPath, 'duplicate front-matter key.');
}
const rawValue = line.slice(colonIdx + 1).trim();
fields.set(key, parseFrontMatterValue(rawValue, relPath));
}
const rawTitle = fields.get('title');
if (typeof rawTitle !== 'string' || rawTitle.trim().length === 0) {
throw invalidCard(relPath, 'missing or empty "title".');
}
const rawSummary = fields.get('summary');
if (typeof rawSummary !== 'string' || rawSummary.trim().length === 0) {
throw invalidCard(relPath, 'missing or empty "summary".');
}
const rawMatches = fields.get('matches');
if (rawMatches !== undefined && !Array.isArray(rawMatches)) {
throw invalidCard(relPath, '"matches" must be an array of strings.');
}
const tags: string[] = [];
const seenTags = new Set<string>();
const addTag = (raw: string): void => {
const normalized = raw.trim().toLowerCase();
if (normalized.length > 0 && !seenTags.has(normalized)) {
seenTags.add(normalized);
tags.push(normalized);
}
};
addTag(sectionId);
if (rawMatches !== undefined) {
for (let i = 0; i < rawMatches.length; i += 1) {
addTag(rawMatches[i] as string);
}
}
const body = lines
.slice(closingIndex + 1)
.join('\n')
.trim();
return Object.freeze({
id: `${libraryId}:${sectionId}/${slug}`,
title: rawTitle,
tags: Object.freeze(tags),
summary: rawSummary,
body,
});
}
function parseExactCardId(
id: string,
libraryId: string,
declaredSections: ReadonlySet<string>
): { readonly sectionId: string; readonly slug: string } | null {
const prefix = `${libraryId}:`;
if (!id.startsWith(prefix)) {
return null;
}
const rest = id.slice(prefix.length);
const slashIdx = rest.indexOf('/');
if (slashIdx <= 0 || rest.indexOf('/', slashIdx + 1) !== -1) {
return null;
}
const sectionId = rest.slice(0, slashIdx);
const slug = rest.slice(slashIdx + 1);
if (!SAFE_IDENT_RE.test(sectionId) || !SAFE_IDENT_RE.test(slug)) {
return null;
}
if (!declaredSections.has(sectionId)) {
return null;
}
return { sectionId, slug };
}
function assertSafeChildName(name: string): void {
if (
name.length === 0 ||
name === '.' ||
name === '..' ||
name.includes('/') ||
name.includes('\\') ||
name.includes('\0')
) {
throw new Error('Invalid directory child entry name.');
}
}
function isValidDirHandle(value: unknown): value is LibraryCardDirHandle {
return (
typeof value === 'object' &&
value !== null &&
typeof (value as { readonly listDir?: unknown }).listDir === 'function' &&
typeof (value as { readonly openSubdir?: unknown }).openSubdir === 'function' &&
typeof (value as { readonly readTextFile?: unknown }).readTextFile === 'function' &&
typeof (value as { readonly close?: unknown }).close === 'function'
);
}
async function safeOpenRootDir(
fs: LibraryCardFs,
resolvedRoot: string
): Promise<LibraryCardDirHandle> {
let handle: unknown;
try {
handle = await fs.openDir(resolvedRoot);
} catch {
throw new LibraryCardError(
'INVALID_LIBRARY',
'Invalid library.yml: failed to open library root directory.'
);
}
if (!isValidDirHandle(handle)) {
throw new LibraryCardError(
'INVALID_LIBRARY',
'Invalid library.yml: failed to open library root directory.'
);
}
return handle;
}
async function safeOpenSubdir(
parent: LibraryCardDirHandle,
name: string,
errorMessage: string,
allowMissing: boolean
): Promise<LibraryCardDirHandle | null> {
let handle: unknown;
try {
handle = await parent.openSubdir(name);
} catch (err) {
if (allowMissing && isEnoentError(err)) {
return null;
}
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
}
if (!isValidDirHandle(handle)) {
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
}
return handle;
}
async function safeReadTextFileFromDir(
dir: LibraryCardDirHandle,
name: string,
errorCode: 'INVALID_LIBRARY' | 'INVALID_CARD',
errorMessage: string
): Promise<string> {
let content: unknown;
try {
content = await dir.readTextFile(name);
} catch {
throw new LibraryCardError(errorCode, errorMessage);
}
if (typeof content !== 'string') {
throw new LibraryCardError(errorCode, errorMessage);
}
return content;
}
async function safeListDirHandle(
dir: LibraryCardDirHandle,
errorMessage: string,
allowMissing: boolean
): Promise<readonly LibraryCardDirEntry[]> {
let rawEntries: unknown;
try {
rawEntries = await dir.listDir();
} catch (err) {
if (allowMissing && isEnoentError(err)) {
return [];
}
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
}
if (!Array.isArray(rawEntries)) {
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
}
const entries: LibraryCardDirEntry[] = [];
for (let i = 0; i < rawEntries.length; i += 1) {
const entry: unknown = rawEntries[i];
if (
typeof entry !== 'object' ||
entry === null ||
typeof (entry as { readonly name?: unknown }).name !== 'string' ||
typeof (entry as { readonly isFile?: unknown }).isFile !== 'boolean' ||
typeof (entry as { readonly isDirectory?: unknown }).isDirectory !== 'boolean'
) {
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
}
entries.push(entry as LibraryCardDirEntry);
}
return entries;
}
interface AnchoredOpenFlags {
readonly dirOpenFlags: number;
readonly subdirOpenFlags: number;
readonly fileOpenFlags: number;
}
function getAnchoredOpenFlags(): AnchoredOpenFlags {
if (
process.platform !== 'linux' ||
typeof fsConstants.O_NOFOLLOW !== 'number' ||
typeof fsConstants.O_DIRECTORY !== 'number'
) {
throw new Error('Anchored no-follow directory operations are not supported on this platform.');
}
return {
dirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY,
subdirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,
fileOpenFlags: fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW,
};
}
function createAnchoredNodeDirHandle(
handle: FileHandle,
flags: AnchoredOpenFlags
): LibraryCardDirHandle {
let closed = false;
const getFdBase = (): string => {
if (closed) {
throw new Error('Directory handle is closed.');
}
return `/proc/self/fd/${handle.fd}`;
};
return {
async listDir(): Promise<readonly LibraryCardDirEntry[]> {
const dirents = await readdir(getFdBase(), { withFileTypes: true });
const entries: LibraryCardDirEntry[] = [];
for (let i = 0; i < dirents.length; i += 1) {
const dirent = dirents[i];
if (dirent !== undefined) {
entries.push({
name: dirent.name,
isFile: dirent.isFile(),
isDirectory: dirent.isDirectory(),
});
}
}
return entries;
},
async openSubdir(name: string): Promise<LibraryCardDirHandle> {
assertSafeChildName(name);
const childHandle = await open(`${getFdBase()}/${name}`, flags.subdirOpenFlags);
try {
const stats = await childHandle.stat();
if (!stats.isDirectory()) {
throw new Error('Target path is not a directory.');
}
} catch (err) {
await childHandle.close();
throw err;
}
return createAnchoredNodeDirHandle(childHandle, flags);
},
async readTextFile(name: string): Promise<string> {
assertSafeChildName(name);
const fileHandle = await open(`${getFdBase()}/${name}`, flags.fileOpenFlags);
try {
const stats = await fileHandle.stat();
if (!stats.isFile()) {
throw new Error('Target path is not a regular file.');
}
return await fileHandle.readFile({ encoding: 'utf8' });
} finally {
await fileHandle.close();
}
},
async close(): Promise<void> {
if (closed) {
return;
}
closed = true;
await handle.close();
},
};
}
/**
* Creates a read-only {@link LibraryCardFs} backed by `node:fs/promises`.
*
* Anchors directory listings and file reads to opened directory file descriptors
* via `/proc/self/fd/<fd>`, enforces `O_NOFOLLOW` on every component below the
* configured root, verifies regular-file/directory types via `fstat`, and fails
* closed on platforms that cannot enforce this boundary.
*/
export function createNodeLibraryCardFs(): LibraryCardFs {
return {
async readTextFile(filePath: string): Promise<string> {
const flags = getAnchoredOpenFlags();
const handle = await open(filePath, flags.fileOpenFlags);
try {
const stats = await handle.stat();
if (!stats.isFile()) {
throw new Error('Target path is not a regular file.');
}
return await handle.readFile({ encoding: 'utf8' });
} finally {
await handle.close();
}
},
async listDir(dirPath: string): Promise<readonly LibraryCardDirEntry[]> {
const flags = getAnchoredOpenFlags();
const handle = await open(dirPath, flags.subdirOpenFlags);
try {
const stats = await handle.stat();
if (!stats.isDirectory()) {
throw new Error('Target path is not a directory.');
}
const anchored = createAnchoredNodeDirHandle(handle, flags);
return await anchored.listDir();
} finally {
await handle.close();
}
},
async openDir(dirPath: string): Promise<LibraryCardDirHandle> {
const flags = getAnchoredOpenFlags();
const handle = await open(dirPath, flags.dirOpenFlags);
try {
const stats = await handle.stat();
if (!stats.isDirectory()) {
throw new Error('Target path is not a directory.');
}
const procStats = await stat(`/proc/self/fd/${handle.fd}`);
if (!procStats.isDirectory()) {
throw new Error('Anchored directory descriptor is not accessible.');
}
} catch (err) {
await handle.close();
throw err;
}
return createAnchoredNodeDirHandle(handle, flags);
},
};
}
/**
* Creates a read-only filesystem reader implementing
* {@link KnowledgePort.listLibraryCards} over `<root>/library.yml` and
* `<root>/cards/<sectionId>/<slug>.md`.
*
* Reads fresh from the injected {@link LibraryCardFs} on every call, narrows
* only by exact case-sensitive `q.id` (leaving `q.query`, `q.tags`, ranking,
* truncation, and `limit` to `createReadKnowledgeTool`), and returns all
* eligible cards regardless of `verified` status.
*/
export function createLibraryCardReader(options: LibraryCardReaderOptions): LibraryCardReader {
const { resolvedRoot, fs } = validateFactoryOptions(options);
return {
async listLibraryCards(q: LibraryCardQuery): Promise<readonly LibraryCardRecord[]> {
const rootDir = await safeOpenRootDir(fs, resolvedRoot);
try {
const manifestText = await safeReadTextFileFromDir(
rootDir,
'library.yml',
'INVALID_LIBRARY',
'Invalid library.yml: failed to read manifest.'
);
const manifest = parseLibraryManifest(manifestText);
const declaredSections = new Set(manifest.sections);
let target: { readonly sectionId: string; readonly slug: string } | null = null;
if (q.id !== undefined) {
target = parseExactCardId(q.id, manifest.id, declaredSections);
if (target === null) {
return Object.freeze([]);
}
}
const rootEntries = await safeListDirHandle(
rootDir,
'Invalid library.yml: failed to list library root directory.',
false
);
const hasCardsDir = rootEntries.some(
entry => entry.name === 'cards' && entry.isDirectory && !entry.isFile
);
if (!hasCardsDir) {
return Object.freeze([]);
}
const cardsDir = await safeOpenSubdir(
rootDir,
'cards',
'Invalid library.yml: failed to open library cards directory.',
true
);
if (cardsDir === null) {
return Object.freeze([]);
}
try {
const cardDirEntries = await safeListDirHandle(
cardsDir,
'Invalid library.yml: failed to list library cards directory.',
true
);
const presentSectionDirs = new Set<string>();
for (let i = 0; i < cardDirEntries.length; i += 1) {
const entry = cardDirEntries[i] as LibraryCardDirEntry;
if (entry.isDirectory && !entry.isFile && SAFE_IDENT_RE.test(entry.name)) {
presentSectionDirs.add(entry.name);
}
}
const sectionsToScan = target !== null ? [target.sectionId] : manifest.sections;
const cards: LibraryCardRecord[] = [];
const seenIds = new Set<string>();
for (let s = 0; s < sectionsToScan.length; s += 1) {
const sectionId = sectionsToScan[s] as string;
if (!presentSectionDirs.has(sectionId)) {
continue;
}
const sectionDir = await safeOpenSubdir(
cardsDir,
sectionId,
`Invalid library.yml: failed to open section directory "cards/${sectionId}".`,
true
);
if (sectionDir === null) {
continue;
}
try {
const sectionEntries = await safeListDirHandle(
sectionDir,
`Invalid library.yml: failed to list section directory "cards/${sectionId}".`,
true
);
const slugs: string[] = [];
const seenSectionSlugs = new Set<string>();
for (let i = 0; i < sectionEntries.length; i += 1) {
const entry = sectionEntries[i] as LibraryCardDirEntry;
if (!entry.isFile || entry.isDirectory || !entry.name.endsWith('.md')) {
continue;
}
const slug = entry.name.slice(0, -3);
if (!SAFE_IDENT_RE.test(slug)) {
continue;
}
if (target !== null && slug !== target.slug) {
continue;
}
if (seenSectionSlugs.has(slug)) {
throw invalidCard(`cards/${sectionId}/${slug}.md`, 'duplicate card id.');
}
seenSectionSlugs.add(slug);
slugs.push(slug);
}
slugs.sort(compareCodeUnits);
for (let i = 0; i < slugs.length; i += 1) {
const slug = slugs[i] as string;
const relPath = `cards/${sectionId}/${slug}.md`;
const canonicalId = `${manifest.id}:${sectionId}/${slug}`;
if (seenIds.has(canonicalId)) {
throw invalidCard(relPath, 'duplicate card id.');
}
seenIds.add(canonicalId);
const cardText = await safeReadTextFileFromDir(
sectionDir,
`${slug}.md`,
'INVALID_CARD',
`Invalid card "${relPath}": failed to read card file.`
);
cards.push(parseCardDocument(cardText, manifest.id, sectionId, slug));
}
} finally {
await sectionDir.close();
}
}
return Object.freeze(cards);
} finally {
await cardsDir.close();
}
} finally {
await rootDir.close();
}
},
};
}

View file

@ -1,173 +0,0 @@
/**
* PostgreSQL composition root for the MCP research copilot server.
*
* Wires a single injected {@link PostgresResearchCopilotExecutor} into all
* PostgreSQL-backed MCP adapters (`search_symbols`, `file_finding`,
* `read_knowledge`, `event_study` listing calendars, and `trial_ledger`) with
* one authoritative Vault cutoff (`vaultContext.vaultCutoffTs`).
*
* Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution,
* market data store, library-card reader, session-date port, ID generator, and
* clock are all injected by the caller.
*/
import {
type ResearchCopilotMcpServerOptions,
createResearchCopilotMcpServer,
} from '../copilot-server';
import type { McpServer } from '../server';
import type { KnowledgePort } from '../tools/read-knowledge';
import {
type EarlyCloseOverrides,
type SessionDatesPort,
createExchangeCalendarResolver,
createPostgresListingCalendarPort,
} from './exchange-calendars';
import {
createPostgresFindingWritePort,
createPostgresKnowledgeReaders,
} from './postgres-findings';
import { createPostgresSymbolSearchPort } from './postgres-symbol-search';
import { createPostgresTrialRefPort } from './postgres-trial-ref';
/**
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface shared by
* all PostgreSQL-backed MCP copilot adapters and `trial_ledger`.
*
* Assignable without casts to `SymbolSearchExecutor`, `TrialRefExecutor`,
* `PostgresFindingsExecutor`, `ListingCalendarExecutor`, and
* `TrialLedgerExecutor`.
*/
export interface PostgresResearchCopilotExecutor {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }>;
}
/**
* Composition options for {@link createPostgresResearchCopilotServer}.
*
* Uses `vaultContext.vaultCutoffTs` as the single authoritative Vault cutoff
* across all Vault-fenced tools and `trial_ledger` visibility lookups.
*/
export interface PostgresResearchCopilotServerOptions
extends Pick<
ResearchCopilotMcpServerOptions,
'name' | 'version' | 'store' | 'vaultContext' | 'principalId'
> {
readonly executor: PostgresResearchCopilotExecutor;
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
readonly schema?: string;
readonly listLibraryCards: KnowledgePort['listLibraryCards'];
readonly sessionDates: SessionDatesPort;
readonly earlyCloses?: EarlyCloseOverrides;
readonly newId: () => string;
readonly now: () => Date | number;
}
function validateOptions(options: PostgresResearchCopilotServerOptions): void {
if (typeof options !== 'object' || options === null) {
throw new Error(
'Invalid `options`: expected a PostgresResearchCopilotServerOptions object.'
);
}
if (
typeof options.executor !== 'object' ||
options.executor === null ||
typeof options.executor.query !== 'function'
) {
throw new Error(
'Invalid `executor`: expected an object with a callable query(text, params?) method.'
);
}
if (typeof options.vaultContext !== 'object' || options.vaultContext === null) {
throw new Error('Invalid `vaultContext`: expected a VaultFenceContext object.');
}
if (typeof options.listLibraryCards !== 'function') {
throw new Error('Invalid `listLibraryCards`: expected a callable function.');
}
if (
typeof options.sessionDates !== 'object' ||
options.sessionDates === null ||
typeof options.sessionDates.listSessionDates !== 'function'
) {
throw new Error(
'Invalid `sessionDates`: expected an object with a callable listSessionDates(query) method.'
);
}
if (typeof options.newId !== 'function') {
throw new Error('Invalid `newId`: expected a callable function.');
}
if (typeof options.now !== 'function') {
throw new Error('Invalid `now`: expected a callable function.');
}
}
/**
* Composes all six research copilot MCP tools into a single {@link McpServer}
* backed by one shared PostgreSQL executor and one authoritative Vault cutoff.
*
* Schema-aware adapters (`search_symbols`, `trial_ledger` visibility lookup,
* `findings`, `provider_caveats`, and listing-to-exchange calendars) qualify
* their tables with `options.schema` when supplied; `trial_ledger` writes and
* cluster DSR reads resolve through the executor's `search_path`.
*/
export function createPostgresResearchCopilotServer(
options: PostgresResearchCopilotServerOptions
): McpServer {
validateOptions(options);
const pgAdapterOptions =
options.schema === undefined
? { executor: options.executor }
: { executor: options.executor, schema: options.schema };
const symbolSearchPort = createPostgresSymbolSearchPort(pgAdapterOptions);
const trialRefPort = createPostgresTrialRefPort({
...pgAdapterOptions,
vaultCutoffTs: options.vaultContext.vaultCutoffTs,
});
const findingWritePort = createPostgresFindingWritePort(pgAdapterOptions);
const knowledgeReaders = createPostgresKnowledgeReaders(pgAdapterOptions);
const listingCalendars = createPostgresListingCalendarPort(pgAdapterOptions);
const resolveExchangeCalendars = createExchangeCalendarResolver(
options.earlyCloses === undefined
? { listingCalendars, sessionDates: options.sessionDates }
: {
listingCalendars,
sessionDates: options.sessionDates,
earlyCloses: options.earlyCloses,
}
);
const knowledgePort: KnowledgePort = {
listLibraryCards: options.listLibraryCards,
...knowledgeReaders,
};
return createResearchCopilotMcpServer({
name: options.name,
version: options.version,
store: options.store,
vaultContext: options.vaultContext,
ledger: options.executor,
principalId: options.principalId,
searchSymbols: {
port: symbolSearchPort,
},
eventStudy: {
resolveExchangeCalendars,
},
fileFinding: {
port: findingWritePort,
trialLookup: trialRefPort,
newId: options.newId,
now: options.now,
},
readKnowledge: {
port: knowledgePort,
},
});
}

View file

@ -1,722 +0,0 @@
/**
* PostgreSQL adapter for the MCP copilot findings and provider caveats tables
* (`37-research-findings.sql`), implementing {@link FindingWritePort} for
* `file_finding` and the `listFindings` / `listProviderCaveats` readers of
* {@link KnowledgePort} for `read_knowledge`.
*
* Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is
* injected via {@link PostgresFindingsExecutor}.
*/
import {
type AppendFindingResult,
FILE_FINDING_KINDS,
type FileFindingKind,
type FiledFindingComparablePayload,
type FiledFindingRecord,
type FindingWritePort,
areFiledFindingPayloadsEqual,
} from '../tools/file-finding';
import type {
FindingQuery,
FindingRecord,
KnowledgePort,
ProviderCaveatQuery,
ProviderCaveatRecord,
} from '../tools/read-knowledge';
import { MAX_ECMASCRIPT_EPOCH_MS } from '../tools/vault-fenced-input';
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
const ISO_INSTANT_RE =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/;
const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const FILE_FINDING_KIND_SET: ReadonlySet<string> = new Set(FILE_FINDING_KINDS);
/** Error codes thrown by {@link PostgresFindingsError}. */
export type PostgresFindingsErrorCode = 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' | 'INVALID_ROW';
/** Typed validation error thrown by the PostgreSQL findings adapter. */
export class PostgresFindingsError extends RangeError {
readonly code: PostgresFindingsErrorCode;
constructor(code: PostgresFindingsErrorCode, message: string) {
super(message);
this.name = 'PostgresFindingsError';
this.code = code;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/**
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module
* has no runtime dependency on `pg` and is unit-testable with a fake executor.
*
* For {@link createPostgresFindingWritePort}, the executor must run each `query()`
* call in autocommit mode on a fresh `READ COMMITTED` snapshot (such as a `pg.Pool`)
* rather than inside a `REPEATABLE READ` / `SERIALIZABLE` or explicit `BEGIN`
* transaction (unless the executor wraps each statement in a `SAVEPOINT` and rolls
* it back before rethrowing errors). Autocommit ensures that `ON CONFLICT ... DO
* NOTHING` winner lookups observe the committed winner and that same-ID `23505`
* primary-key retry lookups do not fail with `25P02` (aborted transaction).
*/
export interface PostgresFindingsExecutor {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }>;
}
/** Factory options for {@link createPostgresFindingWritePort} and {@link createPostgresKnowledgeReaders}. */
export interface PostgresFindingsOptions {
readonly executor: PostgresFindingsExecutor;
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
readonly schema?: string;
}
/** PostgreSQL-backed subset of {@link KnowledgePort} (`findings` and `provider_caveats`). */
export type PostgresKnowledgeReaders = Pick<KnowledgePort, 'listFindings' | 'listProviderCaveats'>;
interface RawFindingReceiptRow {
readonly id: unknown;
readonly created_at: unknown;
}
interface RawStoredFindingForReplayRow {
readonly id: unknown;
readonly kind: unknown;
readonly title: unknown;
readonly summary: unknown;
readonly created_at: unknown;
readonly trial_refs: unknown;
readonly evidence_refs: unknown;
}
interface RawFindingRow {
readonly id: unknown;
readonly title: unknown;
readonly status: unknown;
readonly created_at: unknown;
readonly summary: unknown;
readonly trial_refs: unknown;
readonly evidence_refs: unknown;
}
interface RawProviderCaveatRow {
readonly id: unknown;
readonly provider: unknown;
readonly dataset: unknown;
readonly caveat: unknown;
readonly created_at: unknown;
}
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function daysInUtcMonth(year: number, monthIndex: number): number {
if (monthIndex === 1 && isLeapYear(year)) {
return 29;
}
return DAYS_IN_MONTH[monthIndex] ?? 0;
}
function utcDateMs(
year: number,
monthIndex: number,
day: number,
hours: number,
minutes: number,
seconds: number,
ms: number
): number {
const date = new Date(0);
date.setUTCFullYear(year, monthIndex, day);
date.setUTCHours(hours, minutes, seconds, ms);
return date.getTime();
}
function escapeLikePattern(value: string): string {
return value.replace(/[\\%_]/g, '\\$&');
}
/**
* PostgreSQL POSIX regex matching any non-ASCII character (`> 0x7F`).
*
* Used alongside ASCII SQL pushdown (`ILIKE` / `lower()`) so rows containing
* non-ASCII stored text (e.g. `BİST` under `C` collation or `K` U+212A) are
* kept as candidates and evaluated with JavaScript's `.toLowerCase()` rules.
*/
const PG_NON_ASCII_REGEX = "'[^\\x01-\\x7f]'";
/**
* Returns `true` when every UTF-16 code unit in `value` is ASCII (`<= 0x7F`).
*
* PostgreSQL `ILIKE` / `lower()` agrees with JavaScript `.toLowerCase()` only
* when both the selector and the stored text are pure ASCII. Non-ASCII
* selectors omit SQL casing filters, and ASCII selectors retain non-ASCII
* stored rows as candidates; all returned rows are then filtered with
* JavaScript's `.toLowerCase()` rules after validation.
*/
function isAsciiOnly(value: string): boolean {
for (let i = 0; i < value.length; i += 1) {
if (value.charCodeAt(i) > 0x7f) {
return false;
}
}
return true;
}
function quoteTable(schemaPrefix: string, table: string): string {
return `${schemaPrefix}${table}`;
}
function validateFactoryOptions(options: PostgresFindingsOptions): {
readonly executor: PostgresFindingsExecutor;
readonly schemaPrefix: string;
} {
if (typeof options !== 'object' || options === null) {
throw new PostgresFindingsError(
'INVALID_EXECUTOR',
'Invalid options: expected an object with a PostgresFindingsExecutor.'
);
}
const { executor, schema } = options;
if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') {
throw new PostgresFindingsError(
'INVALID_EXECUTOR',
'Invalid executor: expected an object with a callable query(text, params?) method.'
);
}
if (schema === undefined) {
return { executor, schemaPrefix: '' };
}
if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) {
throw new PostgresFindingsError(
'INVALID_SCHEMA',
'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.'
);
}
return { executor, schemaPrefix: `"${schema}".` };
}
function extractRows<Row>(result: unknown): readonly Row[] {
if (
typeof result !== 'object' ||
result === null ||
!Array.isArray((result as { readonly rows?: unknown }).rows)
) {
throw new PostgresFindingsError(
'INVALID_ROW',
'Invalid executor response: expected an object with a rows array.'
);
}
return (result as { readonly rows: readonly Row[] }).rows;
}
function parseNonEmptyString(value: unknown, field: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}" must be a non-empty string.`
);
}
return value;
}
function parseFindingKind(value: unknown): FileFindingKind {
if (typeof value !== 'string' || !FILE_FINDING_KIND_SET.has(value)) {
throw new PostgresFindingsError(
'INVALID_ROW',
'Invalid findings row: "kind" must be "finding" or "dead_end".'
);
}
return value as FileFindingKind;
}
function parseStringArray(value: unknown, field: string): readonly string[] {
if (!Array.isArray(value)) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}" must be a one-dimensional string array.`
);
}
const result: string[] = [];
for (let i = 0; i < value.length; i += 1) {
const entry: unknown = value[i];
if (typeof entry !== 'string') {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}[${i}]" must be a string.`
);
}
result.push(entry);
}
return result;
}
function parseTimestampIso(value: unknown, field: string): string {
if (value instanceof Date) {
const ms = value.getTime();
if (!Number.isFinite(ms) || Math.abs(ms) >= MAX_ECMASCRIPT_EPOCH_MS) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}" must be a finite Date.`
);
}
return new Date(ms).toISOString();
}
if (typeof value !== 'string') {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}" must be a Date or timezone-qualified ISO-8601 timestamp string.`
);
}
const match = ISO_INSTANT_RE.exec(value);
if (match === null) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}" must be a timezone-qualified ISO-8601 timestamp string.`
);
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const hours = Number(match[4]);
const minutes = Number(match[5]);
const seconds = Number(match[6]);
const fractional = match[7];
const tzToken = match[8];
const tzSign = match[9];
const tzHoursRaw = match[10];
const tzMinutesRaw = match[11];
if (month < 1 || month > 12) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}" has an out-of-range calendar month.`
);
}
const maxDay = daysInUtcMonth(year, month - 1);
if (day < 1 || day > maxDay) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}" has an out-of-range calendar day.`
);
}
if (hours > 23 || minutes > 59 || seconds > 59) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}" has an out-of-range time of day.`
);
}
let ms = 0;
if (fractional !== undefined) {
ms = Number(fractional.slice(0, 3).padEnd(3, '0'));
}
let offsetMs = 0;
if (tzToken !== 'Z') {
const offsetHours = Number(tzHoursRaw);
const offsetMinutes = Number(tzMinutesRaw);
if (offsetHours > 23 || offsetMinutes > 59) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}" has an out-of-range timezone offset.`
);
}
const sign = tzSign === '+' ? 1 : -1;
offsetMs = sign * (offsetHours * 60 + offsetMinutes) * 60_000;
}
const epochMs = utcDateMs(year, month - 1, day, hours, minutes, seconds, ms) - offsetMs;
if (!Number.isFinite(epochMs) || Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Invalid findings row: "${field}" is outside the valid ECMAScript timestamp range.`
);
}
return new Date(epochMs).toISOString();
}
function parseReceiptRow(raw: unknown): { readonly id: string; readonly createdAt: string } {
if (typeof raw !== 'object' || raw === null) {
throw new PostgresFindingsError(
'INVALID_ROW',
'Invalid findings receipt row: expected a non-null object.'
);
}
const row = raw as RawFindingReceiptRow;
return {
id: parseNonEmptyString(row.id, 'id'),
createdAt: parseTimestampIso(row.created_at, 'created_at'),
};
}
function parseStoredFindingForReplayRow(raw: unknown): {
readonly id: string;
readonly createdAt: string;
readonly payload: FiledFindingComparablePayload;
} {
if (typeof raw !== 'object' || raw === null) {
throw new PostgresFindingsError(
'INVALID_ROW',
'Invalid findings replay row: expected a non-null object.'
);
}
const row = raw as RawStoredFindingForReplayRow;
const id = parseNonEmptyString(row.id, 'id');
const kind = parseFindingKind(row.kind);
const title = parseNonEmptyString(row.title, 'title');
const summary = parseNonEmptyString(row.summary, 'summary');
const createdAt = parseTimestampIso(row.created_at, 'created_at');
const trialRefs = parseStringArray(row.trial_refs, 'trial_refs');
const evidenceRefs = parseStringArray(row.evidence_refs, 'evidence_refs');
return {
id,
createdAt,
payload: {
kind,
title,
summary,
trialRefs,
evidenceRefs,
},
};
}
function parseFindingRow(raw: unknown): FindingRecord {
if (typeof raw !== 'object' || raw === null) {
throw new PostgresFindingsError(
'INVALID_ROW',
'Invalid findings row: expected a non-null object.'
);
}
const row = raw as RawFindingRow;
return {
id: parseNonEmptyString(row.id, 'id'),
title: parseNonEmptyString(row.title, 'title'),
status: parseNonEmptyString(row.status, 'status'),
createdAt: parseTimestampIso(row.created_at, 'created_at'),
summary: parseNonEmptyString(row.summary, 'summary'),
trialRefs: parseStringArray(row.trial_refs, 'trial_refs'),
evidenceRefs: parseStringArray(row.evidence_refs, 'evidence_refs'),
};
}
function parseProviderCaveatRow(raw: unknown): ProviderCaveatRecord {
if (typeof raw !== 'object' || raw === null) {
throw new PostgresFindingsError(
'INVALID_ROW',
'Invalid provider_caveats row: expected a non-null object.'
);
}
const row = raw as RawProviderCaveatRow;
return {
id: parseNonEmptyString(row.id, 'id'),
provider: parseNonEmptyString(row.provider, 'provider'),
dataset: parseNonEmptyString(row.dataset, 'dataset'),
caveat: parseNonEmptyString(row.caveat, 'caveat'),
createdAt: parseTimestampIso(row.created_at, 'created_at'),
};
}
function isPostgresUniqueViolation(err: unknown): boolean {
return (
typeof err === 'object' &&
err !== null &&
(err as { readonly code?: unknown }).code === '23505'
);
}
function buildInsertFindingSql(schemaPrefix: string, keyed: boolean): string {
const findingsTable = quoteTable(schemaPrefix, 'findings');
const lines = [
`INSERT INTO ${findingsTable} (`,
' id,',
' kind,',
' title,',
' summary,',
' status,',
' created_at,',
' trial_refs,',
' evidence_refs,',
' idempotency_key',
')',
'VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9)',
];
if (keyed) {
lines.push('ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING');
}
lines.push('RETURNING id, created_at');
return lines.join('\n');
}
function buildSelectByIdempotencyKeySql(schemaPrefix: string): string {
const findingsTable = quoteTable(schemaPrefix, 'findings');
return [
'SELECT',
' id,',
' kind,',
' title,',
' summary,',
' created_at,',
' trial_refs,',
' evidence_refs',
`FROM ${findingsTable}`,
'WHERE idempotency_key = $1::text',
].join('\n');
}
/**
* Creates an append-only PostgreSQL {@link FindingWritePort} backed by the
* `findings` table (`37-research-findings.sql`).
*/
export function createPostgresFindingWritePort(options: PostgresFindingsOptions): FindingWritePort {
const { executor, schemaPrefix } = validateFactoryOptions(options);
const unkeyedInsertSql = buildInsertFindingSql(schemaPrefix, false);
const keyedInsertSql = buildInsertFindingSql(schemaPrefix, true);
const selectByKeySql = buildSelectByIdempotencyKeySql(schemaPrefix);
return {
async appendFinding(
record: FiledFindingRecord,
idempotencyKey?: string
): Promise<AppendFindingResult> {
const insertParams: readonly unknown[] = [
record.id,
record.kind,
record.title,
record.summary,
record.status,
record.createdAt,
[...record.trialRefs],
[...record.evidenceRefs],
idempotencyKey ?? null,
];
if (idempotencyKey === undefined) {
const result = await executor.query<RawFindingReceiptRow>(unkeyedInsertSql, insertParams);
const rows = extractRows<RawFindingReceiptRow>(result);
if (rows.length !== 1) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Expected 1 inserted findings row, received ${rows.length}.`
);
}
const receipt = parseReceiptRow(rows[0]);
return {
status: 'created',
id: receipt.id,
createdAt: receipt.createdAt,
};
}
let insertRows: readonly RawFindingReceiptRow[];
try {
const result = await executor.query<RawFindingReceiptRow>(keyedInsertSql, insertParams);
insertRows = extractRows<RawFindingReceiptRow>(result);
} catch (err) {
if (!isPostgresUniqueViolation(err)) {
throw err;
}
// A concurrent same-ID retry can collide on the primary key before the
// partial idempotency_key index; resolve only if the stored row for this
// key has the exact same ID, otherwise propagate the primary-key error.
const lookupResult = await executor.query<RawStoredFindingForReplayRow>(selectByKeySql, [
idempotencyKey,
]);
const lookupRows = extractRows<RawStoredFindingForReplayRow>(lookupResult);
if (lookupRows.length === 0) {
throw err;
}
if (lookupRows.length > 1) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Expected at most 1 stored finding for idempotency_key, received ${lookupRows.length}.`
);
}
const stored = parseStoredFindingForReplayRow(lookupRows[0]);
if (stored.id !== record.id) {
throw err;
}
return areFiledFindingPayloadsEqual(stored.payload, record)
? { status: 'replayed', id: stored.id, createdAt: stored.createdAt }
: { status: 'conflict' };
}
if (insertRows.length === 1) {
const receipt = parseReceiptRow(insertRows[0]);
return {
status: 'created',
id: receipt.id,
createdAt: receipt.createdAt,
};
}
if (insertRows.length > 1) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Expected 0 or 1 inserted findings rows, received ${insertRows.length}.`
);
}
// Separate SELECT on a fresh READ COMMITTED snapshot so a concurrent winner
// committed during ON CONFLICT DO NOTHING is visible.
const winnerResult = await executor.query<RawStoredFindingForReplayRow>(selectByKeySql, [
idempotencyKey,
]);
const winnerRows = extractRows<RawStoredFindingForReplayRow>(winnerResult);
if (winnerRows.length !== 1) {
throw new PostgresFindingsError(
'INVALID_ROW',
`Expected 1 stored finding for idempotency_key after conflict, received ${winnerRows.length}.`
);
}
const stored = parseStoredFindingForReplayRow(winnerRows[0]);
return areFiledFindingPayloadsEqual(stored.payload, record)
? { status: 'replayed', id: stored.id, createdAt: stored.createdAt }
: { status: 'conflict' };
},
};
}
/**
* Creates read-only PostgreSQL readers (`listFindings` and `listProviderCaveats`)
* for composing {@link KnowledgePort} in `read_knowledge`.
*/
export function createPostgresKnowledgeReaders(
options: PostgresFindingsOptions
): PostgresKnowledgeReaders {
const { executor, schemaPrefix } = validateFactoryOptions(options);
const findingsTable = quoteTable(schemaPrefix, 'findings');
const caveatsTable = quoteTable(schemaPrefix, 'provider_caveats');
return {
async listFindings(q: FindingQuery): Promise<readonly FindingRecord[]> {
const lines = [
'SELECT',
' id,',
' title,',
' status,',
' created_at,',
' summary,',
' trial_refs,',
' evidence_refs',
`FROM ${findingsTable}`,
];
const params: unknown[] = [];
let normalizedQuery: string | null = null;
if (q.id !== undefined) {
params.push(q.id);
lines.push('WHERE id = $1::text');
} else if (q.query !== undefined) {
normalizedQuery = q.query.toLowerCase();
if (isAsciiOnly(q.query)) {
params.push(`%${escapeLikePattern(q.query)}%`);
lines.push(
`WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\' OR title ~ ${PG_NON_ASCII_REGEX} OR summary ~ ${PG_NON_ASCII_REGEX}`
);
}
}
lines.push('ORDER BY id ASC');
const result = await executor.query<RawFindingRow>(lines.join('\n'), params);
const rows = extractRows<RawFindingRow>(result);
const mapped: FindingRecord[] = [];
for (let i = 0; i < rows.length; i += 1) {
const finding = parseFindingRow(rows[i]);
if (
normalizedQuery !== null &&
!finding.title.toLowerCase().includes(normalizedQuery) &&
!finding.summary.toLowerCase().includes(normalizedQuery)
) {
continue;
}
mapped.push(finding);
}
return mapped;
},
async listProviderCaveats(q: ProviderCaveatQuery): Promise<readonly ProviderCaveatRecord[]> {
const lines = [
'SELECT',
' id,',
' provider,',
' dataset,',
' caveat,',
' created_at',
`FROM ${caveatsTable}`,
];
const conditions: string[] = [];
const params: unknown[] = [];
let normalizedProvider: string | null = null;
let normalizedQuery: string | null = null;
if (q.provider !== undefined) {
normalizedProvider = q.provider.toLowerCase();
if (isAsciiOnly(q.provider)) {
params.push(q.provider);
conditions.push(
`(lower(provider) = lower($${params.length}::text) OR provider ~ ${PG_NON_ASCII_REGEX})`
);
}
}
if (q.id !== undefined) {
params.push(q.id);
conditions.push(`id = $${params.length}::text`);
} else if (q.query !== undefined) {
normalizedQuery = q.query.toLowerCase();
if (isAsciiOnly(q.query)) {
params.push(`%${escapeLikePattern(q.query)}%`);
const idx = params.length;
conditions.push(
`(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\' OR provider ~ ${PG_NON_ASCII_REGEX} OR dataset ~ ${PG_NON_ASCII_REGEX} OR caveat ~ ${PG_NON_ASCII_REGEX})`
);
}
}
if (conditions.length > 0) {
lines.push(`WHERE ${conditions.join(' AND ')}`);
}
lines.push('ORDER BY id ASC');
const result = await executor.query<RawProviderCaveatRow>(lines.join('\n'), params);
const rows = extractRows<RawProviderCaveatRow>(result);
const mapped: ProviderCaveatRecord[] = [];
for (let i = 0; i < rows.length; i += 1) {
const caveat = parseProviderCaveatRow(rows[i]);
if (
normalizedProvider !== null &&
caveat.provider.toLowerCase() !== normalizedProvider
) {
continue;
}
if (
normalizedQuery !== null &&
!caveat.provider.toLowerCase().includes(normalizedQuery) &&
!caveat.dataset.toLowerCase().includes(normalizedQuery) &&
!caveat.caveat.toLowerCase().includes(normalizedQuery)
) {
continue;
}
mapped.push(caveat);
}
return mapped;
},
};
}

View file

@ -1,355 +0,0 @@
/**
* Read-only PostgreSQL security-master adapter implementing {@link SymbolSearchPort}
* for the MCP copilot `search_symbols` tool.
*
* Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is
* injected via {@link SymbolSearchExecutor}.
*/
import type { SymbolSearchPort, SymbolSearchQuery, SymbolSearchRow } from '../tools/search-symbols';
import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input';
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
const CALENDAR_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
/** Error codes thrown by {@link PostgresSymbolSearchError}. */
export type PostgresSymbolSearchErrorCode =
| 'INVALID_EXECUTOR'
| 'INVALID_SCHEMA'
| 'INVALID_ROW';
/** Typed validation error thrown by the PostgreSQL symbol-search adapter. */
export class PostgresSymbolSearchError extends RangeError {
readonly code: PostgresSymbolSearchErrorCode;
constructor(code: PostgresSymbolSearchErrorCode, message: string) {
super(message);
this.name = 'PostgresSymbolSearchError';
this.code = code;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/**
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module
* has no runtime dependency on `pg` and is unit-testable with a fake executor.
*/
export interface SymbolSearchExecutor {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }>;
}
/** Factory options for {@link createPostgresSymbolSearchPort}. */
export interface PostgresSymbolSearchPortOptions {
readonly executor: SymbolSearchExecutor;
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
readonly schema?: string;
}
interface RawSymbolSearchRow {
readonly listing_id: unknown;
readonly instrument_id: unknown;
readonly ticker: unknown;
readonly class_suffix: unknown;
readonly name: unknown;
readonly mic: unknown;
readonly currency: unknown;
readonly isin: unknown;
readonly first_bar_date: unknown;
readonly last_bar_date: unknown;
readonly delisted_at: unknown;
}
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function daysInUtcMonth(year: number, monthIndex: number): number {
if (monthIndex === 1 && isLeapYear(year)) {
return 29;
}
return DAYS_IN_MONTH[monthIndex] ?? 0;
}
function isValidCalendarDate(value: unknown): value is string {
if (typeof value !== 'string') {
return false;
}
const match = CALENDAR_DATE_RE.exec(value);
if (match === null) {
return false;
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
if (month < 1 || month > 12) {
return false;
}
return day >= 1 && day <= daysInUtcMonth(year, month - 1);
}
function escapeLikePattern(value: string): string {
return value.replace(/[\\%_]/g, '\\$&');
}
function quoteTable(schemaPrefix: string, table: string): string {
return `${schemaPrefix}${table}`;
}
function buildSearchSymbolsSql(schemaPrefix: string): string {
const listingTable = quoteTable(schemaPrefix, 'listing');
const instrumentTable = quoteTable(schemaPrefix, 'instrument');
const exchangeTable = quoteTable(schemaPrefix, 'exchange');
const historyTable = quoteTable(schemaPrefix, 'listing_symbol_history');
return [
'SELECT',
' l.listing_id AS listing_id,',
' l.instrument_id AS instrument_id,',
' resolved.ticker AS ticker,',
" NULLIF(l.class_suffix, '') AS class_suffix,",
' i.canonical_name AS name,',
' l.mic AS mic,',
' btrim(l.currency) AS currency,',
" NULLIF(btrim(i.primary_isin), '') AS isin,",
" to_char(l.listed_from, 'YYYY-MM-DD') AS first_bar_date,",
" to_char(l.listed_to, 'YYYY-MM-DD') AS last_bar_date,",
" to_char(delisted.delisted_at, 'YYYY-MM-DD') AS delisted_at",
`FROM ${listingTable} l`,
`INNER JOIN ${instrumentTable} i ON i.instrument_id = l.instrument_id`,
`INNER JOIN ${exchangeTable} e ON e.mic = l.mic`,
'CROSS JOIN LATERAL (',
' SELECT (',
' EXISTS (',
' SELECT 1',
` FROM ${historyTable} h_any`,
' WHERE h_any.listing_id = l.listing_id',
' AND upper(h_any.ticker) = upper(l.ticker_root)',
' )',
' AND NOT EXISTS (',
' SELECT 1',
` FROM ${historyTable} h_past`,
' WHERE h_past.listing_id = l.listing_id',
' AND upper(h_past.ticker) = upper(l.ticker_root)',
' AND h_past.valid_from <= $1::date',
' )',
' ) AS is_future',
') root_state',
'LEFT JOIN LATERAL (',
' SELECT h.ticker',
` FROM ${historyTable} h`,
' WHERE h.listing_id = l.listing_id',
' AND h.valid_from <= $1::date',
' AND (h.valid_to IS NULL OR h.valid_to >= $1::date)',
' ORDER BY h.valid_from DESC, h.ticker ASC',
' LIMIT 1',
') hist_active ON TRUE',
'LEFT JOIN LATERAL (',
' SELECT h.ticker',
` FROM ${historyTable} h`,
' WHERE h.listing_id = l.listing_id',
' AND h.valid_from <= $1::date',
' ORDER BY h.valid_from DESC, h.ticker ASC',
' LIMIT 1',
') hist_prior ON TRUE',
'CROSS JOIN LATERAL (',
' SELECT CASE',
' WHEN hist_active.ticker IS NOT NULL THEN hist_active.ticker',
' WHEN NOT root_state.is_future THEN l.ticker_root',
' ELSE hist_prior.ticker',
' END AS ticker',
') resolved',
'CROSS JOIN LATERAL (',
' SELECT CASE',
" WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to",
' ELSE NULL',
' END AS delisted_at',
') delisted',
'WHERE (l.listed_from IS NULL OR l.listed_from <= $1::date)',
' AND resolved.ticker IS NOT NULL',
" AND resolved.ticker <> ''",
' AND ($4::text IS NULL OR btrim(e.country_iso) = $4::text)',
' AND ($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)',
' AND (',
" resolved.ticker ILIKE $2::text ESCAPE '\\'",
" OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')",
" OR i.canonical_name ILIKE $2::text ESCAPE '\\'",
' OR (i.primary_isin IS NOT NULL AND upper(btrim(i.primary_isin)) = upper($3::text))',
' )',
'ORDER BY l.listing_id ASC',
].join('\n');
}
function parseSafeInt(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
throw new PostgresSymbolSearchError(
'INVALID_ROW',
`Invalid security-master row: "${field}" must be a safe integer.`
);
}
return value;
}
function parseNonEmptyString(value: unknown, field: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new PostgresSymbolSearchError(
'INVALID_ROW',
`Invalid security-master row: "${field}" must be a non-empty string.`
);
}
return value;
}
function parseNullableClassSuffix(value: unknown): string | null {
if (value === null) {
return null;
}
if (typeof value !== 'string') {
throw new PostgresSymbolSearchError(
'INVALID_ROW',
'Invalid security-master row: "class_suffix" must be a string or null.'
);
}
return value === '' ? null : value;
}
function parseNullableIsin(value: unknown): string | null {
if (value === null) {
return null;
}
if (typeof value !== 'string') {
throw new PostgresSymbolSearchError(
'INVALID_ROW',
'Invalid security-master row: "isin" must be a string or null.'
);
}
const trimmed = value.trim();
return trimmed === '' ? null : trimmed;
}
function parseNullableDate(value: unknown, field: string): string | null {
if (value === null) {
return null;
}
if (!isValidCalendarDate(value)) {
throw new PostgresSymbolSearchError(
'INVALID_ROW',
`Invalid security-master row: "${field}" must be a valid YYYY-MM-DD calendar date or null.`
);
}
return value;
}
function mapRawRow(raw: unknown): SymbolSearchRow {
if (typeof raw !== 'object' || raw === null) {
throw new PostgresSymbolSearchError(
'INVALID_ROW',
'Invalid security-master row: expected a non-null object.'
);
}
const row = raw as RawSymbolSearchRow;
const listingId = parseSafeInt(row.listing_id, 'listing_id');
const instrumentId = parseSafeInt(row.instrument_id, 'instrument_id');
const ticker = parseNonEmptyString(row.ticker, 'ticker');
const classSuffix = parseNullableClassSuffix(row.class_suffix);
const name = parseNonEmptyString(row.name, 'name');
const mic = parseNonEmptyString(row.mic, 'mic');
const currency = parseNonEmptyString(row.currency, 'currency').trim();
const isin = parseNullableIsin(row.isin);
const firstBarDate = parseNullableDate(row.first_bar_date, 'first_bar_date');
const lastBarDate = parseNullableDate(row.last_bar_date, 'last_bar_date');
const delistedAt = parseNullableDate(row.delisted_at, 'delisted_at');
return {
listingId,
instrumentId,
ticker,
classSuffix,
name,
mic,
currency,
isin,
firstBarDate,
lastBarDate,
delistedAt,
};
}
function validateFactoryOptions(options: PostgresSymbolSearchPortOptions): {
readonly executor: SymbolSearchExecutor;
readonly schemaPrefix: string;
} {
if (typeof options !== 'object' || options === null) {
throw new PostgresSymbolSearchError(
'INVALID_EXECUTOR',
'Invalid options: expected an object with a SymbolSearchExecutor.'
);
}
const { executor, schema } = options;
if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') {
throw new PostgresSymbolSearchError(
'INVALID_EXECUTOR',
'Invalid executor: expected an object with a callable query(text, params?) method.'
);
}
if (schema === undefined) {
return { executor, schemaPrefix: '' };
}
if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) {
throw new PostgresSymbolSearchError(
'INVALID_SCHEMA',
'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.'
);
}
return { executor, schemaPrefix: `"${schema}".` };
}
/**
* Creates a read-only PostgreSQL {@link SymbolSearchPort} backed by the M1
* security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`).
*/
export function createPostgresSymbolSearchPort(
options: PostgresSymbolSearchPortOptions
): SymbolSearchPort {
const { executor, schemaPrefix } = validateFactoryOptions(options);
const sql = buildSearchSymbolsSql(schemaPrefix);
return {
async searchSymbols(q: SymbolSearchQuery): Promise<readonly SymbolSearchRow[]> {
const cutoffTs = validateVaultCutoffTs(q.vaultCutoffTs);
const cutoffDate = utcDateOf(cutoffTs);
const ilikePattern = `%${escapeLikePattern(q.query)}%`;
const country = q.country ?? null;
const includeDelisted = q.includeDelisted;
const result = await executor.query<RawSymbolSearchRow>(sql, [
cutoffDate,
ilikePattern,
q.query,
country,
includeDelisted,
]);
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
throw new PostgresSymbolSearchError(
'INVALID_ROW',
'Invalid executor response: expected an object with a rows array.'
);
}
const mapped: SymbolSearchRow[] = [];
for (let i = 0; i < result.rows.length; i += 1) {
mapped.push(mapRawRow(result.rows[i]));
}
return mapped;
},
};
}

View file

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

View file

@ -1,110 +0,0 @@
import { type McpServer, type McpServerOptions, createMcpServer } from './server';
import { type AnalyzeSignalToolOptions, createAnalyzeSignalTool } from './tools/analyze-signal';
import { type EventStudyToolOptions, createEventStudyTool } from './tools/event-study';
import { type FileFindingToolOptions, createFileFindingTool } from './tools/file-finding';
import { type QueryDataToolOptions, createQueryDataTool } from './tools/query-data';
import { type ReadKnowledgeToolOptions, createReadKnowledgeTool } from './tools/read-knowledge';
import { type SearchSymbolsToolOptions, createSearchSymbolsTool } from './tools/search-symbols';
/**
* Fixed, documented registration order of the six MCP tools exposed by
* {@link createResearchCopilotMcpServer}.
*/
export const RESEARCH_COPILOT_TOOL_NAMES = Object.freeze([
'search_symbols',
'query_data',
'analyze_signal',
'event_study',
'file_finding',
'read_knowledge',
] as const);
/**
* Composed server options for {@link createResearchCopilotMcpServer}.
*
* Shares the common Vault-fenced `MarketDataStore`, `vaultContext`,
* `TrialLedgerExecutor`, and `principalId` across the tools that consume them
* while passing each tool's remaining injected ports unchanged.
*/
export interface ResearchCopilotMcpServerOptions
extends Pick<McpServerOptions, 'name' | 'version'>,
Pick<QueryDataToolOptions, 'store' | 'vaultContext'>,
Pick<AnalyzeSignalToolOptions, 'ledger' | 'principalId'> {
readonly searchSymbols: Omit<SearchSymbolsToolOptions, 'vaultContext'>;
readonly eventStudy: Pick<EventStudyToolOptions, 'resolveExchangeCalendars'>;
readonly fileFinding: FileFindingToolOptions;
readonly readKnowledge: ReadKnowledgeToolOptions;
}
/**
* Composes all six research MCP tools (`search_symbols`, `query_data`,
* `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`) into a
* single transport-agnostic {@link McpServer}.
*
* Keeps the shared `store`, `vaultContext`, `ledger`, and `principalId`
* authoritative across tools and fails closed if any tool is duplicated,
* missing, unexpected, or out of order.
*/
export function createResearchCopilotMcpServer(
options: ResearchCopilotMcpServerOptions
): McpServer {
if (typeof options !== 'object' || options === null) {
throw new Error('Invalid `options`: expected a ResearchCopilotMcpServerOptions object.');
}
if (typeof options.searchSymbols !== 'object' || options.searchSymbols === null) {
throw new Error('Invalid `searchSymbols`: expected a SearchSymbolsToolOptions object.');
}
if (typeof options.eventStudy !== 'object' || options.eventStudy === null) {
throw new Error('Invalid `eventStudy`: expected an EventStudyToolOptions object.');
}
const tools = [
createSearchSymbolsTool({
...options.searchSymbols,
vaultContext: options.vaultContext,
}),
createQueryDataTool({
store: options.store,
vaultContext: options.vaultContext,
}),
createAnalyzeSignalTool({
store: options.store,
ledger: options.ledger,
vaultContext: options.vaultContext,
principalId: options.principalId,
}),
createEventStudyTool({
store: options.store,
ledger: options.ledger,
vaultContext: options.vaultContext,
principalId: options.principalId,
resolveExchangeCalendars: options.eventStudy.resolveExchangeCalendars,
}),
createFileFindingTool(options.fileFinding),
createReadKnowledgeTool(options.readKnowledge),
];
const server = createMcpServer({
name: options.name,
version: options.version,
tools,
});
const registered = server.listTools();
if (registered.length !== RESEARCH_COPILOT_TOOL_NAMES.length) {
throw new Error(
`Research copilot MCP server expected ${RESEARCH_COPILOT_TOOL_NAMES.length} tools, got ${registered.length}.`
);
}
for (let i = 0; i < RESEARCH_COPILOT_TOOL_NAMES.length; i += 1) {
const expectedName = RESEARCH_COPILOT_TOOL_NAMES[i];
const actualName = registered[i]?.name;
if (actualName !== expectedName) {
throw new Error(
`Research copilot MCP server tool mismatch at index ${i}: expected "${expectedName}", got "${String(actualName)}".`
);
}
}
return server;
}

View file

@ -1,835 +0,0 @@
/**
* Dependency-free stdio host composition for the MCP research copilot.
*
* Parses `RESEARCH_MCP_*` environment variables into a strict typed
* {@link ResearchCopilotHostConfig} and composes injected PostgreSQL executor,
* market data store, and library-card reader factories with
* {@link createBarSessionDatesPort}, {@link createPostgresResearchCopilotServer},
* and {@link runStdioServer}.
*
* Pure and dependency-free: zero `node:*` imports, zero bare `process` access,
* no `pg` dependency, and no DuckDB driver import.
*/
import { z } from 'zod';
import type { MarketDataStore } from '../../market-data-store';
import {
MAX_ECMASCRIPT_EPOCH_MS,
isValidInt32,
parseCalendarDayKey,
} from '../../panel-shared';
import {
type BarSessionDatesPortOptions,
createBarSessionDatesPort,
} from '../adapters/bar-session-dates';
import {
EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET,
EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE,
EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET,
EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE,
type EarlyCloseOverrides,
} from '../adapters/exchange-calendars';
import {
type PostgresResearchCopilotExecutor,
createPostgresResearchCopilotServer,
} from '../adapters/postgres-copilot';
import type { McpServer } from '../server';
import { type StdioServerOptions, runStdioServer } from '../stdio';
import type { KnowledgePort } from '../tools/read-knowledge';
/** Environment variable prefix owned by {@link parseResearchCopilotHostConfig}. */
export const RESEARCH_MCP_ENV_PREFIX = 'RESEARCH_MCP_';
/** Headless MCP server name announced during `initialize`. */
export const RESEARCH_COPILOT_HOST_NAME = 'stock-bot-research-copilot';
/** Headless MCP server version announced during `initialize`. */
export const RESEARCH_COPILOT_HOST_VERSION = '0.1.0';
const ENV_POSTGRES_URL = 'RESEARCH_MCP_POSTGRES_URL';
const ENV_POSTGRES_SCHEMA = 'RESEARCH_MCP_POSTGRES_SCHEMA';
const ENV_CURATED_ROOT = 'RESEARCH_MCP_CURATED_ROOT';
const ENV_VAULT_CUTOFF_TS = 'RESEARCH_MCP_VAULT_CUTOFF_TS';
const ENV_PRINCIPAL_ID = 'RESEARCH_MCP_PRINCIPAL_ID';
const ENV_LIBRARY_ROOT = 'RESEARCH_MCP_LIBRARY_ROOT';
const ENV_SESSION_REFERENCE_LISTINGS = 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS';
const ENV_EARLY_CLOSES = 'RESEARCH_MCP_EARLY_CLOSES';
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
const AGENT_PRINCIPAL_RE =
/^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const STRICT_UTC_INSTANT_RE =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/;
const nonBlankEnvString = z.string().refine(value => value.trim().length > 0, {
message: 'blank',
});
const rawHostEnvSchema = z
.object({
[ENV_POSTGRES_URL]: nonBlankEnvString,
[ENV_POSTGRES_SCHEMA]: nonBlankEnvString.optional(),
[ENV_CURATED_ROOT]: nonBlankEnvString,
[ENV_VAULT_CUTOFF_TS]: nonBlankEnvString,
[ENV_PRINCIPAL_ID]: nonBlankEnvString,
[ENV_LIBRARY_ROOT]: nonBlankEnvString,
[ENV_SESSION_REFERENCE_LISTINGS]: nonBlankEnvString,
[ENV_EARLY_CLOSES]: nonBlankEnvString.optional(),
})
.strict();
/** Validated configuration parsed from `RESEARCH_MCP_*` environment variables. */
export interface ResearchCopilotHostConfig {
readonly postgresUrl: string;
readonly postgresSchema?: string;
readonly curatedRoot: string;
readonly vaultCutoffTs: number;
readonly principalId: string;
readonly libraryRoot: string;
readonly referenceListingIds: BarSessionDatesPortOptions['referenceListingIds'];
readonly earlyCloses?: EarlyCloseOverrides;
}
/**
* Typed configuration error thrown by {@link parseResearchCopilotHostConfig}.
*
* Always names the offending `RESEARCH_MCP_*` variable with a fixed reason and
* never embeds raw environment values, DSNs, JSON parser output, or Zod dumps.
*/
export class ResearchCopilotHostConfigError extends RangeError {
readonly variable: string;
constructor(variable: string, message: string) {
super(message);
this.name = 'ResearchCopilotHostConfigError';
this.variable = variable;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/** Managed PostgreSQL executor handle returned by `deps.openExecutor`. */
export interface ManagedPostgresExecutor {
readonly executor: PostgresResearchCopilotExecutor;
close(): Promise<void> | void;
}
/** Managed market data store handle returned by `deps.openStore`. */
export interface ManagedMarketDataStore {
readonly store: MarketDataStore;
close(): Promise<void> | void;
}
/** Library-card reader handle returned by `deps.createLibraryCardReader`. */
export interface LibraryCardReaderHandle {
readonly listLibraryCards: KnowledgePort['listLibraryCards'];
}
/** Injected dependencies for {@link runResearchCopilotStdioHost}. */
export interface ResearchCopilotStdioHostDeps {
readonly config: ResearchCopilotHostConfig;
readonly openExecutor: (
config: ResearchCopilotHostConfig
) => Promise<ManagedPostgresExecutor> | ManagedPostgresExecutor;
readonly openStore: (
config: ResearchCopilotHostConfig
) => Promise<ManagedMarketDataStore> | ManagedMarketDataStore;
readonly createLibraryCardReader: (
config: ResearchCopilotHostConfig
) => Promise<LibraryCardReaderHandle> | LibraryCardReaderHandle;
readonly newId: () => string;
readonly now: () => Date | number;
readonly stdio?: StdioServerOptions;
}
type HostStage =
| 'executor_open'
| 'store_open'
| 'library_reader'
| 'server_init'
| 'stdio_serve'
| 'cleanup';
const STAGE_ERROR_MESSAGES: Readonly<Record<HostStage, string>> = {
executor_open: 'Research copilot stdio host failed while opening the PostgreSQL executor.',
store_open: 'Research copilot stdio host failed while opening the market data store.',
library_reader: 'Research copilot stdio host failed while creating the library card reader.',
server_init: 'Research copilot stdio host failed while initializing the MCP server.',
stdio_serve: 'Research copilot stdio host failed while serving MCP stdio.',
cleanup: 'Research copilot stdio host failed while closing host resources.',
};
function isPlainObjectRecord(value: unknown): value is Record<string, unknown> {
if (typeof value !== 'object' || value === null) {
return false;
}
const proto: unknown = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function defineDataProperty<T>(target: Record<string, T>, key: string, value: T): void {
Object.defineProperty(target, key, {
value,
enumerable: true,
writable: true,
configurable: true,
});
}
function parsePostgresUrl(raw: string): string {
if (raw !== raw.trim()) {
throw new ResearchCopilotHostConfigError(
ENV_POSTGRES_URL,
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.`
);
}
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
throw new ResearchCopilotHostConfigError(
ENV_POSTGRES_URL,
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL.`
);
}
if (
(parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') ||
parsed.hostname.length === 0
) {
throw new ResearchCopilotHostConfigError(
ENV_POSTGRES_URL,
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a postgres:// or postgresql:// URL with a non-empty host.`
);
}
try {
if (parsed.username.length > 0) {
decodeURIComponent(parsed.username);
}
if (parsed.password.length > 0) {
decodeURIComponent(parsed.password);
}
} catch {
throw new ResearchCopilotHostConfigError(
ENV_POSTGRES_URL,
`Invalid configuration variable "${ENV_POSTGRES_URL}": URL credentials contain invalid percent-encoding.`
);
}
return raw;
}
function parsePostgresSchema(raw: string): string {
if (!SCHEMA_IDENT_RE.test(raw)) {
throw new ResearchCopilotHostConfigError(
ENV_POSTGRES_SCHEMA,
`Invalid configuration variable "${ENV_POSTGRES_SCHEMA}": expected a PostgreSQL identifier matching ^[a-z_][a-z0-9_]*$.`
);
}
return raw;
}
function parsePrincipalId(raw: string): string {
if (raw !== 'operator' && !AGENT_PRINCIPAL_RE.test(raw)) {
throw new ResearchCopilotHostConfigError(
ENV_PRINCIPAL_ID,
`Invalid configuration variable "${ENV_PRINCIPAL_ID}": expected "operator" or "agent:<lowercase-uuid>".`
);
}
return raw;
}
function parseVaultCutoffTs(raw: string): number {
const match = STRICT_UTC_INSTANT_RE.exec(raw);
if (match === null) {
throw new ResearchCopilotHostConfigError(
ENV_VAULT_CUTOFF_TS,
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": expected a strict ISO-8601 UTC instant ending in Z.`
);
}
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 fracRaw = match[7];
const millis = fracRaw === undefined ? 0 : Number(fracRaw.padEnd(3, '0'));
if (
month < 1 ||
month > 12 ||
day < 1 ||
day > 31 ||
hour > 23 ||
minute > 59 ||
second > 59
) {
throw new ResearchCopilotHostConfigError(
ENV_VAULT_CUTOFF_TS,
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is not a valid UTC calendar instant.`
);
}
const epochMs = Date.UTC(year, month - 1, day, hour, minute, second, millis);
if (!Number.isSafeInteger(epochMs) || Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS) {
throw new ResearchCopilotHostConfigError(
ENV_VAULT_CUTOFF_TS,
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is out of supported epoch range.`
);
}
const check = new Date(epochMs);
if (
check.getUTCFullYear() !== year ||
check.getUTCMonth() !== month - 1 ||
check.getUTCDate() !== day ||
check.getUTCHours() !== hour ||
check.getUTCMinutes() !== minute ||
check.getUTCSeconds() !== second ||
check.getUTCMilliseconds() !== millis
) {
throw new ResearchCopilotHostConfigError(
ENV_VAULT_CUTOFF_TS,
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is not a valid UTC calendar instant.`
);
}
return epochMs;
}
function parseReferenceListingIds(
raw: string
): BarSessionDatesPortOptions['referenceListingIds'] {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": expected valid JSON.`
);
}
if (!isPlainObjectRecord(parsed)) {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": expected a JSON object mapping calendar codes to listing ID arrays.`
);
}
const result: Record<string, readonly number[]> = {};
const entries = Object.entries(parsed);
for (let i = 0; i < entries.length; i += 1) {
const [calendarCode, rawIds] = entries[i] as [string, unknown];
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": calendar codes must be non-empty trimmed strings.`
);
}
if (!Array.isArray(rawIds) || rawIds.length === 0) {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": each calendar must map to a non-empty array of positive INT32 listing IDs.`
);
}
const copiedIds: number[] = [];
const seen = new Set<number>();
for (let j = 0; j < rawIds.length; j += 1) {
const id: unknown = rawIds[j];
if (!isValidInt32(id) || id <= 0) {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": listing IDs must be positive 32-bit integers.`
);
}
if (seen.has(id)) {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": listing IDs within a calendar must be distinct.`
);
}
seen.add(id);
copiedIds.push(id);
}
defineDataProperty(result, calendarCode, copiedIds);
}
return result;
}
function parseEarlyClosesEnv(raw: string): EarlyCloseOverrides {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": expected valid JSON.`
);
}
if (!isPlainObjectRecord(parsed)) {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": expected a JSON object mapping calendar codes to date/minute overrides.`
);
}
const result: Record<string, Readonly<Record<string, number>>> = {};
const calendarEntries = Object.entries(parsed);
for (let i = 0; i < calendarEntries.length; i += 1) {
const [calendarCode, rawDates] = calendarEntries[i] as [string, unknown];
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": calendar codes must be non-empty trimmed strings.`
);
}
if (!isPlainObjectRecord(rawDates)) {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": each calendar must map to an object of YYYY-MM-DD dates and Eastern close minutes.`
);
}
const dates: Record<string, number> = {};
const dateEntries = Object.entries(rawDates);
for (let j = 0; j < dateEntries.length; j += 1) {
const [dateStr, minute] = dateEntries[j] as [string, unknown];
parseCalendarDayKey(dateStr, ENV_EARLY_CLOSES, () =>
new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": override dates must be valid YYYY-MM-DD calendar dates.`
)
);
if (
dateStr < EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE ||
dateStr > EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE
) {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": override dates must fall within ${EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE}..=${EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE}.`
);
}
if (
typeof minute !== 'number' ||
!Number.isSafeInteger(minute) ||
minute < EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET ||
minute > EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET
) {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": close minutes must be integers from ${EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET} through ${EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET}.`
);
}
defineDataProperty(dates, dateStr, minute);
}
defineDataProperty(result, calendarCode, dates);
}
return result;
}
/**
* Purely parses and validates `RESEARCH_MCP_*` environment variables into a
* typed {@link ResearchCopilotHostConfig}.
*
* Unrelated environment keys are ignored. Unknown `RESEARCH_MCP_*` keys,
* missing required variables, blank values, and malformed fields fail closed
* with {@link ResearchCopilotHostConfigError} naming the variable without
* exposing raw values or credentials.
*/
export function parseResearchCopilotHostConfig(
env: Readonly<Record<string, string | undefined>>
): ResearchCopilotHostConfig {
if (typeof env !== 'object' || env === null) {
throw new ResearchCopilotHostConfigError(
RESEARCH_MCP_ENV_PREFIX,
'Invalid environment object: expected a key-value record.'
);
}
const scopedEnv: Record<string, unknown> = {};
const entries = Object.entries(env);
for (let i = 0; i < entries.length; i += 1) {
const [key, value] = entries[i] as [string, unknown];
if (key.startsWith(RESEARCH_MCP_ENV_PREFIX) && value !== undefined) {
defineDataProperty(scopedEnv, key, value);
}
}
const parsedEnv = rawHostEnvSchema.safeParse(scopedEnv);
if (!parsedEnv.success) {
const firstIssue = parsedEnv.error.issues[0];
if (firstIssue !== undefined) {
if (firstIssue.code === 'unrecognized_keys') {
const unknownKey = firstIssue.keys[0] ?? RESEARCH_MCP_ENV_PREFIX;
throw new ResearchCopilotHostConfigError(
unknownKey,
`Unknown configuration variable "${unknownKey}".`
);
}
const variable =
typeof firstIssue.path[0] === 'string' ? firstIssue.path[0] : RESEARCH_MCP_ENV_PREFIX;
if (firstIssue.code === 'invalid_type' && firstIssue.received === 'undefined') {
throw new ResearchCopilotHostConfigError(
variable,
`Missing required configuration variable "${variable}".`
);
}
if (firstIssue.code === 'custom') {
throw new ResearchCopilotHostConfigError(
variable,
`Invalid configuration variable "${variable}": value must not be empty or whitespace.`
);
}
throw new ResearchCopilotHostConfigError(
variable,
`Invalid configuration variable "${variable}": expected a non-empty string.`
);
}
throw new ResearchCopilotHostConfigError(
RESEARCH_MCP_ENV_PREFIX,
'Invalid research copilot host configuration.'
);
}
const data = parsedEnv.data;
const postgresUrl = parsePostgresUrl(data[ENV_POSTGRES_URL]);
const postgresSchema =
data[ENV_POSTGRES_SCHEMA] !== undefined
? parsePostgresSchema(data[ENV_POSTGRES_SCHEMA])
: undefined;
const curatedRoot = data[ENV_CURATED_ROOT].trim();
const vaultCutoffTs = parseVaultCutoffTs(data[ENV_VAULT_CUTOFF_TS]);
const principalId = parsePrincipalId(data[ENV_PRINCIPAL_ID]);
const libraryRoot = data[ENV_LIBRARY_ROOT].trim();
const referenceListingIds = parseReferenceListingIds(data[ENV_SESSION_REFERENCE_LISTINGS]);
const earlyCloses =
data[ENV_EARLY_CLOSES] !== undefined
? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES])
: undefined;
return {
postgresUrl,
...(postgresSchema !== undefined ? { postgresSchema } : {}),
curatedRoot,
vaultCutoffTs,
principalId,
libraryRoot,
referenceListingIds,
...(earlyCloses !== undefined ? { earlyCloses } : {}),
};
}
function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
if (raw.length === 0) {
return;
}
needles.add(raw);
try {
const decoded = decodeURIComponent(raw);
if (decoded.length > 0) {
needles.add(decoded);
}
} catch {
// Malformed percent-encoding: raw needle is already registered.
}
}
function collectSecretNeedles(postgresUrl: string): readonly string[] {
const needles = new Set<string>();
if (postgresUrl.length > 0) {
needles.add(postgresUrl);
}
try {
const parsed = new URL(postgresUrl);
if (parsed.href.length > 0) {
needles.add(parsed.href);
}
addRawAndDecodedNeedle(needles, parsed.password);
for (const [key, value] of parsed.searchParams.entries()) {
if (key.toLowerCase() === 'password' && value.length > 0) {
needles.add(value);
}
}
if (parsed.search.length > 1) {
const pairs = parsed.search.slice(1).split('&');
for (let i = 0; i < pairs.length; i += 1) {
const pair = pairs[i] as string;
const eqIdx = pair.indexOf('=');
if (eqIdx <= 0) {
continue;
}
const rawKey = pair.slice(0, eqIdx);
let decodedKey = rawKey;
try {
decodedKey = decodeURIComponent(rawKey);
} catch {
// Keep rawKey if percent-decoding fails.
}
if (decodedKey.toLowerCase() === 'password') {
addRawAndDecodedNeedle(needles, pair.slice(eqIdx + 1));
}
}
}
} catch {
// Non-URL postgresUrl passed directly to runResearchCopilotStdioHost: raw string is covered.
}
return Array.from(needles);
}
function containsAnyNeedle(text: string, needles: readonly string[]): boolean {
for (let i = 0; i < needles.length; i += 1) {
if (text.includes(needles[i] as string)) {
return true;
}
}
return false;
}
function isErrorSafeToSurface(
error: unknown,
needles: readonly string[],
visited: Set<unknown> = new Set(),
depth = 0
): error is Error {
if (!(error instanceof Error) || depth > 8) {
return false;
}
if (visited.has(error)) {
return true;
}
visited.add(error);
try {
const message = error.message;
if (typeof message !== 'string' || containsAnyNeedle(message, needles)) {
return false;
}
const stack = error.stack;
if (typeof stack === 'string' && containsAnyNeedle(stack, needles)) {
return false;
}
const cause = (error as { readonly cause?: unknown }).cause;
if (cause !== undefined && !isErrorSafeToSurface(cause, needles, visited, depth + 1)) {
return false;
}
if (error instanceof AggregateError || 'errors' in error) {
const nested = (error as { readonly errors?: unknown }).errors;
if (nested !== undefined) {
if (!Array.isArray(nested)) {
return false;
}
for (let i = 0; i < nested.length; i += 1) {
if (!isErrorSafeToSurface(nested[i], needles, visited, depth + 1)) {
return false;
}
}
}
}
return true;
} catch {
return false;
}
}
function sanitizeHostError(
error: unknown,
stage: HostStage,
needles: readonly string[]
): Error {
if (isErrorSafeToSurface(error, needles)) {
return error;
}
return new Error(STAGE_ERROR_MESSAGES[stage]);
}
function validateHostDeps(deps: ResearchCopilotStdioHostDeps): void {
if (typeof deps !== 'object' || deps === null) {
throw new Error('Invalid `deps`: expected a ResearchCopilotStdioHostDeps object.');
}
if (typeof deps.config !== 'object' || deps.config === null) {
throw new Error('Invalid `deps.config`: expected a ResearchCopilotHostConfig object.');
}
if (typeof deps.openExecutor !== 'function') {
throw new Error('Invalid `deps.openExecutor`: expected a callable factory function.');
}
if (typeof deps.openStore !== 'function') {
throw new Error('Invalid `deps.openStore`: expected a callable factory function.');
}
if (typeof deps.createLibraryCardReader !== 'function') {
throw new Error(
'Invalid `deps.createLibraryCardReader`: expected a callable factory function.'
);
}
if (typeof deps.newId !== 'function') {
throw new Error('Invalid `deps.newId`: expected a callable ID generator function.');
}
if (typeof deps.now !== 'function') {
throw new Error('Invalid `deps.now`: expected a callable clock function.');
}
}
/**
* Composes and runs the headless MCP research copilot over stdio using
* caller-injected resource factories.
*
* - Acquires resources sequentially (`openExecutor` -> `openStore` ->
* `createLibraryCardReader`) before serving any stdio input.
* - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff; the
* caller's `openStore` factory must configure the store with that same cutoff.
* - Always closes every acquired resource exactly once in reverse acquisition
* order on EOF or error, preserving the primary failure when safe and
* replacing credential-bearing or uninspectable errors with a fixed
* stage-specific error without a raw `cause`.
*/
export async function runResearchCopilotStdioHost(
deps: ResearchCopilotStdioHostDeps
): Promise<void> {
validateHostDeps(deps);
const { config } = deps;
const secretNeedles = collectSecretNeedles(
typeof config.postgresUrl === 'string' ? config.postgresUrl : ''
);
const closers: Array<() => Promise<void> | void> = [];
let primaryError: { readonly error: unknown; readonly stage: HostStage } | null = null;
try {
let executorHandle: ManagedPostgresExecutor;
try {
executorHandle = await deps.openExecutor(config);
} catch (error) {
primaryError = { error, stage: 'executor_open' };
throw error;
}
if (
typeof executorHandle !== 'object' ||
executorHandle === null ||
typeof executorHandle.close !== 'function'
) {
const error = new Error(
'Invalid executor handle: expected an object with executor and close().'
);
primaryError = { error, stage: 'executor_open' };
throw error;
}
closers.push(() => executorHandle.close());
let storeHandle: ManagedMarketDataStore;
try {
storeHandle = await deps.openStore(config);
} catch (error) {
primaryError = { error, stage: 'store_open' };
throw error;
}
if (
typeof storeHandle !== 'object' ||
storeHandle === null ||
typeof storeHandle.close !== 'function'
) {
const error = new Error(
'Invalid store handle: expected an object with store and close().'
);
primaryError = { error, stage: 'store_open' };
throw error;
}
closers.push(() => storeHandle.close());
let libraryReader: LibraryCardReaderHandle;
try {
libraryReader = await deps.createLibraryCardReader(config);
} catch (error) {
primaryError = { error, stage: 'library_reader' };
throw error;
}
if (
typeof libraryReader !== 'object' ||
libraryReader === null ||
typeof libraryReader.listLibraryCards !== 'function'
) {
const error = new Error(
'Invalid library card reader: expected an object with listLibraryCards().'
);
primaryError = { error, stage: 'library_reader' };
throw error;
}
let server: McpServer;
try {
const sessionDates = createBarSessionDatesPort({
store: storeHandle.store,
referenceListingIds: config.referenceListingIds,
});
server = createPostgresResearchCopilotServer({
name: RESEARCH_COPILOT_HOST_NAME,
version: RESEARCH_COPILOT_HOST_VERSION,
executor: executorHandle.executor,
...(config.postgresSchema !== undefined ? { schema: config.postgresSchema } : {}),
store: storeHandle.store,
vaultContext: { vaultCutoffTs: config.vaultCutoffTs },
principalId: config.principalId,
listLibraryCards: query => libraryReader.listLibraryCards(query),
sessionDates,
...(config.earlyCloses !== undefined ? { earlyCloses: config.earlyCloses } : {}),
newId: deps.newId,
now: deps.now,
});
} catch (error) {
primaryError = { error, stage: 'server_init' };
throw error;
}
try {
await runStdioServer(server, deps.stdio);
} catch (error) {
primaryError = { error, stage: 'stdio_serve' };
throw error;
}
} catch (error) {
if (primaryError === null) {
primaryError = { error, stage: 'server_init' };
}
}
let firstCloseError: { readonly error: unknown } | null = null;
for (let i = closers.length - 1; i >= 0; i -= 1) {
try {
await closers[i]?.();
} catch (closeErr) {
if (firstCloseError === null) {
firstCloseError = { error: closeErr };
}
}
}
if (primaryError !== null) {
throw sanitizeHostError(primaryError.error, primaryError.stage, secretNeedles);
}
if (firstCloseError !== null) {
throw sanitizeHostError(firstCloseError.error, 'cleanup', secretNeedles);
}
}

View file

@ -1,18 +0,0 @@
export * from './adapters/library-cards';
export * from './adapters/postgres-findings';
export * from './adapters/postgres-symbol-search';
export * from './adapters/postgres-trial-ref';
export * from './adapters/exchange-calendars';
export * from './copilot-server';
export * from './protocol';
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';
export * from './adapters/postgres-copilot';
export * from './adapters/bar-session-dates';
export * from './host/stdio-host';

View file

@ -1,274 +0,0 @@
import { z } from 'zod';
/** Supported Model Context Protocol revision. */
export const MCP_PROTOCOL_VERSION = '2025-03-26';
/** Standard JSON-RPC 2.0 error codes. */
export const JSON_RPC_ERROR_CODES = {
PARSE_ERROR: -32700,
INVALID_REQUEST: -32600,
METHOD_NOT_FOUND: -32601,
INVALID_PARAMS: -32602,
INTERNAL_ERROR: -32603,
} as const;
export type JsonRpcErrorCode = (typeof JSON_RPC_ERROR_CODES)[keyof typeof JSON_RPC_ERROR_CODES];
/** Valid JSON-RPC 2.0 request identifier (string or finite number). */
export const jsonRpcIdSchema = z.union([z.string(), z.number().finite()]);
export type JsonRpcId = z.infer<typeof jsonRpcIdSchema>;
/** Strict JSON-RPC 2.0 request envelope (must carry a valid `id`). */
export const jsonRpcRequestSchema = z
.object({
jsonrpc: z.literal('2.0'),
id: jsonRpcIdSchema,
method: z.string().min(1),
params: z.unknown().optional(),
})
.strict();
export type JsonRpcRequest = z.infer<typeof jsonRpcRequestSchema>;
/** Strict JSON-RPC 2.0 notification envelope (must NOT carry an `id`). */
export const jsonRpcNotificationSchema = z
.object({
jsonrpc: z.literal('2.0'),
method: z.string().min(1),
params: z.unknown().optional(),
})
.strict();
export type JsonRpcNotification = z.infer<typeof jsonRpcNotificationSchema>;
export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification;
export interface JsonRpcSuccessResponse {
readonly jsonrpc: '2.0';
readonly id: JsonRpcId;
readonly result: unknown;
}
export interface JsonRpcErrorObject {
readonly code: number;
readonly message: string;
readonly data?: unknown;
}
export interface JsonRpcErrorResponse {
readonly jsonrpc: '2.0';
readonly id: JsonRpcId | null;
readonly error: JsonRpcErrorObject;
}
export type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse;
/** MCP text content block returned inside `tools/call` results. */
export interface McpTextContent {
readonly type: 'text';
readonly text: string;
}
/** MCP `tools/call` result envelope. */
export interface McpToolCallResult {
readonly content: readonly McpTextContent[];
readonly isError?: boolean;
}
/** Minimal JSON Schema Draft 7/2020-12 property definition for MCP tool inputs. */
export interface JsonSchemaProperty {
readonly type?: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null';
readonly description?: string;
readonly enum?: readonly (string | number | boolean | null)[];
readonly const?: string | number | boolean | null;
readonly minimum?: number;
readonly maximum?: number;
readonly exclusiveMinimum?: number;
readonly exclusiveMaximum?: number;
readonly minLength?: number;
readonly maxLength?: number;
readonly minItems?: number;
readonly maxItems?: number;
readonly items?: JsonSchemaProperty;
readonly properties?: Readonly<Record<string, JsonSchemaProperty>>;
readonly required?: readonly string[];
readonly additionalProperties?: boolean;
readonly anyOf?: readonly JsonSchemaProperty[];
readonly default?: unknown;
}
/** Strict top-level JSON Schema object emitted by `tools/list`. */
export interface JsonSchemaObject {
readonly type: 'object';
readonly properties: Readonly<Record<string, JsonSchemaProperty>>;
readonly required?: readonly string[];
readonly additionalProperties: false;
readonly description?: string;
}
/** Tool metadata returned in `tools/list`. */
export interface McpToolDescriptor {
readonly name: string;
readonly description: string;
readonly inputSchema: JsonSchemaObject;
}
/** Valid MCP progress token (`string | finite number`). */
export const mcpProgressTokenSchema = z.union([z.string(), z.number().finite()]);
export type McpProgressToken = z.infer<typeof mcpProgressTokenSchema>;
/** Standard optional MCP `_meta` request/notification metadata bag. */
export const mcpRequestMetaSchema = z
.object({
progressToken: mcpProgressTokenSchema.optional(),
})
.passthrough();
export type McpRequestMeta = z.infer<typeof mcpRequestMetaSchema>;
const jsonObjectSchema = z.custom<Record<string, unknown>>(
(value): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value),
{ message: 'Expected a JSON object.' }
);
/** Strict MCP `initialize` params schema. */
export const mcpInitializeParamsSchema = z
.object({
protocolVersion: z.string().min(1).optional(),
capabilities: z.record(z.unknown()).optional(),
clientInfo: z
.object({
name: z.string().min(1),
version: z.string().min(1),
})
.strict()
.optional(),
_meta: mcpRequestMetaSchema.optional(),
})
.strict();
/** Strict MCP `notifications/initialized` params schema. */
export const mcpInitializedNotificationParamsSchema = z
.object({
_meta: mcpRequestMetaSchema.optional(),
})
.strict();
/** Strict MCP `ping` params schema. */
export const mcpPingParamsSchema = z
.object({
_meta: mcpRequestMetaSchema.optional(),
})
.strict();
/** Strict MCP `tools/list` params schema. */
export const mcpToolsListParamsSchema = z
.object({
cursor: z.string().min(1).optional(),
_meta: mcpRequestMetaSchema.optional(),
})
.strict();
/** Strict MCP `tools/call` params schema (preserves own keys on `arguments`). */
export const mcpToolsCallParamsSchema = z
.object({
name: z.string().min(1),
arguments: jsonObjectSchema.optional(),
_meta: mcpRequestMetaSchema.optional(),
})
.strict();
export type ParsedJsonRpcMessage =
| { readonly ok: true; readonly kind: 'request'; readonly message: JsonRpcRequest }
| { readonly ok: true; readonly kind: 'notification'; readonly message: JsonRpcNotification }
| {
readonly ok: false;
readonly errorCode: JsonRpcErrorCode;
readonly message: string;
};
/**
* Parses a raw JSON-RPC 2.0 message string.
*
* - Malformed JSON returns `PARSE_ERROR` (-32700).
* - Non-object payloads or invalid envelopes (including an explicit invalid `id`
* such as `id: null` or `id: true`) return `INVALID_REQUEST` (-32600).
* - Objects without an `id` property are parsed as notifications.
*/
export function parseJsonRpcMessage(raw: string): ParsedJsonRpcMessage {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return {
ok: false,
errorCode: JSON_RPC_ERROR_CODES.PARSE_ERROR,
message: 'Parse error: invalid JSON.',
};
}
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
return {
ok: false,
errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
message: 'Invalid Request: expected a JSON-RPC 2.0 object.',
};
}
const hasId = Object.prototype.hasOwnProperty.call(parsed, 'id');
if (hasId) {
const requestResult = jsonRpcRequestSchema.safeParse(parsed);
if (!requestResult.success) {
return {
ok: false,
errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
message: 'Invalid Request: malformed JSON-RPC 2.0 request envelope.',
};
}
return {
ok: true,
kind: 'request',
message: requestResult.data,
};
}
const notificationResult = jsonRpcNotificationSchema.safeParse(parsed);
if (!notificationResult.success) {
return {
ok: false,
errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
message: 'Invalid Request: malformed JSON-RPC 2.0 notification envelope.',
};
}
return {
ok: true,
kind: 'notification',
message: notificationResult.data,
};
}
/** Builds a JSON-RPC 2.0 success response object. */
export function jsonRpcSuccess(id: JsonRpcId, result: unknown): JsonRpcSuccessResponse {
return {
jsonrpc: '2.0',
id,
result,
};
}
/** Builds a JSON-RPC 2.0 error response object. */
export function jsonRpcError(
id: JsonRpcId | null,
code: number,
message: string,
data?: unknown
): JsonRpcErrorResponse {
const error: JsonRpcErrorObject =
data !== undefined ? { code, message, data } : { code, message };
return {
jsonrpc: '2.0',
id,
error,
};
}

View file

@ -1,536 +0,0 @@
import { z } from 'zod';
import {
JSON_RPC_ERROR_CODES,
type JsonSchemaObject,
type JsonSchemaProperty,
MCP_PROTOCOL_VERSION,
type McpToolCallResult,
type McpToolDescriptor,
jsonRpcError,
jsonRpcSuccess,
mcpInitializeParamsSchema,
mcpPingParamsSchema,
mcpToolsCallParamsSchema,
mcpToolsListParamsSchema,
parseJsonRpcMessage,
} from './protocol';
/** Configuration for defining a strongly typed MCP tool. */
export interface McpToolDefinition<TInput> {
readonly name: string;
readonly description: string;
readonly inputSchema: z.ZodType<TInput, z.ZodTypeDef, unknown>;
readonly jsonSchema?: JsonSchemaObject;
readonly handler: (input: TInput) => Promise<McpToolCallResult> | McpToolCallResult;
}
/** Type-erased tool entry registered on an {@link McpServer}. */
export interface McpToolEntry {
readonly name: string;
readonly description: string;
readonly inputSchema: JsonSchemaObject;
readonly execute: (rawArguments: Record<string, unknown>) => Promise<McpToolCallResult>;
}
/** Options for {@link createMcpServer}. */
export interface McpServerOptions {
readonly name: string;
readonly version: string;
readonly tools?: readonly McpToolEntry[];
}
/** Transport-agnostic MCP JSON-RPC 2.0 server interface. */
export interface McpServer {
readonly name: string;
readonly version: string;
listTools(): readonly McpToolDescriptor[];
handleMessage(raw: string): Promise<string | null>;
}
function isOptionalSchema(schema: z.ZodTypeAny): boolean {
if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault) {
return true;
}
if (schema instanceof z.ZodEffects) {
return isOptionalSchema(schema._def.schema);
}
return false;
}
function withDescription(
prop: JsonSchemaProperty,
description: string | undefined
): JsonSchemaProperty {
if (description !== undefined && prop.description === undefined) {
return { ...prop, description };
}
return prop;
}
function convertZodType(schema: z.ZodTypeAny): JsonSchemaProperty {
const outerDescription = schema.description;
if (schema instanceof z.ZodEffects) {
return withDescription(convertZodType(schema._def.schema), outerDescription);
}
if (schema instanceof z.ZodOptional) {
return withDescription(convertZodType(schema.unwrap()), outerDescription);
}
if (schema instanceof z.ZodDefault) {
const inner = convertZodType(schema._def.innerType);
const defaultValue: unknown = schema._def.defaultValue();
return withDescription({ ...inner, default: defaultValue }, outerDescription);
}
if (schema instanceof z.ZodNullable) {
const inner = convertZodType(schema.unwrap());
return withDescription({ anyOf: [inner, { type: 'null' }] }, outerDescription);
}
if (schema instanceof z.ZodString) {
let minLength: number | undefined;
let maxLength: number | undefined;
for (const check of schema._def.checks) {
if (check.kind === 'min') {
minLength = check.value;
} else if (check.kind === 'max') {
maxLength = check.value;
} else if (check.kind === 'length') {
minLength = check.value;
maxLength = check.value;
}
}
const result: {
type: 'string';
description?: string;
minLength?: number;
maxLength?: number;
} = { type: 'string' };
if (outerDescription !== undefined) {
result.description = outerDescription;
}
if (minLength !== undefined) {
result.minLength = minLength;
}
if (maxLength !== undefined) {
result.maxLength = maxLength;
}
return result;
}
if (schema instanceof z.ZodNumber) {
let isInt = false;
let minimum: number | undefined;
let maximum: number | undefined;
let exclusiveMinimum: number | undefined;
let exclusiveMaximum: number | undefined;
for (const check of schema._def.checks) {
if (check.kind === 'int') {
isInt = true;
} else if (check.kind === 'min') {
if (check.inclusive) {
minimum = check.value;
} else {
exclusiveMinimum = check.value;
}
} else if (check.kind === 'max') {
if (check.inclusive) {
maximum = check.value;
} else {
exclusiveMaximum = check.value;
}
}
}
const result: {
type: 'integer' | 'number';
description?: string;
minimum?: number;
maximum?: number;
exclusiveMinimum?: number;
exclusiveMaximum?: number;
} = { type: isInt ? 'integer' : 'number' };
if (outerDescription !== undefined) {
result.description = outerDescription;
}
if (minimum !== undefined) {
result.minimum = minimum;
}
if (maximum !== undefined) {
result.maximum = maximum;
}
if (exclusiveMinimum !== undefined) {
result.exclusiveMinimum = exclusiveMinimum;
}
if (exclusiveMaximum !== undefined) {
result.exclusiveMaximum = exclusiveMaximum;
}
return result;
}
if (schema instanceof z.ZodBoolean) {
return outerDescription !== undefined
? { type: 'boolean', description: outerDescription }
: { type: 'boolean' };
}
if (schema instanceof z.ZodEnum) {
const values = [...schema._def.values] as readonly string[];
return outerDescription !== undefined
? { type: 'string', enum: values, description: outerDescription }
: { type: 'string', enum: values };
}
if (schema instanceof z.ZodLiteral) {
const literalValue: unknown = schema._def.value;
if (
typeof literalValue === 'string' ||
typeof literalValue === 'number' ||
typeof literalValue === 'boolean' ||
literalValue === null
) {
const literalType: JsonSchemaProperty['type'] =
literalValue === null
? 'null'
: typeof literalValue === 'string'
? 'string'
: typeof literalValue === 'number'
? 'number'
: 'boolean';
return outerDescription !== undefined
? { type: literalType, const: literalValue, description: outerDescription }
: { type: literalType, const: literalValue };
}
throw new Error('Unsupported ZodLiteral value type in MCP tool input schema.');
}
if (schema instanceof z.ZodArray) {
const items = convertZodType(schema._def.type);
const result: {
type: 'array';
items: JsonSchemaProperty;
description?: string;
minItems?: number;
maxItems?: number;
} = { type: 'array', items };
if (outerDescription !== undefined) {
result.description = outerDescription;
}
if (schema._def.minLength !== null) {
result.minItems = schema._def.minLength.value;
}
if (schema._def.maxLength !== null) {
result.maxItems = schema._def.maxLength.value;
}
if (schema._def.exactLength !== null) {
result.minItems = schema._def.exactLength.value;
result.maxItems = schema._def.exactLength.value;
}
return result;
}
if (schema instanceof z.ZodUnion) {
const options = (schema._def.options as readonly z.ZodTypeAny[]).map(option =>
convertZodType(option)
);
return outerDescription !== undefined
? { anyOf: options, description: outerDescription }
: { anyOf: options };
}
if (schema instanceof z.ZodObject) {
return convertZodObject(schema, outerDescription);
}
const typeName =
typeof (schema._def as { typeName?: unknown }).typeName === 'string'
? (schema._def as { typeName: string }).typeName
: 'unknown';
throw new Error(`Unsupported Zod schema type "${typeName}" in MCP tool input schema.`);
}
function convertZodObject(
schema: z.ZodObject<z.ZodRawShape>,
outerDescription: string | undefined
): JsonSchemaObject {
const shape = schema.shape;
const properties: Record<string, JsonSchemaProperty> = {};
const required: string[] = [];
for (const [key, fieldSchema] of Object.entries(shape)) {
properties[key] = convertZodType(fieldSchema);
if (!isOptionalSchema(fieldSchema)) {
required.push(key);
}
}
const description = outerDescription ?? schema.description;
const result: {
type: 'object';
properties: Record<string, JsonSchemaProperty>;
required?: string[];
additionalProperties: false;
description?: string;
} = {
type: 'object',
properties,
additionalProperties: false,
};
if (required.length > 0) {
result.required = required;
}
if (description !== undefined) {
result.description = description;
}
return result;
}
/**
* Converts a Zod v3 object schema (including `.refine()` / `.superRefine()`
* `ZodEffects` wrappers) into a strict {@link JsonSchemaObject}.
*
* Fails fast on unsupported Zod schema types so misconfigured tools are caught
* at registration time rather than at `tools/list` time.
*/
export function zodObjectToJsonSchema(schema: z.ZodTypeAny): JsonSchemaObject {
let current: z.ZodTypeAny = schema;
let description = schema.description;
while (current instanceof z.ZodEffects) {
current = current._def.schema;
if (description === undefined && current.description !== undefined) {
description = current.description;
}
}
if (!(current instanceof z.ZodObject)) {
throw new Error('MCP tool inputSchema must be a ZodObject (optionally wrapped in ZodEffects).');
}
return convertZodObject(current, description);
}
function formatZodIssues(error: z.ZodError): string {
const parts = error.issues.map(issue => {
const path = issue.path.length > 0 ? `${issue.path.join('.')}: ` : '';
return `${path}${issue.message}`;
});
return parts.join('; ');
}
const SAFE_ERROR_NAME_RE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
function sanitizeToolError(err: unknown): string {
if (err instanceof Error) {
const rawName = typeof err.name === 'string' ? err.name.trim() : '';
const safeName = SAFE_ERROR_NAME_RE.test(rawName) ? rawName : 'Error';
return `${safeName}: Tool execution failed.`;
}
return 'Error: Tool execution failed.';
}
/**
* Defines a type-erased MCP tool entry with eager JSON Schema generation,
* strict argument validation, and sanitized error handling.
*/
export function defineMcpTool<TInput>(definition: McpToolDefinition<TInput>): McpToolEntry {
if (typeof definition.name !== 'string' || definition.name.trim().length === 0) {
throw new Error('MCP tool name must be a non-empty string.');
}
if (typeof definition.description !== 'string' || definition.description.trim().length === 0) {
throw new Error(`MCP tool "${definition.name}" description must be a non-empty string.`);
}
const resolvedSchema: JsonSchemaObject =
definition.jsonSchema ?? zodObjectToJsonSchema(definition.inputSchema);
return {
name: definition.name,
description: definition.description,
inputSchema: resolvedSchema,
async execute(rawArguments: Record<string, unknown>): Promise<McpToolCallResult> {
const parsed = definition.inputSchema.safeParse(rawArguments);
if (!parsed.success) {
return {
content: [
{
type: 'text',
text: `Invalid arguments for tool "${definition.name}": ${formatZodIssues(parsed.error)}`,
},
],
isError: true,
};
}
try {
return await definition.handler(parsed.data);
} catch (err: unknown) {
return {
content: [
{
type: 'text',
text: sanitizeToolError(err),
},
],
isError: true,
};
}
},
};
}
/**
* Creates a transport-agnostic MCP JSON-RPC 2.0 server with a validated tool
* registry.
*/
export function createMcpServer(options: McpServerOptions): McpServer {
if (typeof options.name !== 'string' || options.name.trim().length === 0) {
throw new Error('MCP server name must be a non-empty string.');
}
if (typeof options.version !== 'string' || options.version.trim().length === 0) {
throw new Error('MCP server version must be a non-empty string.');
}
const toolMap = new Map<string, McpToolEntry>();
const toolDescriptors: McpToolDescriptor[] = [];
for (const tool of options.tools ?? []) {
if (toolMap.has(tool.name)) {
throw new Error(`Duplicate MCP tool name: "${tool.name}".`);
}
toolMap.set(tool.name, tool);
toolDescriptors.push({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
});
}
const frozenDescriptors: readonly McpToolDescriptor[] = Object.freeze([...toolDescriptors]);
return {
name: options.name,
version: options.version,
listTools(): readonly McpToolDescriptor[] {
return frozenDescriptors;
},
async handleMessage(raw: string): Promise<string | null> {
const parsed = parseJsonRpcMessage(raw);
if (!parsed.ok) {
return JSON.stringify(jsonRpcError(null, parsed.errorCode, parsed.message));
}
if (parsed.kind === 'notification') {
return null;
}
const { id, method, params } = parsed.message;
switch (method) {
case 'initialize': {
if (params !== undefined) {
const initParams = mcpInitializeParamsSchema.safeParse(params);
if (!initParams.success) {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.INVALID_PARAMS,
`Invalid params for initialize: ${formatZodIssues(initParams.error)}`
)
);
}
}
return JSON.stringify(
jsonRpcSuccess(id, {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {
tools: {},
},
serverInfo: {
name: options.name,
version: options.version,
},
})
);
}
case 'ping': {
if (params !== undefined) {
const pingParams = mcpPingParamsSchema.safeParse(params);
if (!pingParams.success) {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.INVALID_PARAMS,
`Invalid params for ping: ${formatZodIssues(pingParams.error)}`
)
);
}
}
return JSON.stringify(jsonRpcSuccess(id, {}));
}
case 'tools/list': {
if (params !== undefined) {
const listParams = mcpToolsListParamsSchema.safeParse(params);
if (!listParams.success) {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.INVALID_PARAMS,
`Invalid params for tools/list: ${formatZodIssues(listParams.error)}`
)
);
}
}
return JSON.stringify(
jsonRpcSuccess(id, {
tools: frozenDescriptors,
})
);
}
case 'tools/call': {
const callParams = mcpToolsCallParamsSchema.safeParse(params);
if (!callParams.success) {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.INVALID_PARAMS,
`Invalid params for tools/call: ${formatZodIssues(callParams.error)}`
)
);
}
const tool = toolMap.get(callParams.data.name);
if (tool === undefined) {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.INVALID_PARAMS,
`Unknown tool: "${callParams.data.name}".`
)
);
}
const result = await tool.execute(callParams.data.arguments ?? {});
return JSON.stringify(jsonRpcSuccess(id, result));
}
default: {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.METHOD_NOT_FOUND,
`Method not found: "${method}".`
)
);
}
}
},
};
}

View file

@ -1,147 +0,0 @@
import { JSON_RPC_ERROR_CODES, jsonRpcError } from './protocol';
import type { McpServer } from './server';
/** Default maximum allowed line frame size in UTF-8 bytes (4 MiB). */
export const DEFAULT_STDIO_MAX_LINE_BYTES = 4 * 1024 * 1024;
/** Readable byte/string stream accepted by {@link runStdioServer}. */
export type StdioInput = AsyncIterable<Uint8Array | string>;
/** Minimal writable stream interface accepted by {@link runStdioServer}. */
export interface StdioOutput {
write(chunk: string): boolean;
once?(event: 'drain', listener: () => void): unknown;
}
/** Options for {@link runStdioServer}. */
export interface StdioServerOptions {
readonly input?: StdioInput;
readonly output?: StdioOutput;
readonly maxLineBytes?: number;
}
async function writeLine(output: StdioOutput, line: string): Promise<void> {
const ok = output.write(`${line}\n`);
if (!ok && typeof output.once === 'function') {
await new Promise<void>(resolve => {
output.once?.('drain', () => {
resolve();
});
});
}
}
/**
* Runs a newline-delimited JSON-RPC 2.0 stdio transport loop for an
* {@link McpServer}.
*
* - Decodes binary chunks with streaming UTF-8 (`TextDecoder`) so multi-byte
* characters split across chunk boundaries are never corrupted.
* - Dispatches lines strictly sequentially in arrival order.
* - Writes only compact newline-terminated JSON-RPC responses to `output`
* (skipping `null` notification results and blank lines).
* - Guards against oversized unterminated frames via `maxLineBytes`.
*/
export async function runStdioServer(
server: McpServer,
options?: StdioServerOptions
): Promise<void> {
const input: StdioInput = options?.input ?? process.stdin;
const output: StdioOutput = options?.output ?? process.stdout;
const maxLineBytes = options?.maxLineBytes ?? DEFAULT_STDIO_MAX_LINE_BYTES;
if (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1) {
throw new Error(`Invalid maxLineBytes (${String(maxLineBytes)}): expected a positive integer.`);
}
const decoder = new TextDecoder('utf-8');
const encoder = new TextEncoder();
let buffer = '';
let droppingOversizedLine = false;
const processLine = async (rawLine: string): Promise<void> => {
const trimmed = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
if (trimmed.trim().length === 0) {
return;
}
const response = await server.handleMessage(trimmed);
if (response !== null) {
await writeLine(output, response);
}
};
const emitOversizedError = async (): Promise<void> => {
const errorPayload = JSON.stringify(
jsonRpcError(
null,
JSON_RPC_ERROR_CODES.PARSE_ERROR,
`Parse error: message exceeds maximum frame size of ${maxLineBytes} bytes.`
)
);
await writeLine(output, errorPayload);
};
const drainBuffer = async (): Promise<void> => {
while (true) {
const newlineIdx = buffer.indexOf('\n');
if (newlineIdx === -1) {
if (!droppingOversizedLine && encoder.encode(buffer).byteLength > maxLineBytes) {
droppingOversizedLine = true;
buffer = '';
await emitOversizedError();
}
return;
}
const rawLine = buffer.slice(0, newlineIdx);
buffer = buffer.slice(newlineIdx + 1);
if (droppingOversizedLine) {
droppingOversizedLine = false;
continue;
}
if (encoder.encode(rawLine).byteLength > maxLineBytes) {
await emitOversizedError();
continue;
}
await processLine(rawLine);
}
};
for await (const chunk of input) {
const text = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
if (text.length === 0) {
continue;
}
if (droppingOversizedLine) {
const newlineIdx = text.indexOf('\n');
if (newlineIdx === -1) {
continue;
}
droppingOversizedLine = false;
buffer = text.slice(newlineIdx + 1);
} else {
buffer += text;
}
await drainBuffer();
}
const tail = decoder.decode();
if (tail.length > 0 && !droppingOversizedLine) {
buffer += tail;
}
await drainBuffer();
if (!droppingOversizedLine && buffer.length > 0) {
if (encoder.encode(buffer).byteLength > maxLineBytes) {
await emitOversizedError();
} else {
await processLine(buffer);
}
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,416 +0,0 @@
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

@ -1,249 +0,0 @@
import { z } from 'zod';
import {
type BarRecord,
type MarketDataStore,
MarketDataStoreValidationError,
type VaultFenceContext,
} from '../../market-data-store';
import type { McpToolCallResult } from '../protocol';
import { type McpToolEntry, defineMcpTool } from '../server';
import {
EXCLUSIVE_LISTING_SELECTOR_MESSAGE,
MCP_MAX_LISTING_IDS,
createListingIdsFieldSchema,
createUniverseFieldSchema,
fenceVaultQueryBounds,
formatMappedStoreError,
hasExclusiveListingSelector,
resolveUniverseDate,
validateVaultCutoffTs,
} from './vault-fenced-input';
/** Default maximum number of bar rows returned by `query_data`. */
export const QUERY_DATA_DEFAULT_LIMIT = 500;
/** Hard maximum number of bar rows returned by `query_data`. */
export const QUERY_DATA_MAX_LIMIT = 5_000;
/** Hard maximum number of explicit `listingIds` accepted by `query_data`. */
export const QUERY_DATA_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS;
/**
* Strict Zod input schema for the `query_data` MCP tool.
*
* Intentionally omits `scope` and `vault_evaluation_only`; `.strict()` rejects
* any caller attempt to supply them or any other unknown key.
*/
export const queryDataInputSchema = z
.object({
listingIds: createListingIdsFieldSchema(
'Explicit INT32 listing IDs to query (mutually exclusive with universe).'
),
universe: createUniverseFieldSchema(
'Universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).'
),
from: z
.string()
.min(1)
.describe('Inclusive start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.'),
to: z
.string()
.min(1)
.describe('Inclusive end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.'),
timeframe: z
.enum(['1m', '5m', '1h', '1d'])
.default('1d')
.describe('Bar timeframe (default 1d).'),
adjustment: z
.enum(['raw', 'split', 'total'])
.default('raw')
.describe('Price/volume adjustment mode (default raw).'),
asOf: z
.string()
.min(1)
.optional()
.describe('Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.'),
limit: z
.number()
.int()
.min(1)
.max(QUERY_DATA_MAX_LIMIT)
.default(QUERY_DATA_DEFAULT_LIMIT)
.describe(
`Maximum number of bar rows to return (default ${QUERY_DATA_DEFAULT_LIMIT}, max ${QUERY_DATA_MAX_LIMIT}).`
),
})
.strict()
.refine(hasExclusiveListingSelector, EXCLUSIVE_LISTING_SELECTOR_MESSAGE);
export type QueryDataInput = z.infer<typeof queryDataInputSchema>;
/** Configuration for {@link createQueryDataTool}. */
export interface QueryDataToolOptions {
readonly store: MarketDataStore;
readonly vaultContext: Pick<VaultFenceContext, 'vaultCutoffTs'>;
}
/** Structured JSON payload serialized into the `query_data` MCP text result. */
export interface QueryDataResultPayload {
readonly scope: 'vault_fenced';
readonly vaultCutoffTs: number;
readonly timeframe: '1m' | '5m' | '1h' | '1d';
readonly adjustment: 'raw' | 'split' | 'total';
readonly fromMs: number;
readonly toMs: number;
readonly asOfMs: number;
readonly clampedTo: boolean;
readonly clampedAsOf: boolean;
readonly limit: number;
readonly rowCount: number;
readonly truncated: boolean;
readonly rows: readonly BarRecord[];
}
function validateFactoryOptions(options: QueryDataToolOptions): number {
if (
typeof options.store !== 'object' ||
options.store === null ||
typeof options.store.bars !== 'function' ||
typeof options.store.universe !== 'function'
) {
throw new MarketDataStoreValidationError(
'Invalid `store`: expected a MarketDataStore implementing `bars` and `universe`.',
'store'
);
}
return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs);
}
/**
* Creates the Vault-fenced `query_data` MCP tool backed by an injected
* {@link MarketDataStore}.
*
* Always enforces `scope: 'vault_fenced'`, runs {@link applyVaultFence} before
* any store call, drops any post-cutoff row yielded by a store as defense in
* depth, and bounds output rows by `limit` (default {@link QUERY_DATA_DEFAULT_LIMIT},
* hard max {@link QUERY_DATA_MAX_LIMIT}).
*/
export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry {
const vaultCutoffTs = validateFactoryOptions(options);
const { store } = options;
return defineMcpTool({
name: 'query_data',
description:
'Query Vault-fenced OHLCV market bars for explicit listing IDs or a survivorship-free universe.',
inputSchema: queryDataInputSchema,
async handler(input: QueryDataInput): Promise<McpToolCallResult> {
try {
const fenced = fenceVaultQueryBounds(
{
from: input.from,
to: input.to,
asOf: input.asOf,
},
vaultCutoffTs
);
const effectiveLimit = input.limit;
let listingIds: number[];
if (input.universe !== undefined) {
const universeDate = resolveUniverseDate(
fenced.toMs,
fenced.toSubMs,
fenced.asOfMs,
fenced.asOfSubMs
);
const resolved = await store.universe({
ref: input.universe,
date: universeDate,
});
if (resolved.length === 0) {
const emptyPayload: QueryDataResultPayload = {
scope: 'vault_fenced',
vaultCutoffTs,
timeframe: input.timeframe,
adjustment: input.adjustment,
fromMs: fenced.fromMs,
toMs: fenced.toMs,
asOfMs: fenced.asOfMs,
clampedTo: fenced.clampedTo,
clampedAsOf: fenced.clampedAsOf,
limit: effectiveLimit,
rowCount: 0,
truncated: false,
rows: [],
};
return {
content: [{ type: 'text', text: JSON.stringify(emptyPayload) }],
};
}
listingIds = [...resolved];
} else {
listingIds = [...(input.listingIds ?? [])];
}
const stream = store.bars({
listingIds,
timeframe: input.timeframe,
from: input.from,
to: fenced.effectiveFencedTo,
adjustment: input.adjustment,
asOf: fenced.effectiveFencedAsOf,
scope: 'vault_fenced',
});
const rows: BarRecord[] = [];
let truncated = false;
outer: for await (const batch of stream) {
for (const row of batch.rows) {
if (
!Number.isFinite(row.ts) ||
!Number.isFinite(row.knownAt) ||
row.ts >= vaultCutoffTs ||
row.knownAt >= vaultCutoffTs
) {
continue;
}
if (rows.length >= effectiveLimit) {
truncated = true;
break outer;
}
rows.push(row);
}
}
const payload: QueryDataResultPayload = {
scope: 'vault_fenced',
vaultCutoffTs,
timeframe: input.timeframe,
adjustment: input.adjustment,
fromMs: fenced.fromMs,
toMs: fenced.toMs,
asOfMs: fenced.asOfMs,
clampedTo: fenced.clampedTo,
clampedAsOf: fenced.clampedAsOf,
limit: effectiveLimit,
rowCount: rows.length,
truncated,
rows,
};
return {
content: [{ type: 'text', text: JSON.stringify(payload) }],
};
} catch (err: unknown) {
const mapped = formatMappedStoreError(err);
if (mapped !== null) {
return mapped;
}
throw err;
}
},
});
}

View file

@ -1,588 +0,0 @@
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

@ -1,359 +0,0 @@
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) }],
};
},
});
}

View file

@ -1,341 +0,0 @@
import { z } from 'zod';
import {
type FencedTimeRange,
MarketDataStoreValidationError,
VaultHoldoutFenceError,
VaultScopeNotAuthorizedError,
applyVaultFence,
} from '../../market-data-store';
import {
AdjFactorsSnapshotError,
type AdjFactorsSnapshotErrorCode,
MarketDataStoreNotImplementedError,
} from '../../market-data-store-duckdb';
import type { McpToolCallResult } from '../protocol';
export const INT32_MIN = -2_147_483_648;
export const INT32_MAX = 2_147_483_647;
export const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
export const MS_PER_DAY = 86_400_000;
/** Hard maximum number of explicit `listingIds` accepted by Vault-fenced MCP tools. */
export const MCP_MAX_LISTING_IDS = 500;
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/;
export const EXCLUSIVE_LISTING_SELECTOR_MESSAGE =
'Exactly one of "listingIds" or "universe" must be provided.';
/** Returns true when exactly one of `listingIds` or `universe` is supplied. */
export function hasExclusiveListingSelector(data: {
readonly listingIds?: readonly number[];
readonly universe?: string;
}): boolean {
return (data.listingIds !== undefined) !== (data.universe !== undefined);
}
/** Shared Zod field schema for explicit INT32 `listingIds` (1–500). */
export function createListingIdsFieldSchema(description: string) {
return z
.array(z.number().int().min(INT32_MIN).max(INT32_MAX))
.min(1)
.max(MCP_MAX_LISTING_IDS)
.optional()
.describe(description);
}
/** Shared Zod field schema for a named `universe` reference. */
export function createUniverseFieldSchema(description: string) {
return z.string().min(1).optional().describe(description);
}
/**
* Validates that a raw string is a valid calendar date (`YYYY-MM-DD`) or
* UTC ISO-8601 timestamp with an explicit timezone offset (`Z` or `±HH:MM`).
*/
export function isValidUtcBoundString(raw: string): boolean {
try {
applyVaultFence(
{ from: raw, to: raw, scope: 'vault_evaluation_only' },
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
);
return true;
} catch {
return false;
}
}
/** Validates an injected server-side `vaultCutoffTs` epoch-ms boundary. */
export function validateVaultCutoffTs(cutoffTs: unknown): number {
if (
typeof cutoffTs !== 'number' ||
!Number.isFinite(cutoffTs) ||
!Number.isSafeInteger(cutoffTs) ||
Math.abs(cutoffTs) >= MAX_ECMASCRIPT_EPOCH_MS
) {
throw new MarketDataStoreValidationError(
`Invalid \`vaultContext.vaultCutoffTs\`: ${String(cutoffTs)}.`,
'vaultCutoffTs'
);
}
return cutoffTs;
}
/** Returns the UTC calendar date (`YYYY-MM-DD`) for an epoch-ms timestamp. */
export function utcDateOf(epochMs: number): string {
return new Date(epochMs).toISOString().slice(0, 10);
}
export function extractExplicitSubMsMicros(raw: string): number {
const match = ISO_FRACTIONAL_RE.exec(raw);
if (match === null) {
return 0;
}
const frac = match[1] ?? '';
if (frac.length <= 3) {
return 0;
}
const microDigits = frac.slice(3, 6).padEnd(3, '0');
return Number(microDigits);
}
export function resolveFromSubMsMicros(rawFrom: string): number {
if (DATE_ONLY_RE.test(rawFrom)) {
return 0;
}
return extractExplicitSubMsMicros(rawFrom);
}
export function resolveToSubMsMicros(rawTo: string, clampedTo: boolean): number {
if (clampedTo || DATE_ONLY_RE.test(rawTo)) {
return 999;
}
return extractExplicitSubMsMicros(rawTo);
}
export function resolveAsOfSubMsMicros(rawAsOf: string | undefined, clampedAsOf: boolean): number {
if (clampedAsOf || rawAsOf === undefined || DATE_ONLY_RE.test(rawAsOf)) {
return 999;
}
return extractExplicitSubMsMicros(rawAsOf);
}
export function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string {
const isoMs = new Date(epochMs).toISOString();
if (subMsMicros === 0) {
return isoMs;
}
const extra = String(subMsMicros).padStart(3, '0');
return `${isoMs.slice(0, -1)}${extra}Z`;
}
/**
* Resolves the latest completed UTC calendar date at or before `(epochMs, subMsMicros)`.
* A full day is completed only at `23:59:59.999999Z`; any earlier instant resolves
* to the preceding UTC calendar date.
*/
export function resolveCompletedUtcDate(epochMs: number, subMsMicros: number): string {
const dayStartMs = Math.floor(epochMs / MS_PER_DAY) * MS_PER_DAY;
const dayEndMs = dayStartMs + MS_PER_DAY - 1;
if (epochMs === dayEndMs && subMsMicros === 999) {
return utcDateOf(dayStartMs);
}
return utcDateOf(dayStartMs - MS_PER_DAY);
}
/**
* Resolves the completed UTC date at `min(effectiveTo, effectiveAsOf)` for point-in-time
* universe resolution in `query_data`.
*/
export function resolveUniverseDate(
toMs: number,
toSubMs: number,
asOfMs: number,
asOfSubMs: number
): string {
if (asOfMs < toMs || (asOfMs === toMs && asOfSubMs < toSubMs)) {
return resolveCompletedUtcDate(asOfMs, asOfSubMs);
}
return resolveCompletedUtcDate(toMs, toSubMs);
}
/**
* Resolves a fixed pre-study cohort date: the latest completed UTC date strictly
* before the study start (`fromMs`) and no later than effective `asOf`.
*/
export function resolvePreStartUniverseDate(
fromMs: number,
asOfMs: number,
asOfSubMs: number
): string {
const fromDayStartMs = Math.floor(fromMs / MS_PER_DAY) * MS_PER_DAY;
const preStartDate = utcDateOf(fromDayStartMs - MS_PER_DAY);
const asOfCompletedDate = resolveCompletedUtcDate(asOfMs, asOfSubMs);
return asOfCompletedDate < preStartDate ? asOfCompletedDate : preStartDate;
}
/** Result of fencing MCP query bounds against the server-injected Vault cutoff. */
export interface VaultFencedBounds extends FencedTimeRange {
readonly vaultCutoffDate: string;
readonly fromSubMs: number;
readonly toSubMs: number;
readonly asOfSubMs: number;
readonly canonicalFrom: string;
readonly canonicalTo: string;
readonly canonicalAsOf: string;
readonly effectiveFencedTo: string;
readonly effectiveFencedAsOf: string;
}
/**
* Runs {@link applyVaultFence} under `scope: 'vault_fenced'` with
* `vaultOperatorAuthorized: false` and computes microsecond-preserving effective
* `to` / `asOf` query strings.
*/
export function fenceVaultQueryBounds(
input: { readonly from: string; readonly to: string; readonly asOf?: string },
vaultCutoffTs: number
): VaultFencedBounds {
const fenced = applyVaultFence(
{
from: input.from,
to: input.to,
asOf: input.asOf,
scope: 'vault_fenced',
},
{
vaultCutoffTs,
vaultOperatorAuthorized: false,
}
);
const fromSubMs = resolveFromSubMsMicros(input.from);
const toSubMs = resolveToSubMsMicros(input.to, fenced.clampedTo);
const asOfSubMs = resolveAsOfSubMsMicros(input.asOf, fenced.clampedAsOf);
const canonicalFrom = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs);
const canonicalTo = formatUtcIsoWithMicros(fenced.toMs, toSubMs);
const canonicalAsOf = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs);
const effectiveFencedTo = fenced.clampedTo
? formatUtcIsoWithMicros(fenced.toMs, 999)
: input.to;
const effectiveFencedAsOf =
fenced.clampedAsOf || input.asOf === undefined
? formatUtcIsoWithMicros(fenced.asOfMs, 999)
: input.asOf;
return {
...fenced,
vaultCutoffDate: utcDateOf(vaultCutoffTs),
fromSubMs,
toSubMs,
asOfSubMs,
canonicalFrom,
canonicalTo,
canonicalAsOf,
effectiveFencedTo,
effectiveFencedAsOf,
};
}
const SAFE_VALIDATION_FIELDS: ReadonlySet<string> = new Set([
'from',
'to',
'asOf',
'date',
'ref',
'listingIds',
'timeframe',
'adjustment',
'scope',
'limit',
]);
const SAFE_STORE_METHODS: ReadonlySet<string> = new Set([
'bars',
'crossSection',
'fundamentalsAsOf',
'events',
'shortsAsOf',
'macroAsOf',
'fx',
'universe',
]);
const ADJ_SNAPSHOT_ERROR_MESSAGES: Readonly<Record<AdjFactorsSnapshotErrorCode, string>> = {
missing_snapshot:
'Adjusted bars require a verified point-in-time fenced adj_factors snapshot.',
missing_metadata: 'Required adj_factors snapshot metadata is missing.',
invalid_metadata: 'adj_factors snapshot metadata is invalid.',
unsupported_version: 'adj_factors snapshot metadata version is unsupported.',
retrospective_rejected:
'Retrospective adj_factors snapshots are rejected for point-in-time queries.',
incompatible_fence:
'adj_factors snapshot fence does not match the query asOf or Vault cutoff.',
path_mismatch: 'adj_factors snapshot metadata does not match the configured artifact.',
unpinned_mutable_path:
'Adjusted bars require a pinned or immutable adj_factors snapshot artifact.',
};
/**
* Maps known `MarketDataStore` / Vault domain errors to fixed, sanitized
* `isError: true` MCP tool results without leaking SQL, file paths, or URIs.
*/
export function formatMappedStoreError(err: unknown): McpToolCallResult | null {
if (err instanceof VaultHoldoutFenceError) {
return {
content: [
{
type: 'text',
text: 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.',
},
],
isError: true,
};
}
if (err instanceof VaultScopeNotAuthorizedError) {
return {
content: [
{
type: 'text',
text: "VaultScopeNotAuthorizedError: Data scope 'vault_evaluation_only' is not permitted through MCP.",
},
],
isError: true,
};
}
if (err instanceof MarketDataStoreValidationError) {
const text =
err.field !== undefined && SAFE_VALIDATION_FIELDS.has(err.field)
? `MarketDataStoreValidationError: Invalid query parameter "${err.field}".`
: 'MarketDataStoreValidationError: Query parameters failed store validation.';
return {
content: [{ type: 'text', text }],
isError: true,
};
}
if (err instanceof MarketDataStoreNotImplementedError) {
const text = SAFE_STORE_METHODS.has(err.method)
? `MarketDataStoreNotImplementedError: Store operation "${err.method}" is not supported for this query.`
: 'MarketDataStoreNotImplementedError: Requested store operation is not supported.';
return {
content: [{ type: 'text', text }],
isError: true,
};
}
if (err instanceof AdjFactorsSnapshotError) {
const detail = Object.prototype.hasOwnProperty.call(ADJ_SNAPSHOT_ERROR_MESSAGES, err.code)
? ADJ_SNAPSHOT_ERROR_MESSAGES[err.code]
: 'Adjusted bars snapshot verification failed.';
return {
content: [{ type: 'text', text: `AdjFactorsSnapshotError: ${detail}` }],
isError: true,
};
}
return null;
}

View file

@ -1,293 +0,0 @@
/**
* Node/Bun subprocess and filesystem adapters for {@link exportNotebookSnapshot}.
*
* Intentionally exposed only via the `@stock-bot/research/notebook-snapshot-node`
* subpath (never re-exported from `@stock-bot/research`) so the root package
* stays browser-bundleable.
*/
import { spawn } from 'node:child_process';
import { rename as fsRename, stat as fsStat, open, readFile, rm } from 'node:fs/promises';
import { basename } from 'node:path';
import type {
NotebookCommandResult,
NotebookCommandRunner,
NotebookCommandRunOptions,
NotebookSnapshotFileStat,
NotebookSnapshotFs,
} from './notebook-snapshot';
/** Default per-stream (stdout / stderr) capture cap in bytes (16 MiB). */
export const NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
/** Maximum single-call delay supported by Node/Bun `setTimeout` (2^31 - 1 ms). */
const MAX_TIMER_DELAY_MS = 2_147_483_647;
export interface NodeNotebookCommandRunnerOptions {
/** Maximum captured bytes per stream (stdout and stderr independently). */
readonly maxOutputBytes?: number;
}
interface CodedError extends Error {
code: string;
}
function createCodedError(code: string, message: string): CodedError {
const err = new Error(message) as CodedError;
err.code = code;
return err;
}
function getErrorCode(err: unknown): string | undefined {
if (typeof err === 'object' && err !== null && 'code' in err) {
const code = (err as { code?: unknown }).code;
if (typeof code === 'string') {
return code;
}
}
return undefined;
}
function assertPositiveSafeInteger(value: unknown, label: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
throw new RangeError(`${label} must be a positive finite integer.`);
}
return value;
}
/**
* Creates a real {@link NotebookCommandRunner} backed by `node:child_process.spawn`.
*
* - Always invokes `command` directly with `args` as argv (`shell: false`).
* - Resolves any numeric exit code on `close`; rejects on spawn errors, signal
* termination, timeout (`ETIMEDOUT`), or per-stream output overflow (`EOUTPUTLIMIT`).
* - On timeout or output overflow, sends `SIGKILL` once and rejects only after
* the child's `close` event has fired.
*/
export function createNodeNotebookCommandRunner(
runnerOptions?: NodeNotebookCommandRunnerOptions
): NotebookCommandRunner {
const maxOutputBytes =
runnerOptions?.maxOutputBytes === undefined
? NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES
: assertPositiveSafeInteger(runnerOptions.maxOutputBytes, 'maxOutputBytes');
return {
run(
command: string,
args: readonly string[],
options: NotebookCommandRunOptions
): Promise<NotebookCommandResult> {
let timeoutMs: number;
try {
timeoutMs = assertPositiveSafeInteger(options.timeoutMs, 'timeoutMs');
} catch (err) {
return Promise.reject(err);
}
const commandName = basename(command) || command;
return new Promise<NotebookCommandResult>((resolve, reject) => {
let settled = false;
let terminalFailure: CodedError | null = null;
let killSent = false;
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
const stdoutChunks: Buffer[] = [];
let stdoutBytes = 0;
const stderrChunks: Buffer[] = [];
let stderrBytes = 0;
const clearTimeoutHandle = (): void => {
if (timeoutHandle !== undefined) {
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
};
let child: ReturnType<typeof spawn>;
try {
child = spawn(command, [...args], {
...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
shell: false,
stdio: ['ignore', 'pipe', 'pipe'],
});
} catch (err) {
settled = true;
reject(err);
return;
}
const triggerTerminalFailure = (err: CodedError): void => {
if (settled || terminalFailure !== null) {
return;
}
terminalFailure = err;
clearTimeoutHandle();
stdoutChunks.length = 0;
stderrChunks.length = 0;
if (!killSent) {
killSent = true;
try {
child.kill('SIGKILL');
} catch {
// Child may have already exited before kill was delivered.
}
}
// Tear down our read ends of stdout/stderr so a descendant that
// inherited either pipe cannot prevent `child`'s `close` event from
// firing once the direct child exits.
child.stdout?.destroy();
child.stderr?.destroy();
};
const attachStreamCollector = (
stream: NodeJS.ReadableStream | null,
streamName: 'stdout' | 'stderr',
chunks: Buffer[],
getBytes: () => number,
setBytes: (next: number) => void
): void => {
if (!stream) {
return;
}
stream.on('error', () => {
// Drain/ignore pipe errors once the child is terminating.
});
stream.on('data', (chunk: Buffer | string) => {
if (terminalFailure !== null || settled) {
// Keep draining so a killed/exiting child never blocks on a full pipe.
return;
}
const buf = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;
const nextBytes = getBytes() + buf.byteLength;
if (nextBytes > maxOutputBytes) {
triggerTerminalFailure(
createCodedError(
'EOUTPUTLIMIT',
`Command '${commandName}' exceeded ${streamName} output limit of ${maxOutputBytes} bytes.`
)
);
return;
}
setBytes(nextBytes);
chunks.push(buf);
});
};
attachStreamCollector(
child.stdout,
'stdout',
stdoutChunks,
() => stdoutBytes,
next => {
stdoutBytes = next;
}
);
attachStreamCollector(
child.stderr,
'stderr',
stderrChunks,
() => stderrBytes,
next => {
stderrBytes = next;
}
);
const deadlineMs = performance.now() + timeoutMs;
const scheduleTimeout = (): void => {
if (settled || terminalFailure !== null) {
return;
}
const remainingMs = deadlineMs - performance.now();
if (remainingMs <= 0) {
triggerTerminalFailure(
createCodedError(
'ETIMEDOUT',
`Command '${commandName}' timed out after ${timeoutMs}ms.`
)
);
return;
}
const delayMs = Math.min(Math.ceil(remainingMs), MAX_TIMER_DELAY_MS);
timeoutHandle = setTimeout(scheduleTimeout, delayMs);
};
scheduleTimeout();
child.once('error', err => {
clearTimeoutHandle();
if (settled) {
return;
}
settled = true;
reject(err);
});
child.once('close', (code, signal) => {
clearTimeoutHandle();
if (settled) {
return;
}
settled = true;
if (terminalFailure !== null) {
reject(terminalFailure);
return;
}
if (code === null) {
reject(
new Error(
signal
? `Command '${commandName}' terminated by signal ${signal}.`
: `Command '${commandName}' terminated without an exit code.`
)
);
return;
}
const stdout = Buffer.concat(stdoutChunks, stdoutBytes).toString('utf8');
const stderr = Buffer.concat(stderrChunks, stderrBytes).toString('utf8');
resolve({ exitCode: code, stdout, stderr });
});
});
},
};
}
/**
* Creates a real {@link NotebookSnapshotFs} backed by `node:fs/promises`.
*/
export function createNodeNotebookSnapshotFs(): NotebookSnapshotFs {
return {
async stat(path: string): Promise<NotebookSnapshotFileStat | null> {
try {
const info = await fsStat(path);
return { isFile: info.isFile(), size: info.size };
} catch (err) {
if (getErrorCode(err) === 'ENOENT') {
return null;
}
throw err;
}
},
async createExclusive(path: string): Promise<void> {
const handle = await open(path, 'wx');
await handle.close();
},
async readBytes(path: string): Promise<Uint8Array> {
const data = await readFile(path);
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
},
async rename(sourcePath: string, destinationPath: string): Promise<void> {
await fsRename(sourcePath, destinationPath);
},
async remove(path: string): Promise<void> {
await rm(path, { force: true });
},
};
}

View file

@ -1,804 +0,0 @@
/**
* `marimo check`-gated static HTML snapshot exporter for research notebooks.
*
* Enforces the D9 rule (`design/PLATFORM-PLAN.md`): a notebook must pass
* `marimo check --format=json` with zero errors before `marimo export html`
* runs, and exported HTML is published atomically via a sibling temp file.
*
* All subprocess execution and filesystem access are injected via ports
* (`NotebookCommandRunner`, `NotebookSnapshotFs`). `node:crypto` is loaded
* lazily at call time so `@stock-bot/research` remains browser-bundleable.
*
* Command flags and JSON diagnostic shape are confirmed against marimo 0.26.0
* (pinned in `python/uv.lock`).
*/
export const DEFAULT_MARIMO_COMMAND = 'marimo';
export const DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS = 120_000;
const MAX_TEMP_RESERVATION_ATTEMPTS = 16;
let tempSequence = 0;
/** Stable machine-readable error codes thrown by {@link NotebookSnapshotError}. */
export type NotebookSnapshotErrorCode =
| 'INVALID_OPTION'
| 'INVALID_PATH'
| 'NOTEBOOK_NOT_FOUND'
| 'CHECK_FAILED'
| 'CHECK_OUTPUT_INVALID'
| 'EXPORT_FAILED'
| 'EXPORT_EMPTY'
| 'TIMEOUT';
export interface NotebookSnapshotErrorOptions {
readonly details?: unknown;
readonly cause?: unknown;
}
/** Typed fail-closed error thrown by {@link exportNotebookSnapshot}. */
export class NotebookSnapshotError extends Error {
readonly code: NotebookSnapshotErrorCode;
readonly details?: unknown;
override readonly cause?: unknown;
constructor(
code: NotebookSnapshotErrorCode,
message: string,
options?: NotebookSnapshotErrorOptions
) {
super(message);
this.name = 'NotebookSnapshotError';
this.code = code;
if (options && 'details' in options) {
this.details = options.details;
}
if (options && 'cause' in options) {
this.cause = options.cause;
}
Object.setPrototypeOf(this, new.target.prototype);
}
}
export interface NotebookCommandRunOptions {
readonly cwd?: string;
readonly timeoutMs: number;
}
export interface NotebookCommandResult {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
}
/**
* Injected command-runner port.
*
* Implementations MUST execute `command` directly with `args` as an argv array
* (never via a shell string or shell interpolation).
*
* Timeout contract: on timeout, implementations MUST terminate the subprocess
* and settle (rejecting with an error carrying `code: 'ETIMEDOUT'`) only after
* the process has exited and stopped writing to disk.
*/
export interface NotebookCommandRunner {
run(
command: string,
args: readonly string[],
options: NotebookCommandRunOptions
): Promise<NotebookCommandResult>;
}
export interface NotebookSnapshotFileStat {
readonly isFile: boolean;
readonly size: number;
}
/**
* Minimal injected filesystem port for {@link exportNotebookSnapshot}.
*/
export interface NotebookSnapshotFs {
/** Returns file metadata for `path`, or `null` when `path` does not exist. */
stat(path: string): Promise<NotebookSnapshotFileStat | null>;
/**
* Exclusively creates an empty file at `path` (`O_CREAT | O_EXCL`).
* MUST throw an error carrying `code: 'EEXIST'` if `path` already exists.
*/
createExclusive(path: string): Promise<void>;
/** Reads the complete byte contents of `path`. */
readBytes(path: string): Promise<Uint8Array>;
/** Atomically replaces `destinationPath` with `sourcePath`. */
rename(sourcePath: string, destinationPath: string): Promise<void>;
/** Idempotently removes `path` (succeeds as a no-op if already absent). */
remove(path: string): Promise<void>;
}
/** Parsed marimo 0.26.0 `marimo check --format=json` summary object. */
export interface MarimoCheckSummary {
readonly errored: boolean;
readonly total_files: number;
readonly [key: string]: unknown;
}
/** Parsed marimo 0.26.0 `marimo check --format=json` report object. */
export interface MarimoCheckReport {
readonly issues: readonly Readonly<Record<string, unknown>>[];
readonly summary: MarimoCheckSummary;
readonly [key: string]: unknown;
}
export interface ExportNotebookSnapshotOptions {
readonly notebookPath: string;
readonly outputPath: string;
readonly runner: NotebookCommandRunner;
readonly fs: NotebookSnapshotFs;
/** Executable name or path for marimo (default `'marimo'`). */
readonly marimoCommand?: string;
/** Per-command timeout in milliseconds (default `120_000`). */
readonly timeoutMs?: number;
/** Optional working directory passed to `runner.run`. */
readonly cwd?: string;
/** Optional absolute root directory that `notebookPath` must lexically reside within. */
readonly allowedNotebookRoot?: string;
/** Optional absolute root directory that `outputPath` must lexically reside within. */
readonly allowedOutputRoot?: string;
}
/** Frozen receipt returned when a notebook snapshot is cleanly checked and published. */
export interface NotebookSnapshotReceipt {
readonly notebookPath: string;
readonly outputPath: string;
readonly bytes: number;
readonly sha256: string;
readonly checkDiagnostics: MarimoCheckReport | null;
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function getErrorCode(err: unknown): string | undefined {
if (typeof err === 'object' && err !== null && 'code' in err) {
const code = (err as { code?: unknown }).code;
if (typeof code === 'string') {
return code;
}
}
return undefined;
}
function normalizePosixAbsolutePath(rawPath: string): string {
const segments = rawPath.split('/');
const stack: string[] = [];
for (let i = 0; i < segments.length; i += 1) {
const seg = segments[i];
if (seg === undefined || seg === '' || seg === '.') {
continue;
}
if (seg === '..') {
if (stack.length > 0) {
stack.pop();
}
continue;
}
stack.push(seg);
}
return `/${stack.join('/')}`;
}
function validateAbsolutePath(
rawPath: unknown,
label: string,
options?: { readonly requiredExtension?: string }
): string {
if (typeof rawPath !== 'string' || rawPath.length === 0) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${label}: expected a non-empty string.`
);
}
if (rawPath.includes('\0')) {
throw new NotebookSnapshotError('INVALID_PATH', `Invalid ${label}: NUL bytes are not allowed.`);
}
if (rawPath.startsWith('-')) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${label}: path must not start with '-'.`
);
}
if (!rawPath.startsWith('/')) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${label}: path must be an absolute POSIX path.`
);
}
if (options?.requiredExtension !== undefined) {
if (rawPath.endsWith('/')) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${label}: path must reference a ${options.requiredExtension} file, not a directory.`
);
}
}
const normalized = normalizePosixAbsolutePath(rawPath);
if (options?.requiredExtension !== undefined) {
const ext = options.requiredExtension;
if (!normalized.endsWith(ext) || normalized === `/${ext}` || normalized.endsWith(`/${ext}`)) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${label}: path must end with '${ext}'.`
);
}
}
return normalized;
}
function assertWithinRoot(
normalizedPath: string,
rawRoot: unknown,
pathLabel: string,
rootLabel: string
): void {
const normalizedRoot = validateAbsolutePath(rawRoot, rootLabel);
if (normalizedRoot === '/') {
return;
}
const requiredPrefix = `${normalizedRoot}/`;
if (!normalizedPath.startsWith(requiredPrefix)) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${pathLabel}: resolved path '${normalizedPath}' escapes ${rootLabel} '${normalizedRoot}'.`
);
}
}
function dirnamePosix(normalizedFilePath: string): string {
const lastSlash = normalizedFilePath.lastIndexOf('/');
return lastSlash <= 0 ? '/' : normalizedFilePath.slice(0, lastSlash);
}
function validatePortsAndOptions(options: ExportNotebookSnapshotOptions): {
readonly notebookPath: string;
readonly outputPath: string;
readonly runner: NotebookCommandRunner;
readonly fs: NotebookSnapshotFs;
readonly marimoCommand: string;
readonly timeoutMs: number;
readonly cwd?: string;
} {
if (!isPlainObject(options)) {
throw new NotebookSnapshotError('INVALID_OPTION', 'Invalid options: expected an object.');
}
const { runner, fs } = options;
if (!isPlainObject(runner) || typeof runner.run !== 'function') {
throw new NotebookSnapshotError(
'INVALID_OPTION',
'Invalid runner: expected an object with a callable run(command, args, options) method.'
);
}
if (
!isPlainObject(fs) ||
typeof fs.stat !== 'function' ||
typeof fs.createExclusive !== 'function' ||
typeof fs.readBytes !== 'function' ||
typeof fs.rename !== 'function' ||
typeof fs.remove !== 'function'
) {
throw new NotebookSnapshotError(
'INVALID_OPTION',
'Invalid fs: expected an object implementing stat, createExclusive, readBytes, rename, and remove.'
);
}
const marimoCommand =
options.marimoCommand === undefined ? DEFAULT_MARIMO_COMMAND : options.marimoCommand;
if (
typeof marimoCommand !== 'string' ||
marimoCommand.trim().length === 0 ||
marimoCommand.includes('\0') ||
marimoCommand.startsWith('-')
) {
throw new NotebookSnapshotError(
'INVALID_OPTION',
'Invalid marimoCommand: expected a non-empty command name or path without NUL bytes or leading "-".'
);
}
const timeoutMs =
options.timeoutMs === undefined ? DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS : options.timeoutMs;
if (typeof timeoutMs !== 'number' || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
throw new NotebookSnapshotError(
'INVALID_OPTION',
'Invalid timeoutMs: expected a positive safe integer.'
);
}
const notebookPath = validateAbsolutePath(options.notebookPath, 'notebookPath', {
requiredExtension: '.py',
});
const outputPath = validateAbsolutePath(options.outputPath, 'outputPath', {
requiredExtension: '.html',
});
if (options.allowedNotebookRoot !== undefined) {
assertWithinRoot(
notebookPath,
options.allowedNotebookRoot,
'notebookPath',
'allowedNotebookRoot'
);
}
if (options.allowedOutputRoot !== undefined) {
assertWithinRoot(outputPath, options.allowedOutputRoot, 'outputPath', 'allowedOutputRoot');
}
let cwd: string | undefined;
if (options.cwd !== undefined) {
cwd = validateAbsolutePath(options.cwd, 'cwd');
}
return {
notebookPath,
outputPath,
runner,
fs,
marimoCommand,
timeoutMs,
...(cwd !== undefined ? { cwd } : {}),
};
}
function validateCommandResult(result: unknown, phase: 'check' | 'export'): NotebookCommandResult {
if (
!isPlainObject(result) ||
typeof result.exitCode !== 'number' ||
!Number.isSafeInteger(result.exitCode) ||
typeof result.stdout !== 'string' ||
typeof result.stderr !== 'string'
) {
throw new NotebookSnapshotError(
phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED',
`Invalid runner result for marimo ${phase}: expected { exitCode, stdout, stderr }.`
);
}
return {
exitCode: result.exitCode,
stdout: result.stdout,
stderr: result.stderr,
};
}
function issueHasBlockingError(issue: Record<string, unknown>): boolean {
if (issue.type === 'error' || issue.severity === 'breaking') {
return true;
}
const nested = issue.diagnostics;
if (Array.isArray(nested)) {
for (let i = 0; i < nested.length; i += 1) {
const diag = nested[i];
if (isPlainObject(diag) && (diag.type === 'error' || diag.severity === 'breaking')) {
return true;
}
}
}
return false;
}
function parseAndValidateCheckReport(parsed: unknown): {
readonly report: MarimoCheckReport;
readonly hasBlockingError: boolean;
} {
if (!isPlainObject(parsed)) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
'marimo check JSON output must be an object with { issues, summary }.'
);
}
const { issues, summary } = parsed;
if (!Array.isArray(issues) || !isPlainObject(summary)) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
'marimo check JSON output must contain an issues array and a summary object.'
);
}
if (
typeof summary.errored !== 'boolean' ||
typeof summary.total_files !== 'number' ||
!Number.isSafeInteger(summary.total_files)
) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
'marimo check summary must include boolean errored and integer total_files.'
);
}
if (summary.total_files !== 1) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check reported summary.total_files=${summary.total_files}; expected exactly 1 checked file.`,
{ details: { diagnostics: parsed } }
);
}
let hasBlockingError = summary.errored;
for (let i = 0; i < issues.length; i += 1) {
const issue = issues[i];
if (!isPlainObject(issue)) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}] must be an object.`,
{ details: { diagnostics: parsed } }
);
}
if (issue.type !== undefined && typeof issue.type !== 'string') {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].type must be a string when present.`,
{ details: { diagnostics: parsed } }
);
}
if (issue.severity !== undefined && typeof issue.severity !== 'string') {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].severity must be a string when present.`,
{ details: { diagnostics: parsed } }
);
}
if (issue.diagnostics !== undefined) {
if (!Array.isArray(issue.diagnostics)) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].diagnostics must be an array when present.`,
{ details: { diagnostics: parsed } }
);
}
for (let j = 0; j < issue.diagnostics.length; j += 1) {
const diag = issue.diagnostics[j];
if (!isPlainObject(diag)) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].diagnostics[${j}] must be an object.`,
{ details: { diagnostics: parsed } }
);
}
if (diag.type !== undefined && typeof diag.type !== 'string') {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].diagnostics[${j}].type must be a string when present.`,
{ details: { diagnostics: parsed } }
);
}
if (diag.severity !== undefined && typeof diag.severity !== 'string') {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].diagnostics[${j}].severity must be a string when present.`,
{ details: { diagnostics: parsed } }
);
}
}
}
if (issueHasBlockingError(issue)) {
hasBlockingError = true;
}
}
return {
report: parsed as MarimoCheckReport,
hasBlockingError,
};
}
function deepFreeze<T>(value: T): T {
if (typeof value !== 'object' || value === null || Object.isFrozen(value)) {
return value;
}
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i += 1) {
deepFreeze(value[i]);
}
return Object.freeze(value);
}
const record = value as Record<string, unknown>;
const keys = Object.keys(record);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i] as string;
deepFreeze(record[key]);
}
return Object.freeze(value);
}
function generateTempToken(): string {
tempSequence += 1;
const randomPart =
typeof globalThis.crypto !== 'undefined' && typeof globalThis.crypto.randomUUID === 'function'
? globalThis.crypto.randomUUID().replace(/-/g, '')
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
return `${tempSequence}-${randomPart}`;
}
async function reserveSiblingTempHtml(fs: NotebookSnapshotFs, outputPath: string): Promise<string> {
const dir = dirnamePosix(outputPath);
const dirPrefix = dir === '/' ? '' : dir;
for (let attempt = 0; attempt < MAX_TEMP_RESERVATION_ATTEMPTS; attempt += 1) {
const candidate = `${dirPrefix}/.marimo-snapshot-${generateTempToken()}.tmp.html`;
try {
await fs.createExclusive(candidate);
return candidate;
} catch (err) {
if (getErrorCode(err) === 'EEXIST') {
continue;
}
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`Failed to reserve temporary HTML sibling for '${outputPath}'.`,
{ cause: err }
);
}
}
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`Failed to reserve a unique temporary HTML sibling for '${outputPath}' after ${MAX_TEMP_RESERVATION_ATTEMPTS} attempts.`
);
}
async function sha256HexNodeCrypto(bytes: Uint8Array): Promise<string> {
// Keep the Node built-in specifier non-literal so browser bundlers do not try
// to statically resolve `node:crypto` when bundling `@stock-bot/research`.
const cryptoSpecifier = 'node:crypto';
const nodeCrypto = (await import(cryptoSpecifier)) as typeof import('node:crypto');
return nodeCrypto.createHash('sha256').update(bytes).digest('hex');
}
async function runPhaseCommand(
runner: NotebookCommandRunner,
command: string,
args: readonly string[],
runOptions: NotebookCommandRunOptions,
phase: 'check' | 'export'
): Promise<NotebookCommandResult> {
let rawResult: unknown;
try {
rawResult = await runner.run(command, args, runOptions);
} catch (err) {
if (getErrorCode(err) === 'ETIMEDOUT') {
throw new NotebookSnapshotError(
'TIMEOUT',
`marimo ${phase} timed out after ${runOptions.timeoutMs}ms.`,
{ cause: err, details: { phase, timeoutMs: runOptions.timeoutMs } }
);
}
throw new NotebookSnapshotError(
phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED',
`marimo ${phase} command failed to execute.`,
{ cause: err, details: { phase } }
);
}
return validateCommandResult(rawResult, phase);
}
/**
* Validates a marimo notebook with `marimo check --format=json` and, only when
* the check is clean, exports a static HTML snapshot via `marimo export html`
* and publishes it atomically via sibling temp-file rename.
*/
export async function exportNotebookSnapshot(
options: ExportNotebookSnapshotOptions
): Promise<NotebookSnapshotReceipt> {
const { notebookPath, outputPath, runner, fs, marimoCommand, timeoutMs, cwd } =
validatePortsAndOptions(options);
let notebookStat: NotebookSnapshotFileStat | null;
try {
notebookStat = await fs.stat(notebookPath);
} catch (err) {
if (getErrorCode(err) === 'ENOENT') {
notebookStat = null;
} else {
throw new NotebookSnapshotError(
'NOTEBOOK_NOT_FOUND',
`Unable to stat notebook '${notebookPath}'.`,
{ cause: err }
);
}
}
if (notebookStat === null || !notebookStat.isFile) {
throw new NotebookSnapshotError(
'NOTEBOOK_NOT_FOUND',
`Notebook file not found or is not a regular file: '${notebookPath}'.`
);
}
const runOptions: NotebookCommandRunOptions =
cwd !== undefined ? { cwd, timeoutMs } : { timeoutMs };
// Step 1: Gate on `marimo check --format=json <notebookPath>`.
const checkResult = await runPhaseCommand(
runner,
marimoCommand,
['check', '--format=json', notebookPath],
runOptions,
'check'
);
const hasCheckStdout = checkResult.stdout.length > 0;
let parsedCheckJson: unknown = undefined;
let checkJsonParseError: unknown = undefined;
if (hasCheckStdout) {
try {
parsedCheckJson = JSON.parse(checkResult.stdout);
} catch (err) {
checkJsonParseError = err;
}
}
if (checkResult.exitCode !== 0) {
throw new NotebookSnapshotError(
'CHECK_FAILED',
`marimo check exited with code ${checkResult.exitCode}.`,
{
details: {
exitCode: checkResult.exitCode,
stderr: checkResult.stderr,
stdout: checkResult.stdout,
...(checkJsonParseError === undefined && parsedCheckJson !== undefined
? { diagnostics: parsedCheckJson }
: {}),
},
}
);
}
let checkDiagnostics: MarimoCheckReport | null = null;
if (hasCheckStdout) {
if (checkJsonParseError !== undefined) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
'marimo check exited 0 but emitted non-JSON stdout.',
{
cause: checkJsonParseError,
details: { stdout: checkResult.stdout, stderr: checkResult.stderr },
}
);
}
const { report, hasBlockingError } = parseAndValidateCheckReport(parsedCheckJson);
if (hasBlockingError) {
throw new NotebookSnapshotError(
'CHECK_FAILED',
'marimo check reported blocking errors in diagnostics.',
{
details: {
exitCode: checkResult.exitCode,
stderr: checkResult.stderr,
diagnostics: report,
},
}
);
}
checkDiagnostics = deepFreeze(report);
}
// Step 2: Reserve an exclusive sibling `.html` temp file and run `marimo export html`.
const tempPath = await reserveSiblingTempHtml(fs, outputPath);
let tempOwned = true;
try {
const exportResult = await runPhaseCommand(
runner,
marimoCommand,
['export', 'html', notebookPath, '-o', tempPath, '--force'],
runOptions,
'export'
);
if (exportResult.exitCode !== 0) {
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`marimo export html exited with code ${exportResult.exitCode}.`,
{
details: {
exitCode: exportResult.exitCode,
stderr: exportResult.stderr,
stdout: exportResult.stdout,
},
}
);
}
let tempStat: NotebookSnapshotFileStat | null;
try {
tempStat = await fs.stat(tempPath);
} catch (err) {
if (getErrorCode(err) === 'ENOENT') {
tempStat = null;
} else {
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`Failed to stat exported snapshot temp file '${tempPath}'.`,
{ cause: err }
);
}
}
if (tempStat === null || !tempStat.isFile || tempStat.size <= 0) {
throw new NotebookSnapshotError(
'EXPORT_EMPTY',
`marimo export html produced missing or empty output at '${tempPath}'.`
);
}
let exportedBytes: Uint8Array;
try {
exportedBytes = await fs.readBytes(tempPath);
} catch (err) {
if (getErrorCode(err) === 'ENOENT') {
throw new NotebookSnapshotError(
'EXPORT_EMPTY',
`Exported snapshot temp file '${tempPath}' disappeared before read.`,
{ cause: err }
);
}
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`Failed to read exported snapshot temp file '${tempPath}'.`,
{ cause: err }
);
}
if (!(exportedBytes instanceof Uint8Array) || exportedBytes.byteLength === 0) {
throw new NotebookSnapshotError(
'EXPORT_EMPTY',
`marimo export html produced zero bytes at '${tempPath}'.`
);
}
const sha256 = await sha256HexNodeCrypto(exportedBytes);
const receipt: NotebookSnapshotReceipt = Object.freeze({
notebookPath,
outputPath,
bytes: exportedBytes.byteLength,
sha256,
checkDiagnostics,
});
try {
await fs.rename(tempPath, outputPath);
tempOwned = false;
} catch (err) {
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`Failed to atomically publish snapshot from '${tempPath}' to '${outputPath}'.`,
{ cause: err }
);
}
return receipt;
} catch (err) {
if (tempOwned) {
try {
await fs.remove(tempPath);
} catch {
// Preserve the primary error if temp cleanup also fails.
}
}
if (err instanceof NotebookSnapshotError) {
throw err;
}
throw new NotebookSnapshotError(
'EXPORT_FAILED',
'Unexpected failure during notebook snapshot export.',
{ cause: err }
);
}
}

Some files were not shown because too many files have changed in this diff Show more