| .. | ||
| benchmarks | ||
| src | ||
| test | ||
| package.json | ||
| README.md | ||
| tsconfig.json | ||
@stock-bot/data-pipeline
Normalizes raw provider collections from MongoDB (stock) into canonical PostgreSQL security-master records and curated research datasets.
Safety & Connection Model
- Port:
2002(PIPELINE_SERVICE_PORT, default2002indocker-compose.yml/docker-compose.dev.yml). - Read-Only MongoDB Enforcement: Bootstraps its DI container with
mongoReadOnly: true, connecting viaMONGODB_READ_URI(studio_stock_bot_read@stock) and blocking all write, index, and collection-mutation methods at the client wrapper layer. - Dev vs QA Targets:
- In
development, reads QA MongoDB read-only and writes only to isolated dev PostgreSQL (localhost:5433/trading_bot_dev).assertEnvironmentSafety()hard-blocks writable connections to QA MongoDB (27017/stock) or QA PostgreSQL (5432/trading_bot). - Destructive sync flags (
?clear=true,POST /sync/clear) are restricted in non-test environments; never run destructive clears againsttrading_bot.
- In
Current Runtime Scope
- MongoDB Inputs:
exchanges,eodExchanges,ibExchanges,qmExchanges,eodSymbols,ibSymbols,qmSymbols. - PostgreSQL Tables (
database/postgres/init/02-master-schema.sql):exchanges&provider_exchange_mappingssymbols&provider_mappingssync_status
- HTTP Endpoints (
src/routes/):GET /health— liveness & database readinessGET /sync/status&GET /sync/status/enhanced— sync state and countsPOST /sync/exchanges/all— normalize exchange reference catalogPOST /sync/symbols/:provider— syncqm,eod, oribsymbol mappings
Target Architecture (Milestone M1 & M2)
Full specifications live in:
- DATA-CONTRACTS.md — Empirical 31-collection rules, bi-temporal security master (
exchange,exchange_source_map,instrument,instrument_identifier_history,listing,corporate_action_continuity,listing_symbol_history,provider_mapping,resolution_conflict,override,golden_field_audit), Hive Parquet + DuckDB schemas (bars_1d,fundamentals_pit,earnings_events_pit,short_interest_pit,macro_pit,fx_rates_1d), and QuestDB10.2.0intraday schema. - MILESTONES.md — Step-by-step
M0(read-only wrapper hardening),M1(US + Canada security master &bars_1d+fx_rates_1dcuration), andM2(qmFilings-backed PIT fundamentals, earnings, short interest, and macro curation). - phase1-investigation.md — Initial provider exchange/symbol investigation notes.
Commands
Run from the repository root:
# Start pipeline in dev mode (targets localhost:5433/trading_bot_dev)
bun run --cwd apps/stock/data-pipeline dev
# Typecheck & build
bun run typecheck
bun run build
# Run PostgreSQL environment & read-only MongoDB safety tests
bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/pipeline-safety.test.ts
Pass 1 Exchange Seed Generator
The committed baseline seed in database/postgres/init/35-security-master-exchange-seed.sql covers the 11 US+CA ISO 10383 MICs and the 17 documented explicit provider mappings. To regenerate a full reviewable candidate seed and unresolved-codes report from the read-only QA MongoDB collections (eodExchanges, ibExchanges, qmExchanges, ceoExchanges) on the host:
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
bun run apps/stock/data-pipeline/src/security-master/generate-exchange-seed.ts \
--sql-out ./tmp/35-security-master-exchange-seed.generated.sql \
--report-out ./tmp/pass1-unresolved-exchanges.md
- Read-only guarantee: The CLI initializes config with
mongoReadOnly: true, connects viaMONGODB_READ_URIwithreadOnly: true, performs zero MongoDB writes, and performs zero PostgreSQL writes. - Review and upgrade workflow: Keep
database/postgres/init/35-security-master-exchange-seed.sqlimmutable as the reproducible Pass 1 baseline—runPostgresMigrationsrecords applied filenames inmigrationsand skips any file it has already run, so editing migration35in place would not reach databases that already applied it. Instead, inspect./tmp/pass1-unresolved-exchanges.mdfor unresolved codes (unknown MICs, multi-valuedOperatingMIC, missing MICs), add approved additions or corrections as a new numbered migration underdatabase/postgres/init/(for example36-security-master-exchange-overrides.sql, settingreviewed_byon director-approved rows) and register it inMASTER_FILESinlibs/data/postgres/src/migrations.ts(also updatingEXPLICIT_EXCHANGE_SOURCE_RULESif future generator runs should classify those codes explicitly). Verify the upgrade against a schema where migration35has already run—not only a fresh schema—confirming the new migration applies cleanly and that re-applying the baseline never overwrites rows wherereviewed_by IS NOT NULL.
Pass 4 Cross-Sectional Price Cross-Check
apps/stock/data-pipeline/src/security-master/price-cross-check.ts provides pure, zero-I/O verification for candidate source-to-source listing pairs before persisting provider_mapping / resolution_conflict rows:
- Stratified date sampling (
selectSampleDates): Drops invalid/non-YYYY-MM-DDvalues, deduplicates, sorts ascending, and selectscountdates (default25) by splitting the calendar intocountcontiguous near-equal strata and picking the middle date of each (returning all valid unique dates when<= count). - Price ratio & FX rules (
crossCheckPrices): Compares raw sample closes over dates where both sides have a finiteclose > 0(conflicting duplicate closes or FX rates drop that date and are counted; missing FX dates on cross-currency pairs are skipped and never forward-filled). Expectedleft/rightratio is1.0for matching ISO currencies,usdCad(CAD per 1 USD) forCAD/USD, and1 / usdCadforUSD/CAD; any other currency combination returnsunsupported_currency_pair. - Return correlation: Computes two-pass centered Pearson correlation of consecutive log returns in a canonical common currency (converting CAD closes to USD via
cadClose / usdCadforCAD/USDpairs so correlation is orientation-symmetric and unaffected by FX moves on flat USD prices), rounded to4decimal places (provider_mapping.price_corr NUMERIC(5,4)). Returnsnullwhen fewer than3returns exist or either series has zero variance. - Strict verdict priority & defaults:
unsupported_currency_pair->insufficient_data(usableDates < 5orpriceCorr === null) ->ratio_mismatch(medianRatiooutside inclusive[1 - 0.02, 1 + 0.02]) ->low_correlation(priceCorr < 0.9) ->confirmed. Malformed candidate pairs or endpoints never abort the batch; each malformed slot is counted instats.invalidPairsand recorded with a deterministic non-confirming verdict so verdict counts always reconcile withpairsIn. - Conflicts: Emits
resolution_conflict-shaped records only forratio_mismatch(price_ratio_mismatch) andlow_correlation(price_low_correlation), keyed toleft.sourceandleft.sourceIdwith a JSON-serializabledetailpayload.
Pass 4a Sample-Close & USD/CAD Reader (sample-closes.ts)
apps/stock/data-pipeline/src/security-master/sample-closes.ts provides the read-only MongoDB reader (buildSampleCloseFilter, readSampleCloses) that streams cross-sectional sample closes from eodPrices, qmPrices, and CAD.FOREX into SampleCloseRecord[] and FxRateByDateRecord[] for crossCheckPrices:
- Date storage finding &
$intype:eodPrices(apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts) explicitly enforces and persistsdateas an exactYYYY-MM-DDstring.qmPrices(apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts) copies the provider'sprice.datefield verbatim and derives a BSONDateseparately indateTime, so exactYYYY-MM-DDformatting onqmPrices.dateis an assumption based on the QuoteMedia payload until verified against live QA MongoDB or a captured provider fixture. Keeping the approved string query,buildSampleCloseFilteremits date-first{ date: { $in: string[] } }filters (sortedYYYY-MM-DDstrings, aligning withBAR_SPAN_COLLECTIONSinsrc/normalization/bar-spans.tsanddesign/DATA-CONTRACTS.md) so queries use{ date: 1, eodSearchCode: 1 }and{ qmSearchCode: 1, date: 1 }. On decode, bothDateinstances and string dates are normalized to UTCYYYY-MM-DDvianormalizeBarDate; because any format or BSON-type mismatch ondatewould exclude rows before decode, row counts should be verified on the first live read-only Pass 4 run. - Read-only streaming, raw prices, and FX isolation: Uses
ReadOnlySourceSymbolReader(rejecting non-read-only readers before anyfindand rejecting buffered array results withTypeError), closes cursors infinallyon success and error, projects only_id: 0, id,date, and rawclose(eodPrices/CAD.FOREX) or rawunadjustedclose(qmPrices— nevercloseoradjustedclose), stripsCAD.FOREXfrom equity reads so FX never leaks intocloses, preserves untrimmed non-blank IDs (T-49), chunks large ID sets (idChunkSize, default10,000), skips empty sources (findsRun: 0), and reconcilesdocsRead === emitted + skippedTotalper source. - Local synthetic benchmark (zero MongoDB): Run the headless 500,025-doc streaming benchmark with:
bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts
- Recorded baseline (
2026-11-28, local sandbox, in-memory async cursor fake reader):- Workload:
500,025synthetic docs (25sample dates ×20,000IDs split10,000eodPrices+10,000qmPrices, plus25CAD.FOREXFX docs). - Observed throughput:
2,627,752 docs/s(190.3 mselapsed,25.36 MiBheap delta).
- Workload:
Security Master Persistence (persistSecurityMaster)
apps/stock/data-pipeline/src/security-master/persist.ts persists in-memory Pass 3 (Stage A/B), Pass 5 (resolution_conflict), and Pass 6 (delisting-chains) results into the master track PostgreSQL tables inside a single transaction guarded by pg_advisory_xact_lock(0x534d5053, hashtext(current_schema())):
- Permanent IDs & idempotency: Upserts
instrumentbyprimary_isinand resolveslistingby(instrument_id, mic, ticker_root, class_suffix, currency)without ever changing or deleting an existinginstrument_idorlisting_id. - Override precedence: After upserting
provider_mapping(tier1_isin = 0.990,tier2_cusip = 0.950,tier3_ticker_span = 0.800), unconditionally enforces every row inoverride(method = 'override',confidence = 1.000,price_corr = NULL) so re-runs with conflicting matcher output cannot overwrite director overrides. - Stale fallback cleanup: When a run supplies only dated
provider_mappingrows (validFrom !== '1900-01-01') for a(source, source_id), any leftover1900-01-01fallback row for that pair is deleted in batchedUNNESTstatements within the same transaction and counted inproviderMappingsDeletedStaleFallback. Rows withmethod = 'override', rows protected by anoverrideentry at1900-01-01, dated rows, and(source, source_id)pairs absent from the run are never deleted. - No guessing: Instruments with null/blank
canonicalNameor absent fromsecurityTypeByIsin, and listings with an unknownmic, are skipped and counted per reason along with all dependent listings, mappings, Pass 6 outcomes, and continuities. - Batched writes & local benchmark: All bulk reads/writes use parameterised
UNNESTbatches (default/max chunk size5000). Run the PostgreSQL integration suite and fixed-seed 20,000-instrument / 20,000-listing / 60,000-mapping benchmark against an isolatedstock_bot_safety_*schema with:
bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts
- Recorded baseline (
2026-11-28, host PostgreSQL isolatedstock_bot_safety_*schema, defaultchunkSize = 5000):- Workload:
20,000instruments,20,000listings,60,000provider mappings (100,000core rows;140,000total rows including20,000instrument_identifier_historyand20,000listing_symbol_historyrows). - Observed end-to-end test wall time:
2.36s(2359.01ms, reported bybun test; includes isolated schema migration, synthetic fixture construction,persistSecurityMaster, andCOUNT(*)verification). - Throughput (conservative lower bound over full test wall time):
42,391core rows/s (100,000 / 2.35901s),59,347total rows/s (140,000 / 2.35901s).
- Workload:
Read-Only Source-Symbol Readers (source-symbol-readers.ts)
apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts adapts raw eodSymbols, ibSymbols, qmSymbols, ceoSymbols, and eodSymbolChange documents into deterministic Stage A (StageASourceRecord) and Stage B (StageBEodListingInput, StageBIbContractInput, StageBTickerSourceInput, StageBSymbolChangeInput) inputs via readSecurityMasterSources:
- Read-only streaming contract:
ReadOnlySourceSymbolReaderexposes strictlyisReadOnly()andfind()returning an incrementalAsyncIterable(rejecting buffered array results). Production callers adapt a read-onlyMongoDBClientviacreateReadOnlyMongoSourceSymbolReader(client), which streams throughcollection.find(filter, options)(FindCursor, nevercursor.toArray()), closes cursors infinally, projects_id: 0(omittingqmSymbols.profile/symbolInfo, projectingeodSymbolChange.effective), and pushes down$orcountry/venue filters preserving normalized spellings and venue fallbacks (default['US', 'CA']). - Provider & Pass 1 rules enforced:
createExchangeSourceLookuplayers reviewed US+CA venue mappings (REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS) on top of the 17-row Pass 1 baseline (EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS) with caller/Pass 1 rows overriding. Readers excludeeodSymbolsExchange="NMFQS"mutual funds, preservedelisted: trueand duplicate QM(symbol, exchange)pairs (VOY:CNX+VOY:CC), set Stage A country strictly to issuer country (never listing country), never use IB ATSexchangeIdvenues (AEQLIT,OTCLNKECN, etc.) as listing MIC orprimaryExchange, strip CEO.TO/.Vsuffixes with Stage B double-strip protection, parseeodSymbolChange.effective(alongsideeffectiveDate/date), null invalid ISIN/CUSIP check digits without throwing, and reconciledocsRead === emitted + sum(skips)per collection. - Local synthetic benchmark: Run the unit suite and fixed-seed 368,000-doc synthetic benchmark (
300,000eodSymbols+50,000qmSymbols+18,000ibSymbols, zero DB connections) with:
bun test test/unit/security-master-source-symbol-readers.test.ts
- Recorded baseline (
2026-11-28, local sandbox, in-memory async cursor fake reader):- Workload:
368,000synthetic docs (300,000eodSymbols,50,000qmSymbols,18,000ibSymbols) including NMFQS exclusion, country normalization, ISIN/CUSIP check-digit validation, ticker parsing, and deterministic ASCII sorting. - Observed throughput:
754,047 docs/s(488.0 mswall time, floor>= 25,000 docs/s).
- Workload:
EOD Security-Type Classifier (security-type.ts)
apps/stock/data-pipeline/src/security-master/security-type.ts maps raw EODHD Type strings into the canonical PostgreSQL instrument.security_type enum (SecurityType) and builds the securityTypeByIsin map required by persistSecurityMaster (wired automatically through readEodSymbols and readSecurityMasterSources).
- Mapping table (
EOD_SECURITY_TYPE_MAP, trimmed, whitespace-collapsed, case-insensitive):
EODHD Type |
Canonical SecurityType |
|---|---|
Common Stock |
common |
Preferred Stock |
preferred |
ETF |
etf |
Unit, Units |
unit |
Warrant, Warrants |
warrant |
Right, Rights |
right |
CDR |
cdr |
Currency, Forex, FX |
fx |
- Published-vocabulary & no-guess rule: Because QA MongoDB is unreachable from the agent sandbox, the table is based on the published EODHD
Typevocabulary. Non-equity-like values (FUND,Mutual Fund,Bond,Notes,INDEX, etc.), blanks, non-strings, and unmapped strings returnnulland are never guessed from ticker suffixes or company names. A non-stringTypeon aneodSymbolsdocument does not skip the document from Stage A/B — it is counted undersecurityTypeStats.missingType. - Stage A membership & raw vocabulary diagnostics:
readEodSymbols/readSecurityMasterSourcesbuild the loader-facingsecurityTypeByIsinmap,securityTypeConflicts, andsecurityTypeLoaderStatsstrictly from EOD rows accepted as Stage A instrument members (buildSecurityTypeByIsinForStageA), so rows quarantined by Stage A (isin_cusip_mismatch,duplicate_source_id) can neither supply nor veto a valid instrument's security type. At the same time,securityTypeStatsandunknownSecurityTypesreconcile over all emitted EOD rows (also retained insecurityTypeRecords), so unmapped vocabulary on quarantined rows is never silently hidden. - Reviewing unmapped values & conflicts: After a real security-master run, inspect
unknownSecurityTypes(sorted by count descending, then ASCII, reconciling withsecurityTypeStats.unknownTypeacross all emitted EOD rows) for any newly observed provider strings that should be added toEOD_SECURITY_TYPE_MAP, and inspectsecurityTypeConflicts(ISINs omitted fromsecurityTypeByIsinbecause multiple Stage A-accepted EOD documents disagreed on their classified type; capped bymaxSecurityTypeConflicts, default200, reconciling withsecurityTypeLoaderStats.isinsConflictingandconflictsTruncated). - Local synthetic benchmark: Run the unit suite and fixed-seed 300,000-record synthetic benchmark (zero DB connections) with:
bun test test/unit/security-master-security-type.test.ts
- Recorded baseline (
2026-11-28, local sandbox, zero DB connections):- Workload:
300,000synthetic EOD records (100,000distinct ISIN buckets, mixed mapped/unknown/missing types, and20conflicting ISINs exercising Pass 2 conflict collection). - Observed throughput:
4,277,092 records/s(70.1 mswall time, floor>= 100,000 records/s).
- Workload:
Security-Master Run Composer (run.ts)
apps/stock/data-pipeline/src/security-master/run.ts provides a pure, zero-I/O entry point (composeSecurityMasterRun) that wires in-memory source-symbol reader outputs and observed bar spans end to end without touching MongoDB, PostgreSQL, or the filesystem:
sources + barSpans -> matchInstrumentsStageA -> attachBarSpansToStageBInput -> matchListingsStageB -> linkDelistingChains (Pass 6) -> optional crossCheckPrices (Pass 4) -> buildMatchReport (+ Markdown / CSV / override-template SQL) + PersistSecurityMasterInput
- Pure & deterministic: Contains zero I/O imports and zero wall-clock calls. Shuffling any input array or
securityTypeByIsinmap insertion order produces byte-identical Markdown, CSV, override-template SQL, and deep-equalPersistSecurityMasterInput. - Explicit Pass 4 skipping: When
sampleClosesis omitted or empty, Pass 4 is markedskippedin bothstats.pass4and the rendered Markdown (- Status: skipped (no sample closes supplied)),pass4isnull, andpersistInput.pass4is omitted — it is never reported as passed. - Malformed-record resilience & reconciliation: Pre-pass sanitizers skip and count malformed or sparse entries across every input array without aborting the run, and every step reconciles
recordsIn === resolved + unresolved + skippedwithreport.conflicts.length === stageA + stageB + pass4 + pass6. - Local synthetic benchmark: Run the unit suite and fixed-seed 100,000-record synthetic benchmark (zero DB connections) with:
bun test test/unit/security-master-run.test.ts
- Recorded baseline (
2026-11-28, local sandbox, zero DB connections):- Workload:
100,000synthetic source records (50,000EOD +25,000IB +25,000QM,75,000bar spans,50,000security types) composed end to end through Stage A, Stage B, Pass 6, Pass 4 pair derivation, MatchReport + Markdown/CSV/SQL rendering, andPersistSecurityMasterInputassembly. - Observed throughput:
208,502 records/s(479.6 mswall time, asserted floor>= 10,000 records/s).
- Workload:
Running the security master
apps/stock/data-pipeline/src/security-master/run-security-master.ts runs the full read-only MongoDB security-master pipeline (read-exchanges -> read-sources -> compute-bar-spans -> composeSecurityMasterRun) and writes deterministic report artifacts, with opt-in PostgreSQL persistence via --persist.
Dry run (read-only MongoDB, zero PostgreSQL connections)
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts \
--as-of 2026-01-15 \
--out-dir ./tmp/security-master-report
- Scope of
--as-of <YYYY-MM-DD>:--as-ofsets the calendar reference date for Pass 6 delisting classification (active grace window vs. delisted outcome). It does not take a historical point-in-time snapshot of MongoDB — source symbol records and bar spans are read from the current collections, so the report can incorporate provider observations recorded after--as-of.
Persist to isolated dev PostgreSQL (localhost:5433/trading_bot_dev)
Apply the master track migrations to isolated dev PostgreSQL first (passing the dev target variables explicitly so a QA-configured shell cannot migrate QA):
NODE_ENV=development \
POSTGRES_HOST=localhost \
POSTGRES_PORT=5433 \
POSTGRES_DATABASE=trading_bot_dev \
bun run db:migrate --track master
Then run the CLI with --persist against the same isolated dev PostgreSQL target:
NODE_ENV=development \
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
POSTGRES_HOST=localhost \
POSTGRES_PORT=5433 \
POSTGRES_DATABASE=trading_bot_dev \
bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts \
--as-of 2026-01-15 \
--out-dir ./tmp/security-master-report \
--persist
- Safety guards: MongoDB is always opened with
mongoReadOnly: trueviaMONGODB_READ_URI. Without--persist, no PostgreSQL client is constructed. With--persist,assertSecurityMasterPersistSafety()runsassertEnvironmentSafety()(withSTOCK_BOT_ALLOW_DEV_ON_QA_DBstripped) and enforcesNODE_ENV=developmentagainst an isolated dev PostgreSQL database (*_dev/stock_bot_safety*), blockingNODE_ENV=qaand QA PostgreSQL (localhost:5432/trading_bot) before any PostgreSQL client is created. - Pass 4 status: Pass 4 cross-sectional price cross-check input (
sampleCloses/fxRates) is not yet wired into this CLI;composeSecurityMasterRunis invoked without sample closes and Pass 4 is explicitly reported asskipped(pass4: null).
Output files (--out-dir)
All four files are deterministic and byte-identical for identical inputs (no wall-clock timestamps or output paths):
match-report.md— Human-readable match report covering exchange coverage, per-source/per-country resolution, unresolved breakdowns, Pass 4 (skipped), Pass 6 delisting chains, and conflicts.conflicts.csv— Unified deterministic conflict export across Stage A, Stage B, Pass 4, and Pass 6.override-template.sql— Commented SQL template for director-reviewedoverrideentries.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 viaMONGODB_READ_URI(studio_stock_bot_read@stock), refuses non-read-only readers before issuing any query, and runs strictlyfind({}, { limit, promoteValues: false, promoteLongs: false })(defaultlimit = 1,000, max10,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):
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 (
8collections ×10,000limit) with:
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,000synthetic docs (8collections ×10,000limit) with mixed BSON/JS types, one-level nested objects, and all five string pattern classes, includingrenderFieldShapesMarkdown. - Initial implementation:
442,496 docs/s(180.8 mselapsed,28.50 MiBheap delta). - After path-segment escaping, exact defensive sample cap, and GFM/HTML-safe cell formatting:
365,756 docs/s(218.7 mselapsed,27.66 MiBheap delta).
- Workload:
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):
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 throughcurrent/<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 ./outandcurate-etl curate-bars-1d --eod-prices eodPrices.bson --qm-splits qmSplits.bson --curate-inputs ./tmp/curate-inputs --out ./out), and TypeScript consumers can pin viapinCurateInputSnapshot(outDir)so concurrent refreshes never mix files from different PostgreSQL snapshots.
- Each export writes all three TSVs into
- Output files:
provider_mapping.tsv—source \t source_id \t valid_from \t valid_to(or empty) \t listing_id, sorted inCOLLATE "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 ascendinglisting_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 againstqmmappings (valid_from <= effective_datefor outgoing OTC transfers, valid oneffective_datefor OTC successors, valid onlisted_tofor terminal delistings) and indexed byfrom_listing_idso 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 anactivelisting has a continuity orterminal_return).noOutcome: non-active listings with neither an outgoingotc_delist_transfernor aterminal_return.missingListedTo: terminal-return listings withlisted_to IS NULL.missingOutgoingQmMapping: delisting/OTC candidates without a qualifying outgoingqmmapping.missingSuccessorQmMapping: OTC transfers whose successor listing has noqmmapping valid oneffective_date.nonOtcContinuity: non-otc_delist_transfercontinuities skipped in the purebuildDelistingExportRowsbuilder.
- Local synthetic benchmark (zero PostgreSQL): Run the fixed-seed 500,000-mapping / 100,000-listing streaming benchmark with:
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,000provider_mappingrows,100,000listingrows,2,000OTC continuities, terminal delistings, and skipped rows (606,680exported rows,17,203,861bytes written across all three TSVs). - Observed throughput:
1,506,181 rows/s(402.8 mselapsed,277.01 MiBpeak RSS).
- Workload:
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 aseodIntraday1M,qmIntraday,qmFinancials,ceoPosts) is rejected before any MongoDB call. - Flags:
--out-dir <dir>(required) — destination directory for<collection>.bsonfiles.--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--collectionsis strictlyeodPrices(for exampleCAD.FOREXforcurate-fx-1d). Use a separate--out-dirso a filtered slice never overwrites the fulleodPrices.bson.--te-symbol <sym>(optional) — exact{ teSymbol: <sym> }filter; only permitted when--collectionsis strictlyteMarketData(for exampleUSDCAD).--limit <n>(optional) — positive integer document cap per collection for smoke runs.--batch-size <n>(optional) — MongoDB cursorbatchSize(1..100000, default4096).--help— print usage and exit with zero config/Mongo/fs I/O.
- Read-only safety: Initializes config via
initializeStockConfig('dataPipeline', { mongoReadOnly: true }), enforcesassertEnvironmentSafety()viaassertExportRawBsonSafety(), connects throughresolveReadOnlyMongoClientConfig(), issues strictlyfind(..., { raw: true }), and always closes the MongoDB client infinally. 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)
- Export PostgreSQL security-master TSVs (
run-export-curate-inputs.ts):
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
- Export raw BSON collections from read-only QA MongoDB (
run-export-raw-bson.ts):
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
- Run
tools/curate-etlcommands (curate-bars-1dfirst, 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.parquetand prints read-onlyqmPrices.sharevolumecross-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:
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,000syntheticeodPricesraw BSON frames (123.9 Bavg,123,863,264bytes written, deterministicsha256=67f035eba7060d6312f3d5faecc9e6a6fa14f6239c0c4dc1859794b4cd895886). - Run 1 (
1,000,000docs):3,574,267 docs/s,422.21 MiB/s(279.8 mselapsed,rss_before=97.00 MiB,rss_after=149.91 MiB,peak_rss=150.19 MiB). - Run 2 (
1,000,000docs):3,692,715 docs/s,436.20 MiB/s(270.8 mselapsed,peak_rss=151.03 MiB, identicalsha256). - Scaling check (
2,000,000docs,247,726,576bytes):3,833,075 docs/s,452.78 MiB/s(521.8 mselapsed,peak_rss=146.88 MiB— confirms peak RSS stays bounded independent of document count).
- Workload: