diff --git a/Cargo.lock b/Cargo.lock index 6d77dd3a..11d01203 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,9 +10,9 @@ checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" dependencies = [ "cfg-if", "const-random", - "getrandom 0.3.4", "getrandom 0.4.3", "once_cell", + "serde", "version_check", "zerocopy", ] @@ -73,12 +73,51 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "bson" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3f109694c4f45353972af96bf97d8a057f82e2d6e496457f4d135b9867a518c" +dependencies = [ + "ahash", + "base64", + "bitvec", + "getrandom 0.3.4", + "hex", + "indexmap", + "js-sys", + "rand 0.9.5", + "serde_bytes", + "simdutf8", + "thiserror 2.0.21", + "time", + "uuid", +] + [[package]] name = "bumpalo" version = "3.20.4" @@ -239,6 +278,7 @@ dependencies = [ name = "curate-etl" version = "0.1.0" dependencies = [ + "bson", "parquet", ] @@ -255,6 +295,12 @@ dependencies = [ "parking_lot_core", ] +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "engine" version = "0.1.0" @@ -272,19 +318,25 @@ dependencies = [ "num-rational", "num-traits", "parking_lot", - "rand", + "rand 0.8.8", "rand_distr", "rust_decimal", "serde", "serde_json", "statrs", - "thiserror", + "thiserror 1.0.69", "tokio", "tracing", "tracing-subscriber", "uuid", ] +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.15" @@ -301,6 +353,12 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + [[package]] name = "futures-core" version = "0.3.34" @@ -343,9 +401,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 5.3.0", "wasip2", + "wasm-bindgen", ] [[package]] @@ -385,6 +445,12 @@ version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -409,6 +475,16 @@ dependencies = [ "cc", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", +] + [[package]] name = "itoa" version = "1.0.19" @@ -518,7 +594,7 @@ dependencies = [ "num-complex", "num-rational", "num-traits", - "rand", + "rand 0.8.8", "rand_distr", "simba 0.6.0", "typenum", @@ -661,6 +737,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-integer" version = "0.1.47" @@ -757,6 +839,12 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -796,6 +884,12 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + [[package]] name = "rand" version = "0.8.8" @@ -803,8 +897,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", ] [[package]] @@ -814,7 +918,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] @@ -826,6 +940,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rand_distr" version = "0.4.3" @@ -833,7 +956,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" dependencies = [ "num-traits", - "rand", + "rand 0.8.8", ] [[package]] @@ -933,6 +1056,16 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -1017,6 +1150,12 @@ dependencies = [ "wide", ] +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "slab" version = "0.4.12" @@ -1049,7 +1188,7 @@ dependencies = [ "lazy_static", "nalgebra 0.29.0", "num-traits", - "rand", + "rand 0.8.8", ] [[package]] @@ -1085,13 +1224,28 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + [[package]] name = "thiserror" version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", ] [[package]] @@ -1105,6 +1259,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "thread_local" version = "1.1.10" @@ -1114,6 +1279,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-keccak" version = "2.0.2" @@ -1399,6 +1594,15 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + [[package]] name = "zerocopy" version = "0.8.66" diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index f61e3161..0d31cee1 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -79,8 +79,8 @@ bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/secu - **Recorded baseline (`2026-11-28`, host PostgreSQL isolated `stock_bot_safety_*` schema, default `chunkSize = 5000`):** - Workload: `20,000` instruments, `20,000` listings, `60,000` provider mappings (`100,000` core rows; `140,000` total rows including `20,000` `instrument_identifier_history` and `20,000` `listing_symbol_history` rows). - - Observed end-to-end test wall time: `2.20s` (`2200.02ms`, reported by `bun test`; includes isolated schema migration, synthetic fixture construction, `persistSecurityMaster`, and `COUNT(*)` verification because `test/setup.ts` suppresses `console.info`). - - Throughput (conservative lower bound over full test wall time): `45,454` core rows/s (`100,000 / 2.20002s`), `63,636` total rows/s (`140,000 / 2.20002s`). + - Observed end-to-end test wall time: `2.36s` (`2359.01ms`, reported by `bun test`; includes isolated schema migration, synthetic fixture construction, `persistSecurityMaster`, and `COUNT(*)` verification). + - Throughput (conservative lower bound over full test wall time): `42,391` core rows/s (`100,000 / 2.35901s`), `59,347` total rows/s (`140,000 / 2.35901s`). ## 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`: diff --git a/apps/stock/data-pipeline/src/security-master/persist.ts b/apps/stock/data-pipeline/src/security-master/persist.ts index 5981f7f7..5fbce262 100644 --- a/apps/stock/data-pipeline/src/security-master/persist.ts +++ b/apps/stock/data-pipeline/src/security-master/persist.ts @@ -6,9 +6,9 @@ * schema, default `chunkSize = 5000`): * - Command: `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts` * - Workload: 20,000 instruments, 20,000 listings, 60,000 mappings (100,000 core rows; 140,000 total rows). - * - Observed end-to-end test wall time: 2.20s (2200.02ms, including schema setup, fixture generation, - * persistence, and COUNT(*) verification because `test/setup.ts` suppresses `console.info`). - * - Throughput (lower bound over full test wall time): 45,454 core rows/s, 63,636 total rows/s. + * - Observed end-to-end test wall time: 2.36s (2359.01ms, including schema setup, fixture generation, + * persistence, and COUNT(*) verification). + * - Throughput (lower bound over full test wall time): 42,391 core rows/s, 59,347 total rows/s. */ import type { DelistingChainResult, diff --git a/test/postgres/security-master-persist.test.ts b/test/postgres/security-master-persist.test.ts index ac5b0339..190aa890 100644 --- a/test/postgres/security-master-persist.test.ts +++ b/test/postgres/security-master-persist.test.ts @@ -1970,8 +1970,8 @@ describe.skipIf(!url)('persistSecurityMaster PostgreSQL integration', () => { expect(counts.listing).toBe(instrumentCount); expect(counts.provider_mapping).toBe(instrumentCount * 3); - console.info( - `[security-master-persist benchmark] ${instrumentCount} instruments, ${instrumentCount} listings, ${instrumentCount * 3} mappings (${totalAllRows} total rows) persisted in ${elapsedSec.toFixed(2)}s (${Math.round(totalCoreRows / elapsedSec)} core rows/s, ${Math.round(totalAllRows / elapsedSec)} total rows/s)` + process.stdout.write( + `[security-master-persist benchmark] ${instrumentCount} instruments, ${instrumentCount} listings, ${instrumentCount * 3} mappings (${totalAllRows} total rows) persisted in ${elapsedSec.toFixed(2)}s (${Math.round(totalCoreRows / elapsedSec)} core rows/s, ${Math.round(totalAllRows / elapsedSec)} total rows/s)\n` ); }, 120_000 diff --git a/test/unit/security-master-persist-benchmark-doc.test.ts b/test/unit/security-master-persist-benchmark-doc.test.ts new file mode 100644 index 00000000..2042fc23 --- /dev/null +++ b/test/unit/security-master-persist-benchmark-doc.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +// Guards the recorded persistSecurityMaster benchmark baseline against drift: the README and the +// persist.ts module doc must quote the same measurement, and each quoted rows/s figure must equal +// rows / elapsed seconds for the documented workload. +const repoRoot = join(import.meta.dir, '..', '..'); +const readmePath = join(repoRoot, 'apps/stock/data-pipeline/README.md'); +const persistPath = join(repoRoot, 'apps/stock/data-pipeline/src/security-master/persist.ts'); +const benchmarkTestPath = join(repoRoot, 'test/postgres/security-master-persist.test.ts'); + +const CORE_ROWS = 100_000; // 20,000 instruments + 20,000 listings + 60,000 mappings +const TOTAL_ROWS = 140_000; // core + 20,000 identifier history + 20,000 symbol history + +function toNumber(text: string): number { + return Number(text.replace(/,/g, '')); +} + +function parseBaseline(doc: string) { + const wall = doc.match(/\(`?([\d.]+)ms/); + const core = doc.match(/([\d,]+)`? core rows\/s/); + const total = doc.match(/([\d,]+)`? total rows\/s/); + expect(wall).not.toBeNull(); + expect(core).not.toBeNull(); + expect(total).not.toBeNull(); + return { + elapsedMs: toNumber(wall![1]!), + coreRowsPerSec: toNumber(core![1]!), + totalRowsPerSec: toNumber(total![1]!), + }; +} + +describe('security-master persist benchmark baseline documentation', () => { + const readme = readFileSync(readmePath, 'utf8'); + const persistDoc = readFileSync(persistPath, 'utf8').split('*/')[0]!; + + test('README rows/s figures equal documented rows divided by recorded wall time', () => { + const { elapsedMs, coreRowsPerSec, totalRowsPerSec } = parseBaseline(readme); + + expect(coreRowsPerSec).toBe(Math.round(CORE_ROWS / (elapsedMs / 1000))); + expect(totalRowsPerSec).toBe(Math.round(TOTAL_ROWS / (elapsedMs / 1000))); + }); + + test('persist.ts module doc quotes the same baseline as the README', () => { + const fromReadme = parseBaseline(readme); + const fromDoc = parseBaseline(persistDoc); + + expect(fromDoc).toEqual(fromReadme); + }); + + test('benchmark result line is written to stdout, not the muted console.info', () => { + const source = readFileSync(benchmarkTestPath, 'utf8'); + const lineIndex = source.indexOf('[security-master-persist benchmark]'); + expect(lineIndex).toBeGreaterThan(-1); + + const preceding = source.slice(Math.max(0, lineIndex - 200), lineIndex); + expect(preceding).toContain('process.stdout.write('); + expect(preceding).not.toContain('console.info('); + }); +}); diff --git a/tools/curate-etl/Cargo.toml b/tools/curate-etl/Cargo.toml index f397feb3..2f81cd3a 100644 --- a/tools/curate-etl/Cargo.toml +++ b/tools/curate-etl/Cargo.toml @@ -6,5 +6,6 @@ authors.workspace = true license.workspace = true [dependencies] +bson = { version = "=3.1.0", default-features = false, features = ["compat-3-0-0"] } parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] } diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index f067bedc..fe50b9b4 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated Rust crate (single direct dependency: `parquet` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, and the `M1.2i` streaming Zstd Parquet writer for `bars_1d`. +Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, and the `M1.2o` zero-copy raw BSON decoder for `eodPrices`. ## Scope & Sign Conventions @@ -76,7 +76,7 @@ Rules: ## `fx_1d` Builder (`M1.2e`) -`build_fx_1d` (`src/fx.rs`) merges `CAD.FOREX` daily bars (`FxSource::EodCadForex`, `"eod_cad_forex"`, 1971–2025) and `teMarketData.USDCAD` daily bars (`FxSource::TeUsdCad`, `"te_usdcad"`, through 2026+) into a single sorted, unique `USDCAD` series (`Fx1dRow`) matching the `fx_1d/part.parquet` value columns in `design/DATA-CONTRACTS.md` (excluding `ts`/`known_at` timestamps, which belong to the later writer task). +`build_fx_1d` (`src/fx.rs`) merges `CAD.FOREX` daily bars (`FxSource::EodCadForex`, `"eod_cad_forex"`, 1971–2025) and `teMarketData.USDCAD` daily bars (`FxSource::TeUsdCad`, `"te_usdcad"`, through 2026+) into a single sorted, unique `USDCAD` series (`Fx1dRow`) matching the `fx_1d/part.parquet` value columns in `design/DATA-CONTRACTS.md` (the `M1.2l` Parquet writer takes caller-supplied `ts`/`known_at` timestamps; timestamp derivation policy belongs to the Mongo-streaming wiring task). Rules: 1. **Quote convention:** Both inputs are USD/CAD quotes (CAD per 1 USD); no inversion is performed in this module (`CADUSD.FOREX` inversion is out of scope). @@ -92,7 +92,7 @@ Rules: - Merge: `rows_out == eod.rows_kept + te.rows_kept - te_superseded_by_eod == eod_rows_out + te_rows_out` - Overlap: `overlap_within_tolerance + overlap_mismatched == overlap_checked == te_superseded_by_eod` -Deferred out of `src/fx.rs`: `ts`/`known_at` timestamp derivation (later writer task), `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring FX into `src/adj.rs` cross-currency dividends. +Deferred out of `src/fx.rs`: `ts`/`known_at` timestamp derivation policy (the `M1.2l` Parquet writer accepts caller-supplied timestamps; derivation belongs to the Mongo-streaming wiring task), `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring FX into `src/adj.rs` cross-currency dividends. ## `shorts` Builder (`M1.2f`) @@ -212,6 +212,249 @@ Rules: - Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000` - Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` +## `shorts` Parquet Writer (`M1.2j`) + +`write_shorts_dataset` (`src/parquet_shorts.rs`) streams strictly ascending `(listing_id, report_date)` `ShortsParquetRow` records (with `From<&ShortRow>` / `From>` conversions from `build_shorts`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A). + +1. **Exact 7-column contract schema (`shorts_parquet_schema`):** + - `listing_id` (`INT32`, `REQUIRED`) + - `report_date` (`INT32`, `REQUIRED`, `DATE`) + - `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + - `shares_short` (`DOUBLE`, `REQUIRED`) + - `net_change` (`DOUBLE`, `OPTIONAL`) + - `pct_float` (`DOUBLE`, `OPTIONAL`) + - `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded) +2. **Layout, compression & streaming:** + - Writes `/shorts/part.parquet` (unpartitioned). + - Empty input returns `Ok(ShortsWriteStats::default())` without creating `/shorts` and without modifying or removing any pre-existing `part.parquet`. + - Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `ShortsWriteOptions::zstd_level`). + - Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `ShortsWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with string interning for `source`), flushing and clearing on every row-group boundary. + - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. +3. **Validation, concurrency & atomic publish rules:** + - Input must be strictly ascending by `(listing_id, report_date)` (rejecting duplicates and out-of-order rows). + - `shares_short` must be finite and `>= 0.0`; `net_change` and `pct_float` must be finite when `Some`; `known_at_micros` must be strictly after `report_date` `00:00:00 UTC` (compared in `i128` to avoid overflow on extreme `i32` epoch days); `source` must be non-empty after trimming. + - Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `/shorts` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet..tmp`), flush, and `File::sync_all()`; pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`. +4. **Typed errors (`ParquetShortsError`):** + - `InvalidRowGroupRows` (`row_group_rows == 0`) + - `InvalidZstdLevel { level }` + - `UnsortedInput { prev_listing_id, prev_report_date, listing_id, report_date }` + - `DuplicateKey { listing_id, report_date }` + - `InvalidSharesShort { listing_id, report_date, value }` + - `InvalidNetChange { listing_id, report_date, value }` + - `InvalidPctFloat { listing_id, report_date, value }` + - `KnownAtNotAfterReportDate { listing_id, report_date, known_at_micros }` + - `EmptySource { listing_id, report_date }` + - `LockTimeout { path, waited }` + - `RollbackFailed { cause, failures }` + - `Io { path, source }` + - `Parquet { path, source }` +5. **Measured baseline (`2026-11-28`):** + - Command: `cargo run --release -p curate-etl --offline -- bench-parquet-shorts` + - Input: `rows=1000000`, `listings=12500`, `raw_row_bytes=50` (semi-monthly dates `2017-04-15..=2026-04-30`) + - Output: `files=1`, `row_groups=1`, `bytes=6741816`, `read_back_rows=1000000` + - Perf: `elapsed=106.79 ms`, `throughput=9364116 rows/s`, `write=60.21 MB/s`, `size=6.74 bytes/row`, `compression=7.42x` + +## `events` Parquet Writer (`M1.2k`) + +`write_events_dataset` (`src/parquet_events.rs`) streams strictly ascending `EventsParquetRow` records (with `From<&EventRow>` / `From>` conversions from `build_events`) into Zstd-compressed, UTC-year-partitioned Parquet files matching `design/DATA-CONTRACTS.md` (§3A). + +1. **Exact 7-column contract schema (`events_parquet_schema`):** + - `listing_id` (`INT32`, `REQUIRED`) + - `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + - `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + - `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded) + - `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded) + - `subtype` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary disabled) + - `payload_json` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary disabled) +2. **Partition layout, compression & streaming:** + - Writes `/events/year=YYYY/part.parquet` lazily per observed UTC year `partition_year_utc(ts_micros)` (`1900..=2200`). + - Empty input returns `Ok(EventsWriteStats::default())` without creating `/events` and without modifying or removing any pre-existing partitions. + - Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `EventsWriteOptions::zstd_level`). + - Bounded streaming buffers (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `EventsWriteOptions::row_group_rows`): buffers at most one row group per active year; low-cardinality `known_at_source`/`kind` use string interning while high-cardinality `subtype`/`payload_json` write directly as batched plain byte arrays without unbounded interning. + - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. +3. **Validation, concurrency & atomic publish rules:** + - Input must be strictly ascending by the `build_events` sort key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`; out-of-order and exact-duplicate rows are rejected with the offending `row_index`. + - `known_at_micros >= ts_micros` is enforced (`KnownAtBeforeTs` rejects look-ahead `known_at < ts`); partition year must fall in `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR`; `known_at_source`, `kind`, `subtype`, and `payload_json` must be non-empty after trimming. + - Reuses the shared `parquet_publish` locking, exclusive per-run staging (`part.parquet..tmp`), `File::sync_all()`, live-preserving backup (`part.parquet..bak`), atomic `rename`, and multi-partition rollback (`rollback_published` / `RollbackFailed`) path so partial or failing runs never leave corrupt partitions or transient files behind. +4. **Typed errors (`ParquetEventsError`):** + - `InvalidRowGroupRows` (`row_group_rows == 0`) + - `InvalidZstdLevel { level }` + - `UnsortedInput { row_index, prev_listing_id, prev_ts_micros, listing_id, ts_micros }` + - `DuplicateRow { row_index, listing_id, ts_micros }` + - `KnownAtBeforeTs { row_index, listing_id, ts_micros, known_at_micros }` + - `PartitionYearOutOfRange { row_index, listing_id, ts_micros, year, min_year, max_year }` + - `EmptyKnownAtSource { row_index, listing_id, ts_micros }` + - `EmptyKind { row_index, listing_id, ts_micros }` + - `EmptySubtype { row_index, listing_id, ts_micros }` + - `EmptyPayloadJson { row_index, listing_id, ts_micros }` + - `LockTimeout { path, waited }` + - `RollbackFailed { cause, failures }` + - `Io { path, source }` + - `Parquet { path, source }` +5. **Measured baseline (`2026-11-28`):** + - Command: `cargo run --release -p curate-etl --offline -- bench-parquet-events` + - Input: `rows=500000`, `listings=5000`, `avg_raw_row_bytes=243.6` (11 UTC years `2015..=2025`, ~98.5% filings / ~1.5% linked & lagged earnings) + - Output: `files=11`, `row_groups=11`, `bytes=13831862`, `read_back_rows=500000` + - Perf: `elapsed=548.08 ms`, `throughput=912273 rows/s`, `write=24.07 MB/s`, `size=27.66 bytes/row`, `compression=8.81x` + +## `fx_1d` Parquet Writer (`M1.2l`) + +`write_fx_1d_dataset` (`src/parquet_fx.rs`) streams strictly ascending `(pair, session_date)` `Fx1dParquetRow` records (with zero-allocation `Fx1dParquetRow::from_fx_row(&Fx1dRow, ts_micros, known_at_micros)` construction from `build_fx_1d`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A). + +1. **Exact 9-column contract schema (`fx_1d_parquet_schema`):** + - `pair` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded) + - `session_date` (`INT32`, `REQUIRED`, `DATE`) + - `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + - `open`, `high`, `low`, `close` (`DOUBLE`, `REQUIRED`) + - `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded) + - `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +2. **Layout, compression & streaming:** + - Writes `/fx_1d/part.parquet` (unpartitioned). + - Empty input returns `Ok(Fx1dWriteStats::default())` without creating `/fx_1d` and without modifying or removing any pre-existing `part.parquet`. + - Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `Fx1dWriteOptions::zstd_level`). + - Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `Fx1dWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with string interning for `pair` and `source` and reused buffers across row groups), flushing and clearing on every row-group boundary. + - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. +3. **Validation, concurrency & atomic publish rules:** + - Caller supplies `ts_micros` and `known_at_micros` (FX timestamp derivation policy belongs to the Mongo-streaming wiring task). + - Every streamed row is validated before publication: `pair` and `source` must be non-empty after trimming; every OHLC value must be finite and `> 0.0` with `high >= low` and `open`, `close` inside `[low, high]`; `ts_micros` must fall inside the UTC day `[session_date * 86_400_000_000, +1 day)` (computed in `i128` to avoid overflow on pre-1970 or extreme `i32` dates); `known_at_micros >= ts_micros` is enforced; and input must be strictly ascending and unique by `(pair, session_date)`. + - Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `/fx_1d` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet..tmp`), flush, and `File::sync_all()`; pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`. +4. **Typed errors (`ParquetFxError`):** + - `InvalidRowGroupRows` (`row_group_rows == 0`) + - `InvalidZstdLevel { level }` + - `UnsortedInput { prev_pair, prev_session_date, pair, session_date }` + - `DuplicateKey { pair, session_date }` + - `EmptyPair { session_date }` + - `EmptySource { pair, session_date }` + - `InvalidOhlc { pair, session_date, open, high, low, close }` + - `InconsistentOhlc { pair, session_date, open, high, low, close }` + - `TsOutsideSessionDate { pair, session_date, ts_micros }` + - `KnownAtBeforeTs { pair, session_date, ts_micros, known_at_micros }` + - `LockTimeout { path, waited }` + - `RollbackFailed { cause, failures }` + - `Io { path, source }` + - `Parquet { path, source }` +5. **Measured baseline (`2026-11-28`):** + - Command: `cargo run --release -p curate-etl --offline -- bench-parquet-fx` + - Input: `rows=1000000`, `pairs=80`, `raw_row_bytes=70` (weekday dates `1971..=2026`, mixing `eod_cad_forex` and `te_usdcad`) + - Output: `files=1`, `row_groups=1`, `bytes=22102946`, `read_back_rows=1000000` + - Perf: `elapsed=228.82 ms`, `throughput=4370208 rows/s`, `write=92.12 MB/s`, `size=22.10 bytes/row`, `compression=3.17x` + +## `adj_factors` Parquet Writer (`M1.2m`) + +`write_adj_factors_dataset` (`src/parquet_adj.rs`) streams strictly ascending `(listing_id, ex_date)` `AdjFactorsParquetRow` records (with `AdjFactorsParquetRow::from_adj_row(&AdjFactorRow, known_at_micros)` construction from `build_adj_factors`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A). + +1. **Exact 8-column contract schema (`adj_factors_parquet_schema`):** + - `listing_id` (`INT32`, `REQUIRED`) + - `ex_date` (`INT32`, `REQUIRED`, `DATE`) + - `split_factor` (`DOUBLE`, `REQUIRED`) + - `div_cash` (`DOUBLE`, `REQUIRED`) + - `div_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`, dictionary-encoded; `None` on split-only rows) + - `cum_split_factor` (`DOUBLE`, `REQUIRED`) + - `cum_total_factor` (`DOUBLE`, `REQUIRED`) + - `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +2. **Layout, compression & streaming:** + - Writes `/adj_factors/part.parquet` (unpartitioned). + - Empty input returns `Ok(AdjFactorsWriteStats::default())` without creating `/adj_factors` and without modifying or removing any pre-existing `part.parquet`. + - Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `AdjFactorsWriteOptions::zstd_level`). + - Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `AdjFactorsWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with interned optional `div_currency` streamed in 4,096-row batches and reused buffers across row groups), flushing and clearing on every row-group boundary. + - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. +3. **Validation, concurrency & atomic publish rules:** + - Caller supplies `known_at_micros` without restricting it against `ex_date` (declared dates typically precede `ex_date`, while fallbacks/late notices can fall on or after `ex_date`; timestamp derivation policy belongs to the Mongo-streaming wiring task). + - Every streamed row is validated before publication: `ex_date` calendar year must fall in `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR` (`1900..=2200`); `split_factor`, `cum_split_factor`, and `cum_total_factor` must be finite and `> 0.0`; `div_cash` must be finite and `>= 0.0`; `div_currency` must be `Some(non-empty)` whenever `div_cash > 0.0` and never empty/whitespace when `Some`; and input must be strictly ascending and unique by `(listing_id, ex_date)`. + - Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `/adj_factors` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet..tmp`), flush, and `File::sync_all()`; pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`. +4. **Typed errors (`ParquetAdjError`):** + - `InvalidRowGroupRows` (`row_group_rows == 0`) + - `InvalidZstdLevel { level }` + - `UnsortedInput { prev_listing_id, prev_ex_date, listing_id, ex_date }` + - `DuplicateKey { listing_id, ex_date }` + - `ExDateOutOfRange { listing_id, ex_date, year, min_year, max_year }` + - `InvalidSplitFactor { listing_id, ex_date, value }` + - `InvalidDivCash { listing_id, ex_date, value }` + - `InvalidDivCurrency { listing_id, ex_date }` + - `InvalidCumSplitFactor { listing_id, ex_date, value }` + - `InvalidCumTotalFactor { listing_id, ex_date, value }` + - `LockTimeout { path, waited }` + - `RollbackFailed { cause, failures }` + - `Io { path, source }` + - `Parquet { path, source }` +5. **Measured baseline (`2026-11-28`):** + - Command: `cargo run --release -p curate-etl --offline -- bench-parquet-adj` + - Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=51` (weekday dates `1990..=2025`, ~4% split-only with `None` `div_currency`, ~95% USD/CAD dividends, ~1% combined) + - Output: `files=1`, `row_groups=1`, `bytes=2595560`, `read_back_rows=1000000` + - Perf: `elapsed=106.01 ms`, `throughput=9432939 rows/s`, `write=23.35 MB/s`, `size=2.60 bytes/row`, `compression=19.65x` + +## `corporate_actions` Parquet Writer (`M1.2n`) + +`write_corporate_actions_dataset` (`src/parquet_corporate_actions.rs`) streams non-decreasing `(listing_id, ex_date, kind)` `CorporateActionsParquetRow` records (with `CorporateActionsParquetRow::from_corporate_action_row(&CorporateActionRow, known_at_micros)` construction from `build_corporate_actions`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A). + +1. **Exact 11-column contract schema (`corporate_actions_parquet_schema`):** + - `listing_id` (`INT32`, `REQUIRED`) + - `ex_date` (`INT32`, `REQUIRED`, `DATE`) + - `declared_date` (`INT32`, `OPTIONAL`, `DATE`) + - `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded: `"split"` | `"dividend"` | `"otc_delist_transfer"` | `"delisting"`) + - `ratio` (`DOUBLE`, `OPTIONAL`) + - `cash_amount` (`DOUBLE`, `OPTIONAL`) + - `currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`, dictionary-encoded) + - `successor_listing_id` (`INT32`, `OPTIONAL`) + - `terminal_return` (`DOUBLE`, `OPTIONAL`) + - `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + - `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded: `"declared_date"` | `"ex_date_fallback"` | `"delist_date"`) +2. **Layout, compression & streaming:** + - Writes `/corporate_actions/part.parquet` (unpartitioned). + - Empty input returns `Ok(CorporateActionsWriteStats::default())` without creating `/corporate_actions` and without modifying or removing any pre-existing `part.parquet`. + - Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `CorporateActionsWriteOptions::zstd_level`). + - Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `CorporateActionsWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with interned `kind`, `currency`, and `known_at_source` streamed in 4,096-row batches and reused buffers across row groups), flushing and clearing on every row-group boundary. + - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. +3. **Validation, ordering, concurrency & atomic publish rules:** + - Caller supplies `known_at_micros` (date→timestamp derivation policy belongs to the later Mongo-streaming wiring task). + - Input must be non-decreasing on `(listing_id, ex_date, kind)` using `CorporateActionKind`'s `Ord` (`Split < Dividend < OtcDelistTransfer < Delisting`), matching `build_corporate_actions` output without re-sorting; multiple rows may share the same key (e.g. regular + special dividend on the same ex-date). + - Every streamed row is validated before publication: `ex_date` and optional `declared_date` years must fall in `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR` (`1900..=2200`); `split` requires `ratio` finite `> 0.0`; `dividend` requires `cash_amount` finite `> 0.0` and `currency` non-empty after trimming; `otc_delist_transfer` requires `successor_listing_id != listing_id`; `delisting` requires `terminal_return` finite in `[-1.0, 0.0]`; all fields belonging to other kinds must be `None`; and `known_at_source` must match the kind (`delist_date` only for delisting kinds, `declared_date` requires `declared_date.is_some()`). + - Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `/corporate_actions` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet..tmp`), flush, and `File::sync_all()`; pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`. +4. **Typed errors (`ParquetCorporateActionsError`):** + - `InvalidRowGroupRows` (`row_group_rows == 0`) + - `InvalidZstdLevel { level }` + - `UnsortedInput { prev_listing_id, prev_ex_date, prev_kind, listing_id, ex_date, kind }` + - `ExDateOutOfRange { listing_id, ex_date, year, min_year, max_year }` + - `DeclaredDateOutOfRange { listing_id, ex_date, declared_date, year, min_year, max_year }` + - `InvalidRatio { listing_id, ex_date, value }` + - `InvalidCashAmount { listing_id, ex_date, value }` + - `InvalidCurrency { listing_id, ex_date }` + - `InvalidSuccessorListingId { listing_id, ex_date, successor_listing_id }` + - `InvalidTerminalReturn { listing_id, ex_date, value }` + - `ForbiddenFieldForKind { listing_id, ex_date, kind, field }` + - `InconsistentKnownAtSource { listing_id, ex_date, kind, known_at_source, declared_date }` + - `LockTimeout { path, waited }` + - `RollbackFailed { cause, failures }` + - `Io { path, source }` + - `Parquet { path, source }` +5. **Measured baseline (`2026-11-28`):** + - Command: `cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions` + - Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=72` (weekday dates `1990..=2025`, ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes) + - Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000` + - Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x` + +## `eodPrices` Raw BSON Decoder (`M1.2o`) + +`decode_eod_price_doc`, `decode_eod_price_bytes`, `iter_raw_bson_docs`, and `decode_eod_price_buffer` (`src/bson_eod_prices.rs`) decode raw MongoDB `eodPrices` BSON documents in a single forward pass over `RawDocument::iter_elements()` without allocating a `String` or `bson::Document` per row. + +1. **Pinned dependency & driver compatibility:** + - Adds `bson = { version = "=3.1.0", default-features = false, features = ["compat-3-0-0"] }` (MSRV `1.81+`, tested against workspace `rustc 1.88.0`, no `serde` derive). + - Paired with the official `mongodb` `3.x` Rust driver using `features = ["bson-3"]` so the upcoming MongoDB cursor task reuses the same `bson` 3.x crate without pulling in a duplicate `bson` major version. +2. **Empirical field contract & cited sources:** + - Grounded in `apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts:4-56`, `apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts:105-157`, `apps/stock/data-pipeline/src/normalization/bar-spans.ts:12-18`, and `design/DATA-CONTRACTS.md` §1 (line 13). + - `eodSearchCode`: BSON UTF-8 `String` (borrowed verbatim as `&str`; empty or whitespace-only is rejected). + - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (converted to UTC epoch days via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps map accurately). + - `open`, `high`, `low`, `close`, `volume`: every BSON numeric representation MongoDB can store for a JS number (`Double`, `Int32`, `Int64`); must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). Per `design/DATA-CONTRACTS.md` §1, OHLC is raw and `volume` is retroactively split-adjusted, mapping directly to `EodDailyBar::adj_volume`. + - Unknown extra fields (`_id`, `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `adjusted_close`, `created_at`, `updated_at`, nested objects/arrays, etc.) are skipped without decoding their values. +3. **Zero-allocation key mapping:** + - Decodes into borrowed `RawEodDailyBar<'a>` and converts to `EodDailyBar` via `into_eod_daily_bar(|code, date| ...)` or `try_into_eod_daily_bar(|code, date| mapping.resolve("eod", code, date))`, avoiding per-row `String` allocations across 846M documents. +4. **Typed errors & stream skip/accounting policy:** + - Never panics on untrusted input. `BsonEodPriceError` names the offending field on every field-level error: `MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, `TruncatedDocument`, `CorruptDocumentLength`, and `CorruptBson`. + - `iter_raw_bson_docs` walks concatenated 4-byte little-endian length-prefixed BSON documents (wire / `mongodump` layout), terminating cleanly on unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) while skipping validly framed corrupt documents (`CorruptBson`). + - `decode_eod_price_buffer` reports and skips per-document errors without aborting the stream, reconciling `BsonEodDecodeStats` with `decoded + rejected_total() == docs_in`. +5. **Deferred out of `M1.2o`:** + - MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `qmSplits`, `qmDividends`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`). + ## Local Benchmarks ### `bench-split` @@ -340,14 +583,261 @@ Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-pa - Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000` - Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` +### `bench-parquet-shorts` + +Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `ShortsParquetRow` rows across `12,500` listings on semi-monthly dates (`2017-04-15..=2026-04-30`) with CIRO `+4` business-day `17:00 ET` `known_at` timestamps, writing `shorts/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory: + +```bash +cargo run --release -p curate-etl --offline -- bench-parquet-shorts [rows] +``` + +Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-shorts` + +- Input: `rows=1000000`, `listings=12500`, `raw_row_bytes=50` +- Output: `files=1`, `row_groups=1`, `bytes=6741816`, `read_back_rows=1000000` +- Perf: `elapsed=106.79 ms`, `throughput=9364116 rows/s`, `write=60.21 MB/s`, `size=6.74 bytes/row`, `compression=7.42x` + +### `bench-parquet-events` + +Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `500,000` sorted `EventsParquetRow` rows (~98.5% filings, ~1.5% linked/lagged earnings with ~150–300 byte `payload_json`) across `5,000` listings and 11 UTC years (`2015..=2025`), writing `events/year=YYYY/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying Parquet footer row counts across all 11 files, and deleting the temp directory: + +```bash +cargo run --release -p curate-etl --offline -- bench-parquet-events [rows] +``` + +Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-events` + +- Input: `rows=500000`, `listings=5000`, `avg_raw_row_bytes=243.6` +- Output: `files=11`, `row_groups=11`, `bytes=13831862`, `read_back_rows=500000` +- Perf: `elapsed=548.08 ms`, `throughput=912273 rows/s`, `write=24.07 MB/s`, `size=27.66 bytes/row`, `compression=8.81x` + +### `bench-parquet-fx` + +Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `Fx1dParquetRow` rows across `80` currency pairs on weekday dates (`1971..=2026`, mixing `eod_cad_forex` and `te_usdcad`), writing `fx_1d/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory: + +```bash +cargo run --release -p curate-etl --offline -- bench-parquet-fx [rows] +``` + +Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-fx` + +- Input: `rows=1000000`, `pairs=80`, `raw_row_bytes=70` +- Output: `files=1`, `row_groups=1`, `bytes=22102946`, `read_back_rows=1000000` +- Perf: `elapsed=228.82 ms`, `throughput=4370208 rows/s`, `write=92.12 MB/s`, `size=22.10 bytes/row`, `compression=3.17x` + +### `bench-parquet-adj` + +Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `AdjFactorsParquetRow` rows across `20,000` listings on weekday dates (`1990..=2025`, ~4% split-only with `None` `div_currency`, ~95% USD/CAD dividends, ~1% combined), writing `adj_factors/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory: + +```bash +cargo run --release -p curate-etl --offline -- bench-parquet-adj [rows] +``` + +Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-adj` + +- Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=51` +- Output: `files=1`, `row_groups=1`, `bytes=2595560`, `read_back_rows=1000000` +- Perf: `elapsed=106.01 ms`, `throughput=9432939 rows/s`, `write=23.35 MB/s`, `size=2.60 bytes/row`, `compression=19.65x` + +### `bench-parquet-corporate-actions` + +Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `CorporateActionsParquetRow` rows across `20,000` listings on weekday dates (`1990..=2025`, ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes), writing `corporate_actions/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory: + +```bash +cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions [rows] +``` + +Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions` + +- Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=72` +- Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000` +- Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x` + +### `bench-bson-eod-prices` + +Fixed-seed (`std`-only SplitMix64) zero-copy raw BSON decode benchmark over `1,000,000` realistic synthetic `eodPrices` documents (including `_id`, `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `created_at`, `updated_at`, mixed `Double`/`Int32`/`Int64` numerics, `YYYY-MM-DD` strings + ~5% BSON `DateTime` dates, and ~0.5% deterministic rejected rows) pre-encoded into one contiguous length-prefixed buffer up front, timing decode-only via `decode_eod_price_buffer`: + +```bash +cargo run --release -p curate-etl --offline -- bench-bson-eod-prices [rows] +``` + +Command (`2026-11-28`, two back-to-back runs with identical checksum `0x05af9d2746d1b5e3`): `cargo run --release -p curate-etl --offline -- bench-bson-eod-prices` + +- Input: `rows=1000000`, `bytes=285639152` (~272.4 MiB, ~285.6 bytes/doc) +- Decode: `decoded=995008`, `rejected=4992` (`missing=1985`, `empty=0`, `wrong_type=986`, `malformed_date=1027`, `invalid_number=994`, `corrupt=0`) +- Run 1: `elapsed=221.82 ms`, `throughput=4508210 rows/s`, `scan=1228.07 MB/s`, `latency=221.82 ns/row`, `checksum=0x05af9d2746d1b5e3` +- Run 2: `elapsed=217.38 ms`, `throughput=4600307 rows/s`, `scan=1253.15 MB/s`, `latency=217.38 ns/row`, `checksum=0x05af9d2746d1b5e3` +- Extrapolation to full `846,000,000` `eodPrices` documents on one core (decode-only, excluding MongoDB cursor I/O and Parquet writes): `183.9 s`–`187.7 s` (`3.07`–`3.13 min`). + ## Deferred Follow-Ups (`M1.3+` / `M2`) -This crate currently depends only on `parquet` (Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline once the Cargo cache is populated. Follow-up tasks will add: +This crate currently depends only on `bson` (`=3.1.0`, `default-features = false, features = ["compat-3-0-0"]`) and `parquet` (`=60.2.0`, Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline. Follow-up tasks will add: - `bars_1d` and `fx_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata - `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends -- Zstd Parquet writers for the remaining curated tables (`adj_factors`, `corporate_actions`, `fx_1d`, `events`, `shorts`) and `qmPrices` OHLC cross-check +- `qmPrices` OHLC cross-check - Read-only MongoDB `RawDocumentBuf` streaming cursors (`eodPrices`, `eodIntraday1M`, `qmSplits`) - PostgreSQL I/O preload into `ProviderMappingTable` and rewiring the builders to resolve `(source, source_id, bar_date) -> listing_id: i32` - `rayon` parallel sharding across symbol/date partitions - QuestDB ILP v2 writer for time-series ingestion + +## `bars_1d` Curation Stage (`M1.2p` / `M1.2q`) + +`curate_bars_1d` and `curate_and_write_bars_1d` (`src/curate_bars.rs`) join `build_bars_1d`, `ProviderMappingTable`, listing currency metadata, `session_close::et_session_close_utc_micros`, and `write_bars_1d_dataset` into contract `Bars1dParquetRow` records sorted and unique by `(listing_id, session_date)`. + +1. **Field rules:** + - Calls `build_bars_1d` unchanged (raw OHLC passed through bit-for-bit, `volume = adj_volume / factor` via `SplitTable`, read-only `qmPrices.sharevolume` cross-check with `Bars1dStats` and `mismatch_samples` carried through untouched). + - Resolves `(mapping_source, source_id, session_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run, caching the last `(listing_id, currency)` lookup per run). + - Stamps `ts_micros = known_at_micros = 16:00:00 America/New_York` (`16:00 ET`) converted to UTC microseconds via `session_close::et_session_close_utc_micros` (`21:00 UTC` in EST, `20:00 UTC` in EDT). Across `1976-01-01..=2030-12-31`, `America/New_York` and `America/Toronto` share identical DST rules across all three eras: + - `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. + Early-close half days still use `16:00 ET` (strictly later than the real close, so never look-ahead). + - Sets `vwap = None` and `source = "eod_unadj"` (`BARS_1D_SOURCE_EOD`). +2. **Drop & collision policy (never panics or aborts on bad rows):** + - Strict drop priority per built row: + 1. `dropped_unmapped`: no `provider_mapping` range covers `(mapping_source, source_id, session_date)`. + 2. `dropped_missing_currency`: `listing_id` absent from `listing_currencies` or maps to a blank string. + 3. `dropped_ts_out_of_range`: `session_date` falls outside `session_close::et_session_close_utc_micros`'s `1976-01-01..=2030-12-31` window. The lower bound is deliberately `1976-01-01` because US emergency DST in `1974–1975` diverged from Toronto, so earlier dates drop here rather than guessing. + - After re-sorting in place by `(listing_id, session_date)`, cross-`source_id` collisions on the same `(listing_id, session_date)` collapse to one row when OHLCV is bitwise identical (`listing_collision_collapsed += g - 1`) and drop the entire group when any OHLCV field differs (`listing_collision_dropped += g`). + - Exact conservation invariant in `CurateBars1dStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + dropped_missing_currency + dropped_ts_out_of_range + listing_collision_collapsed + listing_collision_dropped`. + - Typed caller errors: `CurateBarsError` (`Bars(BarsError)`, `EmptyMappingSource`) and `CurateBarsWriteError` (`Curate(CurateBarsError)`, `Parquet(ParquetBarsError)`). + +### `bench-curate-bars` + +Fixed-seed (`std`-only SplitMix64) benchmark over `2,000,000` source-keyed `eodPrices` bars across `2,000` `String` keys per `2,000,000`-row block (`2008..=2025` with unique per-key coprime-stride `(source_id, session_date)` pairs guarded against cursor wrap, plus in-range `1990..=2007`, pre-1976 out-of-range, explicitly injected builder duplicates, date-ranged ticker-reuse/unmapped, missing-currency, and cross-`source_id` collision slices, `2,000` splits per block, and ~50% `qmPrices` partners), separately timing in-memory `curate_bars_1d` and Zstd Parquet `write_bars_1d_dataset` into a temp directory with footer row-count verification and cleanup: + +```bash +cargo run --release -p curate-etl --offline -- bench-curate-bars [rows] +``` + +Command (`2026-11-28`, two back-to-back runs with identical checksum `0x098ac03b74d9899a`): `cargo run --release -p curate-etl --offline -- bench-curate-bars` + +- Input: `rows=2000000`, `qm_rows=995681`, `splits=2000`, `keys=2000` +- Builder: `rows_out=1994014`, `invalid_ohlc=0`, `inconsistent_ohlc=0`, `invalid_vol=0`, `dup_collapsed=1930`, `dup_conflict_dropped=4056` +- Output: `rows_out=1947916` (`97.40%` retained), `listings_out=2000`, `files=36`, `row_groups=36`, `bytes=53241768`, `read_back_rows=1947916` +- Curation stats: `unmapped=17873`, `missing_curr=15129`, `ts_oor=3946`, `pre_2008_rows=39257`, `coll_collapsed=3066`, `coll_dropped=6084`, `mismatch_samples=100` +- Note: 846M-row single-core figures below are linear projections from the measured `2,000,000`-row batch at `97.40%` retention. +- Run 1: + - Stage (in-memory): `elapsed=1164.89 ms`, `throughput=1716906 rows/s`, `latency=582.44 ns/row`, single-core 846M projection `492.7 s` (`8.21 min`), `checksum=0x098ac03b74d9899a` + - Parquet write: `elapsed=698.34 ms`, `throughput=2789371 rows/s` + - Combined (stage → Parquet): `elapsed=1863.22 ms`, `throughput=1073410 rows/s`, single-core 846M projection `788.1 s` (`13.14 min`, projected at batch=`2000000` and `97.40%` retention) +- Run 2: + - Stage (in-memory): `elapsed=1181.40 ms`, `throughput=1692903 rows/s`, `latency=590.70 ns/row`, single-core 846M projection `499.7 s` (`8.33 min`), `checksum=0x098ac03b74d9899a` + - Parquet write: `elapsed=708.69 ms`, `throughput=2748627 rows/s` + - Combined (stage → Parquet): `elapsed=1890.09 ms`, `throughput=1058151 rows/s`, single-core 846M projection `799.5 s` (`13.33 min`, projected at batch=`2000000` and `97.40%` retention) + +## `shorts` Curation Stage (`M1.2r`) + +`curate_shorts` and `curate_and_write_shorts` (`src/curate_shorts.rs`) join `build_shorts`, `ProviderMappingTable`, and `write_shorts_dataset` into contract `ShortsParquetRow` records sorted and unique by `(listing_id, report_date)`. + +1. **Field rules:** + - Calls `build_shorts` unchanged (finite `>= 0.0` `shares_short` validation, non-finite optional `net_change`/`pct_float` sanitization to `None`, `-0.0` normalization, same-`(key, report_date)` deduplication, `+4` Canadian TSX business-day CIRO lag, and `known_at_micros = 17:00:00 America/Toronto` UTC microseconds). + - Resolves `(mapping_source, key, report_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run, since `build_shorts` emits rows sorted by `(key, report_date)`). + - **Point-in-time mapping boundary:** `provider_mapping` is resolved strictly on `report_date` (the reporting period the short position describes), not on `known_at_date` (`+4` TSX business days later). + - Carries `source` through unchanged from `build_shorts` (`SHORTS_SOURCE_CEO = "ceo_shorts"`) as `Cow::Borrowed`. +2. **Drop & collision policy (never panics or aborts on bad rows):** + - Rows whose `(mapping_source, key, report_date)` is not covered by any `provider_mapping` range are dropped into `dropped_unmapped`. + - After re-sorting in place by `(listing_id, report_date)`, cross-`key` collisions on the same `(listing_id, report_date)` collapse to one row when `known_at_micros`, `shares_short`, `net_change`, and `pct_float` are bitwise identical (`listing_collision_collapsed += g - 1`) and drop the entire group when any of those fields differ (`listing_collision_dropped += g`). + - Exact conservation invariant in `CurateShortsStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + listing_collision_collapsed + listing_collision_dropped`. + - Typed caller errors: `CurateShortsError` (`Shorts(ShortsError)`, `EmptyMappingSource`) and `CurateShortsWriteError` (`Curate(CurateShortsError)`, `Parquet(ParquetShortsError)`). A curate error in `curate_and_write_shorts` returns before invoking `write_shorts_dataset`, leaving `out_dir` untouched. + +### `bench-curate-shorts` + +Fixed-seed (`std`-only SplitMix64) benchmark over `2,000,000` source-keyed `ceoShorts` reports across `12,500` `String` keys per `1,000,000`-row block (`25,000` keys at `2,000,000` rows over the `218` semi-monthly dates `2017-04-15..=2026-04-30`, with per-key coprime-stride cursors guarded against exhaustion, date-ranged ticker reuse with an interior gap, unmapped keys, explicit builder duplicates, invalid `shares_short`/non-finite optional field slices, and identical/conflicting cross-key collisions), separately timing in-memory `curate_shorts` and Zstd Parquet `write_shorts_dataset` into a temp directory with footer row-count verification and cleanup: + +```bash +cargo run --release -p curate-etl --offline -- bench-curate-shorts [rows] +``` + +Command (`2026-11-28`, two back-to-back runs with identical checksum `0xde3b3bd654c65ebe`): `cargo run --release -p curate-etl --offline -- bench-curate-shorts` + +- Input: `rows=2000000`, `keys=25000` +- Builder: `rows_out=1990174`, `invalid_shares=4005`, `nulled_net_change=1953`, `nulled_pct_float=1956`, `dup_collapsed=1937`, `dup_conflict_dropped=3884` +- Output: `rows_out=1936876` (`96.84%` retained), `listings_out=25000`, `files=1`, `row_groups=2`, `bytes=17721340`, `read_back_rows=1936876` +- Curation stats: `unmapped=43484`, `coll_collapsed=3410`, `coll_dropped=6404` +- Run 1: + - Stage (in-memory): `elapsed=1091.40 ms`, `throughput=1832514 rows/s`, `latency=545.70 ns/row`, `checksum=0xde3b3bd654c65ebe` + - Parquet write: `elapsed=224.75 ms`, `throughput=8617888 rows/s` + - Combined (stage → Parquet): `elapsed=1316.15 ms`, `throughput=1519586 rows/s` +- Run 2: + - Stage (in-memory): `elapsed=1002.51 ms`, `throughput=1994998 rows/s`, `latency=501.25 ns/row`, `checksum=0xde3b3bd654c65ebe` + - Parquet write: `elapsed=228.03 ms`, `throughput=8494083 rows/s` + - Combined (stage → Parquet): `elapsed=1230.53 ms`, `throughput=1625311 rows/s` + +## `events` Curation Stage (`M1.2s`) + +`curate_events` and `curate_and_write_events` (`src/curate_events.rs`) join `build_events`, `ProviderMappingTable`, and `write_events_dataset` into contract `EventsParquetRow` records strictly ascending in the 7-field writer sort key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`. + +1. **Field & Point-in-Time rules:** + - Runs `build_events` unchanged on source keys so same-day earnings↔filing linking (`8-K` / `News release`), form classification, timestamp parsing, conservative `16:05 ET` fallback, and per-key deduplication happen before `provider_mapping` resolution. + - Internally uses the crate-private `build_events_with_dates` helper (zero overhead on public `build_events`, unchanged `EventsParquetRow` schema) to carry each row's already-parsed Eastern local calendar date (`ParsedFilingTime::et_date` for filings; `QmEarning::report_date` for earnings) alongside the row. + - Resolves `(mapping_source, key, event_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run) strictly on that Eastern local calendar date—covering pre-2008 historical filings and late-evening EST/EDT filings whose UTC date has rolled over—never on UTC date or `known_at` date. + - Moves `subtype` and `payload_json` without cloning, keeps `known_at_source` and `kind` as `Cow::Borrowed`, and frees builder rows before re-sorting. +2. **Drop & collapse policy (never panics or aborts on bad rows):** + - Rows whose `(mapping_source, key, event_date)` is not covered by any `provider_mapping` range are dropped into `dropped_unmapped`. + - After re-sorting in place by the 7-field writer key, cross-`key` rows mapping to the same `listing_id` that are identical on all seven fields collapse to one row (`listing_duplicate_collapsed`), while rows differing in any single field are all kept. + - Exact conservation invariants in `CurateEventsStats`: `rows_in == builder.rows_out`, `rows_in == rows_out + dropped_unmapped + listing_duplicate_collapsed`, and `rows_out == filings_out + earnings_out`. + - Typed caller errors: `CurateEventsError::EmptyMappingSource` and `CurateEventsWriteError` (`Curate(CurateEventsError)`, `Parquet(ParquetEventsError)`). A curate error in `curate_and_write_events` returns before invoking `write_events_dataset`, leaving `out_dir` untouched. + +### `bench-curate-events` + +Fixed-seed (`std`-only SplitMix64) benchmark over `500,000` source-keyed rows (~98.5% `qmFilings`, ~1.5% `qmEarnings`) across `20,000` `String` source keys (`2003-01-01..=2026-04-30`, covering single-range keys, multi-range ticker reuse with an H2-2021 gap, alias keys for cross-key duplicates, unmapped keys, pre-2008 filings, late-evening ET rollovers, linked/unlinked earnings, and builder skips/duplicates), separately timing in-memory `curate_events` and Zstd Parquet `write_events_dataset` into a temp directory with footer row-count verification across all year partitions and cleanup: + +```bash +cargo run --release -p curate-etl --offline -- bench-curate-events [rows] +``` + +Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0a1b7ace6344e408`): `cargo run --release -p curate-etl --offline -- bench-curate-events` + +- Input: `rows=500000`, `filings=492500`, `earnings=7500`, `keys=20000` +- Builder: `rows_out=493755`, `filings_out=487053`, `earnings_out=6702`, `malformed_ts=1011`, `unknown_zone=960`, `invalid_dt=1466`, `filing_dup=2010`, `linked=2556`, `lagged_1605=4146`, `earnings_oor=38`, `earnings_dup=102`, `earnings_conflict=658` +- Output: `rows_out=484402` (`96.88%` retained), `filings_out=477818`, `earnings_out=6584`, `listings_out=19997`, `files=24`, `row_groups=24`, `bytes=16057718`, `read_back_rows=484402` +- Curation stats: `unmapped=7713`, `dup_collapsed=1640` +- Run 1: + - Stage (in-memory): `elapsed=551.10 ms`, `throughput=907273 rows/s`, `latency=1102.20 ns/row`, `checksum=0x0a1b7ace6344e408` + - Parquet write: `elapsed=752.90 ms`, `throughput=643382 rows/s` + - Combined (stage → Parquet): `elapsed=1304.00 ms`, `throughput=383435 rows/s` +- Run 2: + - Stage (in-memory): `elapsed=589.24 ms`, `throughput=848550 rows/s`, `latency=1178.48 ns/row`, `checksum=0x0a1b7ace6344e408` + - Parquet write: `elapsed=682.82 ms`, `throughput=709419 rows/s` + - Combined (stage → Parquet): `elapsed=1272.06 ms`, `throughput=393065 rows/s` + +## `fx_1d` Curation Stage (`M1.2t`) + +`curate_fx_1d` and `curate_and_write_fx_1d` (`src/curate_fx.rs`) join `build_fx_1d` and `write_fx_1d_dataset` into contract `Fx1dParquetRow` records sorted and unique by `session_date` (no `provider_mapping` lookup is needed because FX rows are keyed by `pair = "USDCAD"`, not `listing_id`). + +1. **Field & timestamp rules:** + - Calls `build_fx_1d` unchanged (`CAD.FOREX` takes precedence on overlapping dates, `teMarketData.USDCAD` fills interior gaps and the post-EOD tail, the read-only 1% overlap cross-check runs untouched, and all `Fx1dStats` counters are carried through unchanged). + - Maps every `Fx1dRow` via `Fx1dParquetRow::from_fx_row` with zero per-row heap allocation (`pair = "USDCAD"` and `source` ∈ `{"eod_cad_forex", "te_usdcad"}` stay `Cow::Borrowed`), preserving the strictly ascending, unique `session_date` order. + - **Conservative no-look-ahead timestamp rule:** stamps every row with `ts_micros = known_at_micros = (session_date + 1) * FX_1D_MICROS_PER_DAY - 1` (`23:59:59.999999 UTC` of `session_date`, offset `FX_1D_TS_OFFSET_MICROS_FROM_DAY_START = 86_399_999_999` from UTC midnight) via `fx_1d_utc_day_end_micros`. Neither `CAD.FOREX` nor `teMarketData.USDCAD` documents its daily FX cutoff, so the last microsecond of the UTC day is the conservative no-look-ahead choice (same-day `16:00 ET` equity close signals resolve to the prior UTC day's bar), satisfies `parquet_fx`'s `TsOutsideSessionDate` and `KnownAtBeforeTs` checks, and requires no DST table for `1971–1975` (outside `session_close.rs`'s `1976–2030` window). +2. **Accounting & error handling:** + - Exact conservation invariant in `CurateFx1dStats`: `rows_in == builder.rows_out == rows_out`, with `stats.builder` bit-identical to calling `build_fx_1d` directly. + - Checked `i64` arithmetic: any `session_date` whose UTC day-end microsecond timestamp overflows `i64` (`session_date >= 106_751_991` or `session_date <= -106_751_993`, including `i32::MAX` / `i32::MIN`) returns `CurateFxError::SessionDateOutOfRange { session_date }` without panicking or wrapping. + - `curate_and_write_fx_1d` runs `curate_fx_1d` before invoking `write_fx_1d_dataset`, so any `CurateFxError` leaves `out_dir` untouched (and surfaces via `CurateFxWriteError::{Curate, Parquet}`). +3. **Still out of scope:** + - Live MongoDB cursor / BSON decoders for `CAD.FOREX` and `teMarketData.USDCAD` documents + - Intraday `fx_1m` curation + +### `bench-curate-fx` + +Fixed-seed (`std`-only SplitMix64) benchmark over `20,000` (default; real dataset is ~15k rows) or `[rows]` daily USD/CAD bars (~80% `CAD.FOREX`, ~20% `teMarketData.USDCAD` with overlap window, interior EOD gaps, post-EOD TE tail, and injected invalid/inconsistent/duplicate rows), separately timing in-memory `curate_fx_1d` and Zstd Parquet `write_fx_1d_dataset` into a temp directory with footer row-count verification and cleanup: + +```bash +cargo run --release -p curate-etl --offline -- bench-curate-fx [rows] +``` + +1. Default run (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-curate-fx` + - Input: `rows=20000`, `eod_rows=16000`, `te_rows=4000` + - Builder: `rows_out=17180` (`eod_out=15341`, `te_out=1839`, `eod_invalid=164`, `eod_inconsistent=178`, `eod_dup_collapsed=145`, `eod_dup_conflict=172`, `te_invalid=18`, `te_inconsistent=26`, `te_dup_collapsed=27`, `te_dup_conflict=14`) + - Stage (in-memory): `rows_out=17180` (`85.90%` retained), `elapsed=1.070 ms`, `throughput=18683801 rows/s`, `latency=53.52 ns/row`, `checksum=0x298f47e68cdf7022` + - Parquet write: `files=1`, `row_groups=1`, `bytes=714498`, `read_back_rows=17180`, `elapsed=16.691 ms`, `throughput=1029303 rows/s` + - Combined (stage → Parquet): `elapsed=17.761 ms`, `throughput=1126041 rows/s` + - Overlap: `te_superseded=2076`, `checked=2076`, `within_tol=1979`, `mismatched=97`, `max_overlap_rel=0.025000` +2. 1M-row run (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-curate-fx 1000000` + - Input: `rows=1000000`, `eod_rows=800000`, `te_rows=200000` + - Builder: `rows_out=859916` (`eod_out=767923`, `te_out=91993`, `eod_invalid=8245`, `eod_inconsistent=8035`, `eod_dup_collapsed=7794`, `eod_dup_conflict=8003`, `te_invalid=1214`, `te_inconsistent=1198`, `te_dup_collapsed=1213`, `te_dup_conflict=1213`) + - Stage (in-memory): `rows_out=859916` (`85.99%` retained), `elapsed=59.652 ms`, `throughput=16763900 rows/s`, `latency=59.65 ns/row`, `checksum=0x2a2f2665b32d8ae0` + - Parquet write: `files=1`, `row_groups=1`, `bytes=27440094`, `read_back_rows=859916`, `elapsed=215.804 ms`, `throughput=3984706 rows/s` + - Combined (stage → Parquet): `elapsed=275.456 ms`, `throughput=3630342 rows/s` + - Overlap: `te_superseded=103169`, `checked=103169`, `within_tol=97958`, `mismatched=5211`, `max_overlap_rel=0.025000` diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 4ab31613..02b8bbd7 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -8,22 +8,50 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use std::time::Instant; +use bson::oid::ObjectId; +use bson::raw::{cstr, RawDocumentBuf}; +use bson::DateTime; use parquet::errors::ParquetError; use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; +use crate::bson_eod_prices::{decode_eod_price_buffer, BsonEodDecodeStats}; use crate::corporate_actions::{ - build_corporate_actions, CorporateActionError, CorporateActionsStats, DelistingOutcomeEvent, - DividendActionEvent, SplitActionEvent, + build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats, + DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent, +}; +use crate::events::{ + build_events, classify_form_type, encode_earnings_payload_json, encode_filing_payload_json, + EventsStats, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar, FxSource, FX_PAIR_USDCAD}; +use crate::parquet_adj::{ + write_adj_factors_dataset, AdjFactorsParquetRow, AdjFactorsWriteOptions, ParquetAdjError, }; -use crate::events::{build_events, EventsStats, QmEarning, QmFiling}; -use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar}; use crate::parquet_bars::{ write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, ParquetBarsError, }; +use crate::parquet_corporate_actions::{ + write_corporate_actions_dataset, CorporateActionsParquetRow, CorporateActionsWriteOptions, + ParquetCorporateActionsError, +}; +use crate::parquet_events::{ + write_events_dataset, EventsParquetRow, EventsWriteOptions, ParquetEventsError, +}; +use crate::parquet_fx::{ + write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, ParquetFxError, +}; +use crate::parquet_shorts::{ + write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, +}; use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable}; -use crate::shorts::{build_shorts, epoch_days_to_ymd, CeoShortReport, ShortsError, ShortsStats}; +use crate::shorts::{ + add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, CeoShortReport, + ShortsError, ShortsStats, SHORTS_DISSEMINATION_HOUR_ET, SHORTS_DISSEMINATION_MINUTE_ET, + SHORTS_LAG_BUSINESS_DAYS, SHORTS_SOURCE_CEO, +}; use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable}; pub const DEFAULT_BENCH_ROWS: usize = 10_000_000; @@ -37,11 +65,30 @@ pub const DEFAULT_EVENTS_BENCH_ROWS: usize = 500_000; pub const DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS: usize = 10_000_000; pub const DEFAULT_PARQUET_BARS_BENCH_ROWS: usize = 5_000_000; pub const PARQUET_BARS_RAW_ROW_BYTES: usize = 84; +pub const DEFAULT_PARQUET_SHORTS_BENCH_ROWS: usize = 1_000_000; +pub const PARQUET_SHORTS_RAW_ROW_BYTES: usize = 50; +pub const DEFAULT_PARQUET_EVENTS_BENCH_ROWS: usize = 500_000; +pub const DEFAULT_PARQUET_FX_BENCH_ROWS: usize = 1_000_000; +pub const PARQUET_FX_RAW_ROW_BYTES: usize = 70; +pub const DEFAULT_PARQUET_ADJ_BENCH_ROWS: usize = 1_000_000; +pub const PARQUET_ADJ_RAW_ROW_BYTES: usize = 51; +pub const DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS: usize = 1_000_000; +/// Uncompressed logical row size estimate for `corporate_actions/part.parquet` (11 columns): +/// `listing_id` (4) + `ex_date` (4) + `declared_date` (4) + `kind` (~8) + `ratio` (8) +/// + `cash_amount` (8) + `currency` (3) + `successor_listing_id` (4) + `terminal_return` (8) +/// + `known_at` (8) + `known_at_source` (~13) = 72 bytes. +pub const PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES: usize = 72; +pub const DEFAULT_BSON_EOD_PRICES_BENCH_ROWS: usize = 1_000_000; pub const BENCH_KEY_COUNT: usize = 20_000; pub const BENCH_EVENT_COUNT: usize = 19_000; pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000; const SHORTS_BENCH_KEY_COUNT: usize = 12_500; const PARQUET_BARS_BENCH_BASE_LISTINGS: usize = 2_000; +const PARQUET_SHORTS_BENCH_BASE_LISTINGS: usize = 12_500; +const PARQUET_EVENTS_BENCH_BASE_LISTINGS: usize = 5_000; +const PARQUET_FX_BENCH_BASE_PAIRS: usize = 80; +const PARQUET_ADJ_BENCH_BASE_LISTINGS: usize = 20_000; +const PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS: usize = 20_000; const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57; const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70; @@ -52,6 +99,12 @@ const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500; const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500; const PROVIDER_MAPPING_BENCH_SEED: u64 = 0x570C_4B07_9407_1D00; const PARQUET_BARS_BENCH_SEED: u64 = 0x570C_4B07_9A49_BA45; +const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404; +const PARQUET_EVENTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_E7E4; +const PARQUET_FX_BENCH_SEED: u64 = 0x570C_4B07_9A49_F81D; +const PARQUET_ADJ_BENCH_SEED: u64 = 0x570C_4B07_9A49_AD7F; +const BSON_EOD_PRICES_BENCH_SEED: u64 = 0x570C_4B07_B504_E0D1; +const PARQUET_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_9A49_C049; const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05]; /// Deterministic SplitMix64 generator (zero external dependencies). @@ -661,37 +714,8 @@ fn next_weekday(date: i32) -> i32 { } } -/// Runs the fixed-seed `build_fx_1d` + [`fx_rate_on_or_before`] benchmark for `rows` total daily -/// FX rows across `CAD.FOREX` (~80%) and `teMarketData.USDCAD` (~20%). -/// -/// Generates deterministic USD/CAD bars with an overlap window, interior EOD gaps, a post-EOD TE -/// tail, small shares of invalid/inconsistent/identical-duplicate/conflicting-duplicate rows, and -/// ~5% intentional overlap mismatches. Shuffles both inputs deterministically, times -/// [`build_fx_1d`], then times [`DEFAULT_FX_BENCH_LOOKUPS`] (`1_000_000`, or `0` when `rows == 0`) -/// zero-allocation [`fx_rate_on_or_before`] lookups. -pub fn run_fx_benchmark(rows: usize) -> FxBenchReport { - if rows == 0 { - let built = build_fx_1d(&[], &[]); - return FxBenchReport { - rows: 0, - eod_rows_in: 0, - te_rows_in: 0, - rows_out: 0, - build_elapsed_ms: 0.0, - build_rows_per_sec: 0.0, - build_ns_per_row: 0.0, - lookups: 0, - lookup_hits: 0, - lookup_elapsed_ms: 0.0, - lookups_per_sec: 0.0, - ns_per_lookup: 0.0, - checksum: 0, - stats: built.stats, - }; - } - +fn generate_fx_bench_inputs(rows: usize, rng: &mut SplitMix64) -> (Vec, Vec) { let base_date = ymd_to_epoch_days(1971, 1, 4).unwrap_or(368); - let mut rng = SplitMix64::new(FX_BENCH_SEED); let te_target = rows / 5; let eod_target = rows - te_target; @@ -885,8 +909,44 @@ pub fn run_fx_benchmark(rows: usize) -> FxBenchReport { }); } - shuffle_slice(&mut eod, &mut rng); - shuffle_slice(&mut te, &mut rng); + shuffle_slice(&mut eod, rng); + shuffle_slice(&mut te, rng); + + (eod, te) +} + +/// Runs the fixed-seed `build_fx_1d` + [`fx_rate_on_or_before`] benchmark for `rows` total daily +/// FX rows across `CAD.FOREX` (~80%) and `teMarketData.USDCAD` (~20%). +/// +/// Generates deterministic USD/CAD bars with an overlap window, interior EOD gaps, a post-EOD TE +/// tail, small shares of invalid/inconsistent/identical-duplicate/conflicting-duplicate rows, and +/// ~5% intentional overlap mismatches. Shuffles both inputs deterministically, times +/// [`build_fx_1d`], then times [`DEFAULT_FX_BENCH_LOOKUPS`] (`1_000_000`, or `0` when `rows == 0`) +/// zero-allocation [`fx_rate_on_or_before`] lookups. +pub fn run_fx_benchmark(rows: usize) -> FxBenchReport { + if rows == 0 { + let built = build_fx_1d(&[], &[]); + return FxBenchReport { + rows: 0, + eod_rows_in: 0, + te_rows_in: 0, + rows_out: 0, + build_elapsed_ms: 0.0, + build_rows_per_sec: 0.0, + build_ns_per_row: 0.0, + lookups: 0, + lookup_hits: 0, + lookup_elapsed_ms: 0.0, + lookups_per_sec: 0.0, + ns_per_lookup: 0.0, + checksum: 0, + stats: built.stats, + }; + } + + let base_date = ymd_to_epoch_days(1971, 1, 4).unwrap_or(368); + let mut rng = SplitMix64::new(FX_BENCH_SEED); + let (eod, te) = generate_fx_bench_inputs(rows, &mut rng); let eod_rows_in = eod.len(); let te_rows_in = te.len(); @@ -1636,31 +1696,62 @@ struct BenchTempDir { } impl BenchTempDir { - fn new_in(base: &Path) -> Result { + fn new_in_with_prefix(base: &Path, prefix: &str) -> Result { let pid = std::process::id(); for _ in 0..1024 { let seq = BENCH_TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let path = base.join(format!("curate-etl-bench-pq-bars-{pid}-{seq}")); + let path = base.join(format!("{prefix}-{pid}-{seq}")); match fs::create_dir(&path) { Ok(()) => return Ok(Self { path }), Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, - Err(source) => { - return Err(ParquetBarsError::Io { path, source }); - } + Err(source) => return Err((path, source)), } } - Err(ParquetBarsError::Io { - path: base.to_path_buf(), - source: io::Error::new( + Err(( + base.to_path_buf(), + io::Error::new( io::ErrorKind::AlreadyExists, "exhausted unique benchmark temp directory names", ), - }) + )) + } + + fn new_in(base: &Path) -> Result { + Self::new_in_with_prefix(base, "curate-etl-bench-pq-bars") + .map_err(|(path, source)| ParquetBarsError::Io { path, source }) } fn new() -> Result { Self::new_in(&std::env::temp_dir()) } + + fn new_shorts() -> Result { + Self::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-pq-shorts") + .map_err(|(path, source)| ParquetShortsError::Io { path, source }) + } + + fn new_events() -> Result { + Self::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-pq-events") + .map_err(|(path, source)| ParquetEventsError::Io { path, source }) + } + + fn new_fx() -> Result { + Self::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-pq-fx") + .map_err(|(path, source)| ParquetFxError::Io { path, source }) + } + + fn new_adj() -> Result { + Self::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-pq-adj") + .map_err(|(path, source)| ParquetAdjError::Io { path, source }) + } + + fn new_corporate_actions() -> Result { + Self::new_in_with_prefix( + &std::env::temp_dir(), + "curate-etl-bench-pq-corporate-actions", + ) + .map_err(|(path, source)| ParquetCorporateActionsError::Io { path, source }) + } } impl Drop for BenchTempDir { @@ -1956,6 +2047,3344 @@ pub fn run_parquet_bars_benchmark(rows: usize) -> Result Vec<(i32, i64)> { + semi_monthly_report_dates() + .into_iter() + .map(|report_date| { + let known_day = add_canadian_business_days(report_date, SHORTS_LAG_BUSINESS_DAYS) + .expect("semi-monthly date within calendar range"); + let known_at = et_to_utc_micros( + known_day, + SHORTS_DISSEMINATION_HOUR_ET, + SHORTS_DISSEMINATION_MINUTE_ET, + 0, + ) + .expect("17:00 ET valid"); + (report_date, known_at) + }) + .collect() +} + +struct ParquetShortsBenchIter { + dates: Vec<(i32, i64)>, + listing_count: usize, + base_per_listing: usize, + rem_listings: usize, + cur_listing: usize, + cur_date_idx: usize, + cur_listing_rows: usize, + cur_shares: f64, + rng: SplitMix64, +} + +impl ParquetShortsBenchIter { + fn new(rows: usize, dates: Vec<(i32, i64)>) -> Self { + let min_listings = if rows == 0 { + PARQUET_SHORTS_BENCH_BASE_LISTINGS + } else { + rows.div_ceil(dates.len()) + .max(PARQUET_SHORTS_BENCH_BASE_LISTINGS) + }; + let active_listings = rows.min(min_listings); + let base_per_listing = if active_listings == 0 { + 0 + } else { + rows / active_listings + }; + let rem_listings = if active_listings == 0 { + 0 + } else { + rows % active_listings + }; + let mut iter = Self { + dates, + listing_count: active_listings, + base_per_listing, + rem_listings, + cur_listing: 0, + cur_date_idx: 0, + cur_listing_rows: 0, + cur_shares: 10_000.0, + rng: SplitMix64::new(PARQUET_SHORTS_BENCH_SEED), + }; + if active_listings > 0 { + iter.setup_listing(0); + } + iter + } + + fn setup_listing(&mut self, listing_idx: usize) { + self.cur_listing = listing_idx; + self.cur_date_idx = 0; + self.cur_listing_rows = + self.base_per_listing + usize::from(listing_idx < self.rem_listings); + self.cur_shares = ((self.rng.next_u64() % 2_000_000) + 100) as f64; + } +} + +impl Iterator for ParquetShortsBenchIter { + type Item = ShortsParquetRow; + + fn next(&mut self) -> Option { + if self.cur_listing >= self.listing_count { + return None; + } + if self.cur_date_idx >= self.cur_listing_rows { + let next_listing = self.cur_listing + 1; + if next_listing >= self.listing_count { + self.cur_listing = next_listing; + return None; + } + self.setup_listing(next_listing); + } + + let listing_id = (self.cur_listing + 1) as i32; + let w = self.dates.len(); + let n = self.cur_listing_rows; + let date_pos = if n == 1 { + (self.cur_listing.wrapping_mul(131)) % w + } else { + (self.cur_date_idx * w) / n + }; + let (report_date, known_at_micros) = self.dates[date_pos]; + self.cur_date_idx += 1; + + let r1 = self.rng.next_u64(); + let r2 = self.rng.next_u64(); + let delta = ((r1 % 40_001) as f64) - 20_000.0; + let next_shares = (self.cur_shares + delta).max(0.0); + let net_change = if (r2 & 0xF) == 0 { + None + } else { + Some(next_shares - self.cur_shares) + }; + self.cur_shares = next_shares; + let pct_float = if ((r2 >> 4) & 0x3) == 0 { + None + } else { + Some(((r2 >> 8) % 2_500) as f64 * 0.01) + }; + + Some(ShortsParquetRow { + listing_id, + report_date, + known_at_micros, + shares_short: next_shares, + net_change, + pct_float, + source: Cow::Borrowed(SHORTS_SOURCE_CEO), + }) + } +} + +fn verify_parquet_shorts_row_count( + out_dir: &Path, + expected_rows: usize, +) -> Result { + if expected_rows == 0 { + return Ok(0); + } + let path = out_dir.join("shorts/part.parquet"); + let file = File::open(&path).map_err(|source| ParquetShortsError::Io { + path: path.clone(), + source, + })?; + let reader = SerializedFileReader::new(file).map_err(|source| ParquetShortsError::Parquet { + path: path.clone(), + source, + })?; + let read_back_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err( + |_| ParquetShortsError::Parquet { + path: path.clone(), + source: ParquetError::General(format!( + "negative or overflowing Parquet footer row count: {}", + reader.metadata().file_metadata().num_rows() + )), + }, + )?; + + if read_back_rows != expected_rows { + return Err(ParquetShortsError::Parquet { + path, + source: ParquetError::General(format!( + "parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}" + )), + }); + } + + Ok(read_back_rows) +} + +fn run_parquet_shorts_benchmark_tracked( + rows: usize, +) -> Result<(ParquetShortsBenchReport, PathBuf), ParquetShortsError> { + let temp = BenchTempDir::new_shorts()?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let stats = write_shorts_dataset( + &temp.path, + std::iter::empty::(), + ShortsWriteOptions::default(), + )?; + let read_back_rows = verify_parquet_shorts_row_count(&temp.path, 0)?; + let report = ParquetShortsBenchReport { + rows: 0, + read_back_rows, + listing_count: 0, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_SHORTS_RAW_ROW_BYTES, + elapsed_ms: 0.0, + rows_per_sec: 0.0, + mb_per_sec: 0.0, + bytes_per_row: 0.0, + compression_ratio: 0.0, + }; + drop(temp); + return Ok((report, temp_path)); + } + + let dates = semi_monthly_report_dates_with_known_at(); + let iter = ParquetShortsBenchIter::new(rows, dates); + let listing_count = iter.listing_count; + + let start = Instant::now(); + let stats = write_shorts_dataset(&temp.path, iter, ShortsWriteOptions::default())?; + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + if stats.rows_written != rows { + return Err(ParquetShortsError::Parquet { + path: temp.path.join("shorts/part.parquet"), + source: ParquetError::General(format!( + "writer row count mismatch: expected {rows}, stats reported {}", + stats.rows_written + )), + }); + } + + let read_back_rows = verify_parquet_shorts_row_count(&temp.path, rows)?; + + let (rows_per_sec, _) = compute_rates(rows, elapsed_secs); + let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { + (stats.bytes_written as f64 / (1024.0 * 1024.0)) / elapsed_secs + } else { + 0.0 + }; + let bytes_per_row = stats.bytes_written as f64 / rows as f64; + let raw_bytes = (rows as f64) * (PARQUET_SHORTS_RAW_ROW_BYTES as f64); + let compression_ratio = if stats.bytes_written > 0 { + raw_bytes / (stats.bytes_written as f64) + } else { + 0.0 + }; + + drop(temp); + + Ok(( + ParquetShortsBenchReport { + rows, + read_back_rows, + listing_count, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_SHORTS_RAW_ROW_BYTES, + elapsed_ms, + rows_per_sec, + mb_per_sec, + bytes_per_row, + compression_ratio, + }, + temp_path, + )) +} + +/// Runs the fixed-seed Zstd Parquet `shorts` writer benchmark for `rows` sorted short-interest +/// rows across `12,500` listings (scaling automatically for larger row counts) on semi-monthly +/// dates (`2017-04-15..=2026-04-30`), reads back the Parquet footer row count, and deletes its +/// temporary output directory. +pub fn run_parquet_shorts_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_parquet_shorts_benchmark_tracked(rows)?; + Ok(report) +} + +/// Summary metrics produced by [`run_parquet_events_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ParquetEventsBenchReport { + pub rows: usize, + pub read_back_rows: usize, + pub listing_count: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub avg_raw_row_bytes: f64, + pub elapsed_ms: f64, + pub rows_per_sec: f64, + pub mb_per_sec: f64, + pub bytes_per_row: f64, + pub compression_ratio: f64, +} + +const BENCH_EVENTS_ANNOUNCE_SUBTYPES: &[&str] = &["unknown", "amc", "bto"]; + +struct ParquetEventsBenchIter<'a> { + start_micros: i64, + span_micros: u64, + listing_count: usize, + base_per_listing: usize, + rem_listings: usize, + cur_listing: usize, + cur_row_idx: usize, + cur_listing_rows: usize, + emitted_seq: usize, + raw_bytes: &'a mut u64, + rng: SplitMix64, +} + +impl<'a> ParquetEventsBenchIter<'a> { + fn new(rows: usize, raw_bytes: &'a mut u64) -> Self { + let start_day = ymd_to_epoch_days(2015, 1, 1).expect("valid start date"); + let end_day = ymd_to_epoch_days(2025, 12, 31).expect("valid end date"); + let start_micros = i64::from(start_day) * 86_400_000_000; + let end_exclusive_micros = i64::from(end_day + 1) * 86_400_000_000; + let span_micros = (end_exclusive_micros - start_micros) as u64; + + let active_listings = rows.min(PARQUET_EVENTS_BENCH_BASE_LISTINGS); + let base_per_listing = if active_listings == 0 { + 0 + } else { + rows / active_listings + }; + let rem_listings = if active_listings == 0 { + 0 + } else { + rows % active_listings + }; + let mut iter = Self { + start_micros, + span_micros, + listing_count: active_listings, + base_per_listing, + rem_listings, + cur_listing: 0, + cur_row_idx: 0, + cur_listing_rows: 0, + emitted_seq: 0, + raw_bytes, + rng: SplitMix64::new(PARQUET_EVENTS_BENCH_SEED), + }; + if active_listings > 0 { + iter.setup_listing(0); + } + iter + } + + fn setup_listing(&mut self, listing_idx: usize) { + self.cur_listing = listing_idx; + self.cur_row_idx = 0; + self.cur_listing_rows = + self.base_per_listing + usize::from(listing_idx < self.rem_listings); + } +} + +impl Iterator for ParquetEventsBenchIter<'_> { + type Item = EventsParquetRow; + + fn next(&mut self) -> Option { + if self.cur_listing >= self.listing_count { + return None; + } + if self.cur_row_idx >= self.cur_listing_rows { + let next_listing = self.cur_listing + 1; + if next_listing >= self.listing_count { + self.cur_listing = next_listing; + return None; + } + self.setup_listing(next_listing); + } + + let listing_id = (self.cur_listing + 1) as i32; + let n = self.cur_listing_rows as u64; + let r1 = self.rng.next_u64(); + let r2 = self.rng.next_u64(); + + let offset_micros = if n == 1 { + ((self.cur_listing as u64).wrapping_mul(31_536_000_000_000) + (r1 % 86_400_000_000)) + % self.span_micros + } else { + let slot = (self.span_micros / n).max(1); + let jitter_cap = slot.min(3_600_000_000); + (self.cur_row_idx as u64) * slot + (r1 % jitter_cap) + }; + let ts_micros = self.start_micros + offset_micros as i64; + + let seq = self.emitted_seq; + self.cur_row_idx += 1; + self.emitted_seq += 1; + + let is_earnings = (r2 % 1_000) < 15; + let row = if is_earnings { + let linked = ((r2 >> 10) & 1) == 0; + let known_at_micros = if linked { + ts_micros + } else { + ts_micros + 14_700_000_000 // +4h05m lag + }; + let known_at_source = if linked { + KNOWN_AT_SOURCE_FILING_TIMESTAMP + } else { + KNOWN_AT_SOURCE_STATUTORY_LAG + }; + let subtype = BENCH_EVENTS_ANNOUNCE_SUBTYPES + [((r2 >> 12) as usize) % BENCH_EVENTS_ANNOUNCE_SUBTYPES.len()]; + let report_date = ts_micros.div_euclid(86_400_000_000) as i32; + let fiscal_period_end = Some(report_date - 35); + let actual_eps = Some((((r2 >> 16) % 800) as f64 - 150.0) * 0.01); + let revenue = Some((((r2 >> 28) % 50_000) + 100) as f64 * 100_000.0); + let linked_id = linked.then(|| format!("000{listing_id:07}-24-{seq:06}")); + let payload_json = encode_earnings_payload_json( + actual_eps, + subtype, + fiscal_period_end, + linked_id.as_deref(), + report_date, + revenue, + ); + EventsParquetRow { + listing_id, + ts_micros, + known_at_micros, + known_at_source: Cow::Borrowed(known_at_source), + kind: Cow::Borrowed(EVENT_KIND_EARNINGS), + subtype: subtype.to_string(), + payload_json, + } + } else { + let form_type = BENCH_FORM_TYPES[((r2 >> 10) as usize) % BENCH_FORM_TYPES.len()]; + let (group, is_amendment) = classify_form_type(form_type); + let filing_id = format!("000{listing_id:07}-24-{seq:06}"); + let url = format!( + "https://www.sec.gov/Archives/edgar/data/{listing_id:07}/{filing_id}/primary-filing-document-{seq:08}.htm" + ); + let payload_json = + encode_filing_payload_json(Some(&filing_id), form_type, is_amendment, Some(&url)); + EventsParquetRow { + listing_id, + ts_micros, + known_at_micros: ts_micros, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + kind: Cow::Borrowed(EVENT_KIND_FILING), + subtype: group.as_str().to_string(), + payload_json, + } + }; + + *self.raw_bytes += (4 + + 8 + + 8 + + row.known_at_source.len() + + row.kind.len() + + row.subtype.len() + + row.payload_json.len()) as u64; + + Some(row) + } +} + +fn verify_parquet_events_row_count( + out_dir: &Path, + years: impl IntoIterator, + expected_rows: usize, +) -> Result { + let mut read_back_rows = 0usize; + for year in years { + let path = out_dir.join(format!("events/year={year:04}/part.parquet")); + let file = File::open(&path).map_err(|source| ParquetEventsError::Io { + path: path.clone(), + source, + })?; + let reader = SerializedFileReader::new(file).map_err(|source| { + ParquetEventsError::Parquet { + path: path.clone(), + source, + } + })?; + let file_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err( + |_| ParquetEventsError::Parquet { + path: path.clone(), + source: ParquetError::General(format!( + "negative or overflowing Parquet footer row count: {}", + reader.metadata().file_metadata().num_rows() + )), + }, + )?; + read_back_rows = read_back_rows.checked_add(file_rows).ok_or_else(|| { + ParquetEventsError::Parquet { + path: path.clone(), + source: ParquetError::General("read-back row count overflow".to_string()), + } + })?; + } + + if read_back_rows != expected_rows { + return Err(ParquetEventsError::Parquet { + path: out_dir.join("events"), + source: ParquetError::General(format!( + "parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}" + )), + }); + } + + Ok(read_back_rows) +} + +fn run_parquet_events_benchmark_tracked( + rows: usize, +) -> Result<(ParquetEventsBenchReport, PathBuf), ParquetEventsError> { + let temp = BenchTempDir::new_events()?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let stats = write_events_dataset( + &temp.path, + std::iter::empty::(), + EventsWriteOptions::default(), + )?; + let read_back_rows = + verify_parquet_events_row_count(&temp.path, stats.rows_by_year.keys().copied(), 0)?; + let report = ParquetEventsBenchReport { + rows: 0, + read_back_rows, + listing_count: 0, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + avg_raw_row_bytes: 0.0, + elapsed_ms: 0.0, + rows_per_sec: 0.0, + mb_per_sec: 0.0, + bytes_per_row: 0.0, + compression_ratio: 0.0, + }; + drop(temp); + return Ok((report, temp_path)); + } + + let mut raw_bytes = 0u64; + let iter = ParquetEventsBenchIter::new(rows, &mut raw_bytes); + let listing_count = iter.listing_count; + + let start = Instant::now(); + let stats = write_events_dataset(&temp.path, iter, EventsWriteOptions::default())?; + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + if stats.rows_written != rows { + return Err(ParquetEventsError::Parquet { + path: temp.path.join("events"), + source: ParquetError::General(format!( + "writer row count mismatch: expected {rows}, stats reported {}", + stats.rows_written + )), + }); + } + + let read_back_rows = + verify_parquet_events_row_count(&temp.path, stats.rows_by_year.keys().copied(), rows)?; + + let (rows_per_sec, _) = compute_rates(rows, elapsed_secs); + let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { + (stats.bytes_written as f64 / (1024.0 * 1024.0)) / elapsed_secs + } else { + 0.0 + }; + let bytes_per_row = stats.bytes_written as f64 / rows as f64; + let avg_raw_row_bytes = raw_bytes as f64 / rows as f64; + let compression_ratio = if stats.bytes_written > 0 { + (raw_bytes as f64) / (stats.bytes_written as f64) + } else { + 0.0 + }; + + drop(temp); + + Ok(( + ParquetEventsBenchReport { + rows, + read_back_rows, + listing_count, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + avg_raw_row_bytes, + elapsed_ms, + rows_per_sec, + mb_per_sec, + bytes_per_row, + compression_ratio, + }, + temp_path, + )) +} + +/// Runs the fixed-seed Zstd Parquet `events` writer benchmark for `rows` sorted filing/earnings +/// rows spanning `2015..=2025` across up to `5,000` listings, reads back Parquet footer row +/// counts across all year partitions, and deletes its temporary output directory. +pub fn run_parquet_events_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_parquet_events_benchmark_tracked(rows)?; + Ok(report) +} + +/// Summary metrics produced by [`run_parquet_fx_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ParquetFxBenchReport { + pub rows: usize, + pub read_back_rows: usize, + pub pair_count: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub raw_row_bytes: usize, + pub elapsed_ms: f64, + pub rows_per_sec: f64, + pub mb_per_sec: f64, + pub bytes_per_row: f64, + pub compression_ratio: f64, +} + +const BENCH_FX_STATIC_PAIRS: [&str; 79] = [ + "FX0000", "FX0001", "FX0002", "FX0003", "FX0004", "FX0005", "FX0006", "FX0007", "FX0008", + "FX0009", "FX0010", "FX0011", "FX0012", "FX0013", "FX0014", "FX0015", "FX0016", "FX0017", + "FX0018", "FX0019", "FX0020", "FX0021", "FX0022", "FX0023", "FX0024", "FX0025", "FX0026", + "FX0027", "FX0028", "FX0029", "FX0030", "FX0031", "FX0032", "FX0033", "FX0034", "FX0035", + "FX0036", "FX0037", "FX0038", "FX0039", "FX0040", "FX0041", "FX0042", "FX0043", "FX0044", + "FX0045", "FX0046", "FX0047", "FX0048", "FX0049", "FX0050", "FX0051", "FX0052", "FX0053", + "FX0054", "FX0055", "FX0056", "FX0057", "FX0058", "FX0059", "FX0060", "FX0061", "FX0062", + "FX0063", "FX0064", "FX0065", "FX0066", "FX0067", "FX0068", "FX0069", "FX0070", "FX0071", + "FX0072", "FX0073", "FX0074", "FX0075", "FX0076", "FX0077", "FX0078", +]; + +fn collect_bench_weekdays_1971_2026() -> Vec { + let start = ymd_to_epoch_days(1971, 1, 4).expect("valid start date"); + let end = ymd_to_epoch_days(2026, 12, 31).expect("valid end date"); + let mut days = Vec::with_capacity(15_000); + let mut d = start; + while d <= end { + let dow = (d + 4).rem_euclid(7); + if (1..=5).contains(&dow) { + days.push(d); + } + d += 1; + } + days +} + +struct ParquetFxBenchIter { + weekdays: Vec, + te_tail_start_day: i32, + pair_count: usize, + pair_width: usize, + base_per_pair: usize, + rem_pairs: usize, + cur_pair_idx: usize, + cur_day_idx: usize, + cur_pair_rows: usize, + cur_rate: f64, + rng: SplitMix64, +} + +impl ParquetFxBenchIter { + fn new(rows: usize, weekdays: Vec) -> Self { + let min_pairs = if rows == 0 { + PARQUET_FX_BENCH_BASE_PAIRS + } else { + rows.div_ceil(weekdays.len()) + .max(PARQUET_FX_BENCH_BASE_PAIRS) + }; + let active_pairs = rows.min(min_pairs); + let max_synthetic_idx = active_pairs.saturating_sub(2); + let pair_width = (max_synthetic_idx.checked_ilog10().unwrap_or(0) as usize + 1).max(4); + let base_per_pair = if active_pairs == 0 { + 0 + } else { + rows / active_pairs + }; + let rem_pairs = if active_pairs == 0 { + 0 + } else { + rows % active_pairs + }; + let te_tail_start_day = ymd_to_epoch_days(2026, 1, 1).expect("valid tail date"); + let mut iter = Self { + weekdays, + te_tail_start_day, + pair_count: active_pairs, + pair_width, + base_per_pair, + rem_pairs, + cur_pair_idx: 0, + cur_day_idx: 0, + cur_pair_rows: 0, + cur_rate: 1.35, + rng: SplitMix64::new(PARQUET_FX_BENCH_SEED), + }; + if active_pairs > 0 { + iter.setup_pair(0); + } + iter + } + + fn setup_pair(&mut self, pair_idx: usize) { + self.cur_pair_idx = pair_idx; + self.cur_day_idx = 0; + self.cur_pair_rows = self.base_per_pair + usize::from(pair_idx < self.rem_pairs); + self.cur_rate = 0.95 + ((self.rng.next_u64() % 60) as f64) * 0.01; + } + + #[inline] + fn pair_label(&self, pair_idx: usize) -> Cow<'static, str> { + // Place canonical "USDCAD" last so lexicographic order ("FX0000" < ... < "USDCAD") + // is strictly ascending and zero-allocation for up to 80 pairs (~1.16M rows). + if pair_idx + 1 == self.pair_count { + Cow::Borrowed(FX_PAIR_USDCAD) + } else if self.pair_width == 4 { + if let Some(&static_pair) = BENCH_FX_STATIC_PAIRS.get(pair_idx) { + Cow::Borrowed(static_pair) + } else { + Cow::Owned(format!("FX{pair_idx:04}")) + } + } else { + Cow::Owned(format!("FX{pair_idx:0width$}", width = self.pair_width)) + } + } +} + +impl Iterator for ParquetFxBenchIter { + type Item = Fx1dParquetRow; + + fn next(&mut self) -> Option { + if self.cur_pair_idx >= self.pair_count { + return None; + } + if self.cur_day_idx >= self.cur_pair_rows { + let next_pair = self.cur_pair_idx + 1; + if next_pair >= self.pair_count { + self.cur_pair_idx = next_pair; + return None; + } + self.setup_pair(next_pair); + } + + let pair = self.pair_label(self.cur_pair_idx); + let w = self.weekdays.len(); + let n = self.cur_pair_rows; + let date_pos = if n == 1 { + (self.cur_pair_idx.wrapping_mul(131)) % w + } else { + (self.cur_day_idx * w) / n + }; + let session_date = self.weekdays[date_pos]; + self.cur_day_idx += 1; + + let r1 = self.rng.next_u64(); + let step = ((r1 % 201) as f64 - 100.0) * 0.0001; + let next_rate = (self.cur_rate + step).clamp(0.92, 1.60); + let half_spread = (((r1 >> 8) % 80) + 10) as f64 * 0.0001; + let low = (next_rate - half_spread).max(0.50); + let high = next_rate + half_spread; + let open = low + (high - low) * (((r1 >> 16) % 100) as f64 * 0.01); + let close = next_rate; + self.cur_rate = next_rate; + + let source = if session_date >= self.te_tail_start_day || ((r1 >> 24) % 20) == 0 { + FxSource::TeUsdCad + } else { + FxSource::EodCadForex + }; + let ts_micros = i64::from(session_date) * 86_400_000_000 + 22 * 3_600_000_000; + let known_at_micros = ts_micros + 900_000_000; + + Some(Fx1dParquetRow { + pair, + session_date, + ts_micros, + open, + high, + low, + close, + source: Cow::Borrowed(source.as_str()), + known_at_micros, + }) + } +} + +fn verify_parquet_fx_row_count( + out_dir: &Path, + expected_rows: usize, +) -> Result { + if expected_rows == 0 { + return Ok(0); + } + let path = out_dir.join("fx_1d/part.parquet"); + let file = File::open(&path).map_err(|source| ParquetFxError::Io { + path: path.clone(), + source, + })?; + let reader = SerializedFileReader::new(file).map_err(|source| ParquetFxError::Parquet { + path: path.clone(), + source, + })?; + let read_back_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err( + |_| ParquetFxError::Parquet { + path: path.clone(), + source: ParquetError::General(format!( + "negative or overflowing Parquet footer row count: {}", + reader.metadata().file_metadata().num_rows() + )), + }, + )?; + + if read_back_rows != expected_rows { + return Err(ParquetFxError::Parquet { + path, + source: ParquetError::General(format!( + "parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}" + )), + }); + } + + Ok(read_back_rows) +} + +fn run_parquet_fx_benchmark_tracked( + rows: usize, +) -> Result<(ParquetFxBenchReport, PathBuf), ParquetFxError> { + let temp = BenchTempDir::new_fx()?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let stats = write_fx_1d_dataset( + &temp.path, + std::iter::empty::(), + Fx1dWriteOptions::default(), + )?; + let read_back_rows = verify_parquet_fx_row_count(&temp.path, 0)?; + let report = ParquetFxBenchReport { + rows: 0, + read_back_rows, + pair_count: 0, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_FX_RAW_ROW_BYTES, + elapsed_ms: 0.0, + rows_per_sec: 0.0, + mb_per_sec: 0.0, + bytes_per_row: 0.0, + compression_ratio: 0.0, + }; + drop(temp); + return Ok((report, temp_path)); + } + + let weekdays = collect_bench_weekdays_1971_2026(); + let iter = ParquetFxBenchIter::new(rows, weekdays); + let pair_count = iter.pair_count; + + let start = Instant::now(); + let stats = write_fx_1d_dataset(&temp.path, iter, Fx1dWriteOptions::default())?; + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + if stats.rows_written != rows { + return Err(ParquetFxError::Parquet { + path: temp.path.join("fx_1d/part.parquet"), + source: ParquetError::General(format!( + "writer row count mismatch: expected {rows}, stats reported {}", + stats.rows_written + )), + }); + } + + let read_back_rows = verify_parquet_fx_row_count(&temp.path, rows)?; + + let (rows_per_sec, _) = compute_rates(rows, elapsed_secs); + let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { + (stats.bytes_written as f64 / (1024.0 * 1024.0)) / elapsed_secs + } else { + 0.0 + }; + let bytes_per_row = stats.bytes_written as f64 / rows as f64; + let raw_bytes = (rows as f64) * (PARQUET_FX_RAW_ROW_BYTES as f64); + let compression_ratio = if stats.bytes_written > 0 { + raw_bytes / (stats.bytes_written as f64) + } else { + 0.0 + }; + + drop(temp); + + Ok(( + ParquetFxBenchReport { + rows, + read_back_rows, + pair_count, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_FX_RAW_ROW_BYTES, + elapsed_ms, + rows_per_sec, + mb_per_sec, + bytes_per_row, + compression_ratio, + }, + temp_path, + )) +} + +/// Runs the fixed-seed Zstd Parquet `fx_1d` writer benchmark for `rows` sorted daily FX rows +/// spanning `1971..=2026` across up to `80` currency pairs (scaling automatically for larger row +/// counts), reads back the Parquet footer row count, and deletes its temporary output directory. +pub fn run_parquet_fx_benchmark(rows: usize) -> Result { + let (report, _) = run_parquet_fx_benchmark_tracked(rows)?; + Ok(report) +} + +/// Summary metrics produced by [`run_parquet_adj_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ParquetAdjBenchReport { + pub rows: usize, + pub read_back_rows: usize, + pub listing_count: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub raw_row_bytes: usize, + pub elapsed_ms: f64, + pub rows_per_sec: f64, + pub mb_per_sec: f64, + pub bytes_per_row: f64, + pub compression_ratio: f64, +} + +fn collect_bench_weekdays_1990_2025() -> Vec { + let start = ymd_to_epoch_days(1990, 1, 2).expect("valid start date"); + let end = ymd_to_epoch_days(2025, 12, 31).expect("valid end date"); + let mut days = Vec::with_capacity(9_500); + let mut d = start; + while d <= end { + let dow = (d + 4).rem_euclid(7); + if (1..=5).contains(&dow) { + days.push(d); + } + d += 1; + } + days +} + +struct ParquetAdjBenchIter { + weekdays: Vec, + listing_count: usize, + base_per_listing: usize, + rem_listings: usize, + cur_listing: usize, + cur_day_idx: usize, + cur_listing_rows: usize, + cum_split: f64, + cum_total: f64, + rng: SplitMix64, +} + +impl ParquetAdjBenchIter { + fn new(rows: usize, weekdays: Vec) -> Self { + let min_listings = if rows == 0 { + PARQUET_ADJ_BENCH_BASE_LISTINGS + } else { + rows.div_ceil(weekdays.len()) + .max(PARQUET_ADJ_BENCH_BASE_LISTINGS) + }; + let active_listings = rows.min(min_listings); + let base_per_listing = if active_listings == 0 { + 0 + } else { + rows / active_listings + }; + let rem_listings = if active_listings == 0 { + 0 + } else { + rows % active_listings + }; + let mut iter = Self { + weekdays, + listing_count: active_listings, + base_per_listing, + rem_listings, + cur_listing: 0, + cur_day_idx: 0, + cur_listing_rows: 0, + cum_split: 1.0, + cum_total: 1.0, + rng: SplitMix64::new(PARQUET_ADJ_BENCH_SEED), + }; + if active_listings > 0 { + iter.setup_listing(0); + } + iter + } + + fn setup_listing(&mut self, listing_idx: usize) { + self.cur_listing = listing_idx; + self.cur_day_idx = 0; + self.cur_listing_rows = + self.base_per_listing + usize::from(listing_idx < self.rem_listings); + self.cum_split = 1.0 + ((self.rng.next_u64() % 8) as f64) * 0.5; + self.cum_total = self.cum_split * (1.05 + ((self.rng.next_u64() % 40) as f64) * 0.01); + } +} + +impl Iterator for ParquetAdjBenchIter { + type Item = AdjFactorsParquetRow; + + fn next(&mut self) -> Option { + if self.cur_listing >= self.listing_count { + return None; + } + if self.cur_day_idx >= self.cur_listing_rows { + let next_listing = self.cur_listing + 1; + if next_listing >= self.listing_count { + self.cur_listing = next_listing; + return None; + } + self.setup_listing(next_listing); + } + + let listing_id = (self.cur_listing as i32) + 1; + let w = self.weekdays.len(); + let n = self.cur_listing_rows; + let date_pos = if n == 1 { + (self.cur_listing.wrapping_mul(131)) % w + } else { + (self.cur_day_idx * w) / n + }; + let ex_date = self.weekdays[date_pos]; + self.cur_day_idx += 1; + + let r1 = self.rng.next_u64(); + let kind_roll = r1 % 100; + let currency = if ((r1 >> 8) & 3) == 0 { "CAD" } else { "USD" }; + + let (split_factor, div_cash, div_currency) = if kind_roll < 4 { + // ~4% split-only rows (`div_currency = None`). + let ratio = SAMPLE_RATIOS[((r1 >> 16) as usize) % SAMPLE_RATIOS.len()]; + (ratio, 0.0, None) + } else if kind_roll == 4 { + // ~1% combined split + dividend rows. + let ratio = SAMPLE_RATIOS[((r1 >> 16) as usize) % SAMPLE_RATIOS.len()]; + let cash = (((r1 >> 24) % 150) + 5) as f64 * 0.01; + (ratio, cash, Some(Cow::Borrowed(currency))) + } else { + // ~95% dividend-only rows. + let cash = (((r1 >> 24) % 250) + 1) as f64 * 0.01; + (1.0, cash, Some(Cow::Borrowed(currency))) + }; + + let cum_split_factor = self.cum_split; + let cum_total_factor = self.cum_total; + // Declared 14–21 days before ex_date (~90%), or ex_date fallback (~10%). + let lead_days = if ((r1 >> 40) % 10) == 0 { + 0 + } else { + 14 + ((r1 >> 44) % 8) as i32 + }; + let known_at_micros = + i64::from(ex_date - lead_days) * 86_400_000_000 + 13 * 3_600_000_000; + + Some(AdjFactorsParquetRow { + listing_id, + ex_date, + split_factor, + div_cash, + div_currency, + cum_split_factor, + cum_total_factor, + known_at_micros, + }) + } +} + +fn verify_parquet_adj_row_count( + out_dir: &Path, + expected_rows: usize, +) -> Result { + if expected_rows == 0 { + return Ok(0); + } + let path = out_dir.join("adj_factors/part.parquet"); + let file = File::open(&path).map_err(|source| ParquetAdjError::Io { + path: path.clone(), + source, + })?; + let reader = SerializedFileReader::new(file).map_err(|source| ParquetAdjError::Parquet { + path: path.clone(), + source, + })?; + let read_back_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err( + |_| ParquetAdjError::Parquet { + path: path.clone(), + source: ParquetError::General(format!( + "negative or overflowing Parquet footer row count: {}", + reader.metadata().file_metadata().num_rows() + )), + }, + )?; + + if read_back_rows != expected_rows { + return Err(ParquetAdjError::Parquet { + path, + source: ParquetError::General(format!( + "parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}" + )), + }); + } + + Ok(read_back_rows) +} + +fn run_parquet_adj_benchmark_tracked( + rows: usize, +) -> Result<(ParquetAdjBenchReport, PathBuf), ParquetAdjError> { + let temp = BenchTempDir::new_adj()?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let stats = write_adj_factors_dataset( + &temp.path, + std::iter::empty::(), + AdjFactorsWriteOptions::default(), + )?; + let read_back_rows = verify_parquet_adj_row_count(&temp.path, 0)?; + let report = ParquetAdjBenchReport { + rows: 0, + read_back_rows, + listing_count: 0, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_ADJ_RAW_ROW_BYTES, + elapsed_ms: 0.0, + rows_per_sec: 0.0, + mb_per_sec: 0.0, + bytes_per_row: 0.0, + compression_ratio: 0.0, + }; + drop(temp); + return Ok((report, temp_path)); + } + + let weekdays = collect_bench_weekdays_1990_2025(); + let iter = ParquetAdjBenchIter::new(rows, weekdays); + let listing_count = iter.listing_count; + + let start = Instant::now(); + let stats = write_adj_factors_dataset(&temp.path, iter, AdjFactorsWriteOptions::default())?; + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + if stats.rows_written != rows { + return Err(ParquetAdjError::Parquet { + path: temp.path.join("adj_factors/part.parquet"), + source: ParquetError::General(format!( + "writer row count mismatch: expected {rows}, stats reported {}", + stats.rows_written + )), + }); + } + + let read_back_rows = verify_parquet_adj_row_count(&temp.path, rows)?; + + let (rows_per_sec, _) = compute_rates(rows, elapsed_secs); + let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { + (stats.bytes_written as f64 / (1024.0 * 1024.0)) / elapsed_secs + } else { + 0.0 + }; + let bytes_per_row = stats.bytes_written as f64 / rows as f64; + let raw_bytes = (rows as f64) * (PARQUET_ADJ_RAW_ROW_BYTES as f64); + let compression_ratio = if stats.bytes_written > 0 { + raw_bytes / (stats.bytes_written as f64) + } else { + 0.0 + }; + + drop(temp); + + Ok(( + ParquetAdjBenchReport { + rows, + read_back_rows, + listing_count, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_ADJ_RAW_ROW_BYTES, + elapsed_ms, + rows_per_sec, + mb_per_sec, + bytes_per_row, + compression_ratio, + }, + temp_path, + )) +} + +/// Runs the fixed-seed Zstd Parquet `adj_factors` writer benchmark for `rows` sorted split/dividend +/// rows spanning `1990..=2025` across up to `20,000` listings, reads back the Parquet footer row +/// count, and deletes its temporary output directory. +pub fn run_parquet_adj_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_parquet_adj_benchmark_tracked(rows)?; + Ok(report) +} + +/// Summary metrics produced by [`run_parquet_corporate_actions_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ParquetCorporateActionsBenchReport { + pub rows: usize, + pub read_back_rows: usize, + pub listing_count: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub raw_row_bytes: usize, + pub elapsed_ms: f64, + pub rows_per_sec: f64, + pub mb_per_sec: f64, + pub bytes_per_row: f64, + pub compression_ratio: f64, +} + +struct ParquetCorporateActionsBenchIter { + weekdays: Vec, + listing_count: usize, + base_per_listing: usize, + rem_listings: usize, + cur_listing: usize, + cur_day_idx: usize, + cur_listing_rows: usize, + rng: SplitMix64, +} + +impl ParquetCorporateActionsBenchIter { + fn new(rows: usize, weekdays: Vec) -> Self { + let min_listings = if rows == 0 { + PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS + } else { + rows.div_ceil(weekdays.len()) + .max(PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS) + }; + let active_listings = rows.min(min_listings); + let base_per_listing = if active_listings == 0 { + 0 + } else { + rows / active_listings + }; + let rem_listings = if active_listings == 0 { + 0 + } else { + rows % active_listings + }; + let mut iter = Self { + weekdays, + listing_count: active_listings, + base_per_listing, + rem_listings, + cur_listing: 0, + cur_day_idx: 0, + cur_listing_rows: 0, + rng: SplitMix64::new(PARQUET_CORPORATE_ACTIONS_BENCH_SEED), + }; + if active_listings > 0 { + iter.setup_listing(0); + } + iter + } + + fn setup_listing(&mut self, listing_idx: usize) { + self.cur_listing = listing_idx; + self.cur_day_idx = 0; + self.cur_listing_rows = + self.base_per_listing + usize::from(listing_idx < self.rem_listings); + } +} + +impl Iterator for ParquetCorporateActionsBenchIter { + type Item = CorporateActionsParquetRow; + + fn next(&mut self) -> Option { + if self.cur_listing >= self.listing_count { + return None; + } + if self.cur_day_idx >= self.cur_listing_rows { + let next_listing = self.cur_listing + 1; + if next_listing >= self.listing_count { + self.cur_listing = next_listing; + return None; + } + self.setup_listing(next_listing); + } + + let listing_id = (self.cur_listing as i32) + 1; + let w = self.weekdays.len(); + let n = self.cur_listing_rows; + let date_pos = if n == 1 { + (self.cur_listing.wrapping_mul(131)) % w + } else { + (self.cur_day_idx * w) / n + }; + let ex_date = self.weekdays[date_pos]; + self.cur_day_idx += 1; + + let r1 = self.rng.next_u64(); + let kind_roll = r1 % 100; + + // M1.2c mix: ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes + // (split between otc_delist_transfer and delisting). + if kind_roll < 4 { + let ratio = SAMPLE_RATIOS[((r1 >> 16) as usize) % SAMPLE_RATIOS.len()]; + let decl_roll = (r1 >> 40) % 100; + let (declared_date, known_at_day, known_at_source) = if decl_roll < 80 { + let d = ex_date - (14 + ((r1 >> 48) % 8) as i32); + (Some(d), d, KnownAtSource::DeclaredDate) + } else if decl_roll < 98 { + (None, ex_date, KnownAtSource::ExDateFallback) + } else { + (Some(ex_date + 3), ex_date, KnownAtSource::ExDateFallback) + }; + Some(CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date, + kind: CorporateActionKind::Split, + ratio: Some(ratio), + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: None, + known_at_micros: i64::from(known_at_day) * 86_400_000_000 + 13 * 3_600_000_000, + known_at_source, + }) + } else if kind_roll < 96 { + let currency = if ((r1 >> 8) & 3) == 0 { "CAD" } else { "USD" }; + let cash = (((r1 >> 24) % 250) + 1) as f64 * 0.01; + let decl_roll = (r1 >> 40) % 100; + let (declared_date, known_at_day, known_at_source) = if decl_roll < 80 { + let d = ex_date - (14 + ((r1 >> 48) % 8) as i32); + (Some(d), d, KnownAtSource::DeclaredDate) + } else if decl_roll < 98 { + (None, ex_date, KnownAtSource::ExDateFallback) + } else { + (Some(ex_date + 3), ex_date, KnownAtSource::ExDateFallback) + }; + Some(CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date, + kind: CorporateActionKind::Dividend, + ratio: None, + cash_amount: Some(cash), + currency: Some(Cow::Borrowed(currency)), + successor_listing_id: None, + terminal_return: None, + known_at_micros: i64::from(known_at_day) * 86_400_000_000 + 13 * 3_600_000_000, + known_at_source, + }) + } else if kind_roll < 98 { + Some(CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date: None, + kind: CorporateActionKind::OtcDelistTransfer, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: Some(listing_id + 1_000_000), + terminal_return: None, + known_at_micros: i64::from(ex_date) * 86_400_000_000 + 13 * 3_600_000_000, + known_at_source: KnownAtSource::DelistDate, + }) + } else { + let terminal_return = match (r1 >> 24) % 4 { + 0 => -1.0, + 1 => -0.5, + 2 => -0.3, + _ => 0.0, + }; + Some(CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date: None, + kind: CorporateActionKind::Delisting, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: Some(terminal_return), + known_at_micros: i64::from(ex_date) * 86_400_000_000 + 13 * 3_600_000_000, + known_at_source: KnownAtSource::DelistDate, + }) + } + } +} + +fn verify_parquet_corporate_actions_row_count( + out_dir: &Path, + expected_rows: usize, +) -> Result { + if expected_rows == 0 { + return Ok(0); + } + let path = out_dir.join("corporate_actions/part.parquet"); + let file = File::open(&path).map_err(|source| ParquetCorporateActionsError::Io { + path: path.clone(), + source, + })?; + let reader = + SerializedFileReader::new(file).map_err(|source| ParquetCorporateActionsError::Parquet { + path: path.clone(), + source, + })?; + let read_back_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err( + |_| ParquetCorporateActionsError::Parquet { + path: path.clone(), + source: ParquetError::General(format!( + "negative or overflowing Parquet footer row count: {}", + reader.metadata().file_metadata().num_rows() + )), + }, + )?; + + if read_back_rows != expected_rows { + return Err(ParquetCorporateActionsError::Parquet { + path, + source: ParquetError::General(format!( + "parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}" + )), + }); + } + + Ok(read_back_rows) +} + +fn run_parquet_corporate_actions_benchmark_tracked( + rows: usize, +) -> Result<(ParquetCorporateActionsBenchReport, PathBuf), ParquetCorporateActionsError> { + let temp = BenchTempDir::new_corporate_actions()?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let stats = write_corporate_actions_dataset( + &temp.path, + std::iter::empty::(), + CorporateActionsWriteOptions::default(), + )?; + let read_back_rows = verify_parquet_corporate_actions_row_count(&temp.path, 0)?; + let report = ParquetCorporateActionsBenchReport { + rows: 0, + read_back_rows, + listing_count: 0, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES, + elapsed_ms: 0.0, + rows_per_sec: 0.0, + mb_per_sec: 0.0, + bytes_per_row: 0.0, + compression_ratio: 0.0, + }; + drop(temp); + return Ok((report, temp_path)); + } + + let weekdays = collect_bench_weekdays_1990_2025(); + let iter = ParquetCorporateActionsBenchIter::new(rows, weekdays); + let listing_count = iter.listing_count; + + let start = Instant::now(); + let stats = write_corporate_actions_dataset( + &temp.path, + iter, + CorporateActionsWriteOptions::default(), + )?; + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + if stats.rows_written != rows { + return Err(ParquetCorporateActionsError::Parquet { + path: temp.path.join("corporate_actions/part.parquet"), + source: ParquetError::General(format!( + "writer row count mismatch: expected {rows}, stats reported {}", + stats.rows_written + )), + }); + } + + let read_back_rows = verify_parquet_corporate_actions_row_count(&temp.path, rows)?; + + let (rows_per_sec, _) = compute_rates(rows, elapsed_secs); + let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { + (stats.bytes_written as f64 / (1024.0 * 1024.0)) / elapsed_secs + } else { + 0.0 + }; + let bytes_per_row = stats.bytes_written as f64 / rows as f64; + let raw_bytes = (rows as f64) * (PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES as f64); + let compression_ratio = if stats.bytes_written > 0 { + raw_bytes / (stats.bytes_written as f64) + } else { + 0.0 + }; + + drop(temp); + + Ok(( + ParquetCorporateActionsBenchReport { + rows, + read_back_rows, + listing_count, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES, + elapsed_ms, + rows_per_sec, + mb_per_sec, + bytes_per_row, + compression_ratio, + }, + temp_path, + )) +} + +/// Runs the fixed-seed Zstd Parquet `corporate_actions` writer benchmark for `rows` sorted +/// split/dividend/delisting rows spanning `1990..=2025` across up to `20,000` listings, reads back +/// the Parquet footer row count, and deletes its temporary output directory. +pub fn run_parquet_corporate_actions_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_parquet_corporate_actions_benchmark_tracked(rows)?; + Ok(report) +} + +/// Summary metrics produced by [`run_bson_eod_prices_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BsonEodPricesBenchReport { + pub rows: usize, + pub bytes: usize, + pub elapsed_ms: f64, + pub rows_per_sec: f64, + pub mb_per_sec: f64, + pub ns_per_row: f64, + pub checksum: u64, + pub stats: BsonEodDecodeStats, +} + +/// Runs the fixed-seed raw BSON `eodPrices` zero-copy decode benchmark for `rows` synthetic +/// documents. +/// +/// Pre-encodes `rows` realistic `eodPrices` documents (including extra metadata fields `_id`, +/// `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `created_at`, +/// `updated_at`, mixed `Double`/`Int32`/`Int64` numerics, `YYYY-MM-DD` strings + ~5% BSON +/// `DateTime` dates, and ~0.5% deterministic rejected rows) into one contiguous length-prefixed +/// `Vec` buffer up front, then times decode-only via [`decode_eod_price_buffer`]. +pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport { + if rows == 0 { + return BsonEodPricesBenchReport { + rows: 0, + bytes: 0, + elapsed_ms: 0.0, + rows_per_sec: 0.0, + mb_per_sec: 0.0, + ns_per_row: 0.0, + checksum: 0, + stats: BsonEodDecodeStats::default(), + }; + } + + const SYMBOL_POOL: usize = 2_000; + const EXCHANGES: [&str; 4] = ["NASDAQ", "NYSE", "TSX", "TSXV"]; + const PROVIDER_EXCHANGES: [&str; 4] = ["US", "US", "TO", "V"]; + const MILLIS_PER_DAY: i64 = 86_400_000; + + let min_date = ymd_to_epoch_days(2010, 1, 4).unwrap_or(14_613); + let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); + let mut date_days: Vec = Vec::with_capacity(4_200); + let mut date_strings: Vec = Vec::with_capacity(4_200); + for d in min_date..=max_date { + let dow = (d + 4).rem_euclid(7); + if dow == 0 || dow == 6 { + continue; + } + let (y, m, day) = epoch_days_to_ymd(d); + date_days.push(d); + date_strings.push(format!("{y:04}-{m:02}-{day:02}")); + } + + let symbols: Vec<(String, String, &'static str, &'static str)> = (0..SYMBOL_POOL) + .map(|i| { + let ex_idx = i % EXCHANGES.len(); + let sym = format!("SYM{i:04}"); + let prov = PROVIDER_EXCHANGES[ex_idx]; + let code = format!("{sym}.{prov}"); + (sym, code, EXCHANGES[ex_idx], prov) + }) + .collect(); + + let mut rng = SplitMix64::new(BSON_EOD_PRICES_BENCH_SEED); + // ~240 bytes per realistic eodPrices document with extra metadata fields. + let mut buffer: Vec = Vec::with_capacity(rows.saturating_mul(256)); + + for i in 0..rows { + let sym_idx = (rng.next_u64() as usize) % symbols.len(); + let (ref symbol, ref code, exchange, provider_exchange) = symbols[sym_idx]; + let date_idx = (rng.next_u64() as usize) % date_days.len(); + let epoch_day = date_days[date_idx]; + let date_str = &date_strings[date_idx]; + + let base_cents = 100 + (rng.next_u64() % 50_000) as i64; + let open = base_cents as f64 / 100.0; + let spread = 1.0 + (rng.next_u64() % 200) as f64 / 100.0; + let high = open + spread; + let low = (open - spread * 0.5).max(0.01); + let close = low + (high - low) * ((rng.next_u64() % 100) as f64 / 100.0); + let volume_i64 = 1_000 + (rng.next_u64() % 50_000_000) as i64; + + let mut oid_bytes = [0u8; 12]; + let seq = (i as u64).to_be_bytes(); + oid_bytes[4..12].copy_from_slice(&seq); + + let created_ms = i64::from(epoch_day) * MILLIS_PER_DAY + 79_200_000; + let updated_ms = created_ms + 60_000; + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes)); + doc.append(cstr!("symbol"), symbol.as_str()); + doc.append(cstr!("exchange"), exchange); + doc.append(cstr!("providerExchange"), provider_exchange); + doc.append(cstr!("source"), "eod"); + + // Inject ~0.5% deterministic rejected rows across 4 distinct error categories. + let bad_roll = rng.next_u64() % 1_000; + doc.append(cstr!("eodSearchCode"), code.as_str()); + if bad_roll == 0 { + // Malformed date string. + doc.append(cstr!("date"), "2023-02-29"); + } else if rng.next_u64() % 20 == 0 { + // ~5% BSON DateTime dates. + doc.append( + cstr!("date"), + DateTime::from_millis(i64::from(epoch_day) * MILLIS_PER_DAY), + ); + } else { + doc.append(cstr!("date"), date_str.as_str()); + } + + if bad_roll == 1 { + // Wrong BSON type on open. + doc.append(cstr!("open"), "bad"); + } else if i % 10 == 0 { + doc.append(cstr!("open"), (base_cents / 100) as i32); + } else { + doc.append(cstr!("open"), open); + } + + if bad_roll == 2 { + // Negative price on high. + doc.append(cstr!("high"), -1.0_f64); + } else { + doc.append(cstr!("high"), high); + } + + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("adjustedClose"), close * 0.95); + + if bad_roll != 3 && bad_roll != 4 { + match i % 3 { + 0 => doc.append(cstr!("volume"), volume_i64), + 1 => doc.append(cstr!("volume"), (volume_i64 as i32).abs()), + _ => doc.append(cstr!("volume"), volume_i64 as f64), + } + } + // When bad_roll is 3 or 4, omit `volume` to exercise MissingField. + + doc.append(cstr!("created_at"), DateTime::from_millis(created_ms)); + doc.append(cstr!("updated_at"), DateTime::from_millis(updated_ms)); + + buffer.extend_from_slice(doc.as_bytes()); + } + + let bytes = buffer.len(); + let mut hash = 0u64; + let mut err_hash = 0u64; + + let start = Instant::now(); + let stats = decode_eod_price_buffer( + &buffer, + |bar| { + hash = mix_bytes(hash, bar.eod_search_code.as_bytes()); + hash = mix_u64(hash, bar.session_date as u64); + hash = mix_u64(hash, bar.open.to_bits()); + hash = mix_u64(hash, bar.high.to_bits()); + hash = mix_u64(hash, bar.low.to_bits()); + hash = mix_u64(hash, bar.close.to_bits()); + hash = mix_u64(hash, bar.adj_volume.to_bits()); + }, + |offset, _err| { + err_hash = mix_u64(err_hash, offset as u64 ^ 0xDEAD_BEEF_CAFE_BABEu64); + }, + ); + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + let (rows_per_sec, ns_per_row) = compute_rates(rows, elapsed_secs); + let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { + (bytes as f64 / (1024.0 * 1024.0)) / elapsed_secs + } else { + 0.0 + }; + let checksum = black_box(hash ^ err_hash); + + BsonEodPricesBenchReport { + rows, + bytes, + elapsed_ms, + rows_per_sec, + mb_per_sec, + ns_per_row, + checksum, + stats, + } +} + +pub const DEFAULT_CURATE_BARS_BENCH_ROWS: usize = 2_000_000; +pub const EOD_PRICES_FULL_ROW_COUNT: f64 = 846_000_000.0; +const CURATE_BARS_BENCH_SEED: u64 = 0x570C_4B07_C04A_BA45; +const CURATE_BARS_BENCH_KEY_COUNT: usize = 2_000; +const CURATE_BARS_BENCH_ROWS_PER_KEY_BLOCK: usize = 2_000_000; +const CURATE_BARS_BENCH_SPLIT_COUNT: usize = 2_000; + +/// Errors returned by [`run_curate_bars_benchmark`]. +#[derive(Debug)] +pub enum CurateBarsBenchError { + /// Curation stage or Parquet write error. + Write(crate::curate_bars::CurateBarsWriteError), + /// Fixture exhausted the unique date pool for a key before generating all requested rows. + FixtureDatePoolExhausted { + rows: usize, + key_count: usize, + key_idx: usize, + pool: &'static str, + capacity: u64, + }, +} + +impl std::fmt::Display for CurateBarsBenchError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Write(err) => write!(f, "{err}"), + Self::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + pool, + capacity, + } => write!( + f, + "curate-bars benchmark fixture exhausted unique {pool} date pool (capacity {capacity} dates/key) for key_idx={key_idx} while generating {rows} rows across {key_count} keys" + ), + } + } +} + +impl std::error::Error for CurateBarsBenchError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Write(err) => Some(err), + Self::FixtureDatePoolExhausted { .. } => None, + } + } +} + +impl From for CurateBarsBenchError { + fn from(err: crate::curate_bars::CurateBarsWriteError) -> Self { + Self::Write(err) + } +} + +impl From for CurateBarsBenchError { + fn from(err: crate::curate_bars::CurateBarsError) -> Self { + Self::Write(crate::curate_bars::CurateBarsWriteError::from(err)) + } +} + +impl From for CurateBarsBenchError { + fn from(err: ParquetBarsError) -> Self { + Self::Write(crate::curate_bars::CurateBarsWriteError::from(err)) + } +} + +/// Scales the benchmark key space in `2,000`-key blocks per `2,000,000` rows so larger batches +/// keep ordinary `(source_id, session_date)` pairs unique without exhausting the 2008..=2025 +/// date pool. +fn curate_bars_bench_key_count(rows: usize) -> usize { + let blocks = rows.div_ceil(CURATE_BARS_BENCH_ROWS_PER_KEY_BLOCK).max(1); + CURATE_BARS_BENCH_KEY_COUNT.saturating_mul(blocks) +} + +/// Summary metrics produced by [`run_curate_bars_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateBarsBenchReport { + pub rows: usize, + pub key_count: usize, + pub split_event_count: usize, + pub qm_rows_in: usize, + pub rows_out: usize, + pub pre_2008_rows_out: usize, + pub listings_out: usize, + pub mismatch_samples_out: usize, + pub stage_elapsed_ms: f64, + pub stage_rows_per_sec: f64, + pub stage_ns_per_row: f64, + pub stage_extrap_846m_secs: f64, + pub parquet_elapsed_ms: f64, + pub parquet_rows_per_sec: f64, + pub total_elapsed_ms: f64, + pub total_rows_per_sec: f64, + pub total_extrap_846m_secs: f64, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub read_back_rows: usize, + pub checksum: u64, + pub stats: crate::curate_bars::CurateBars1dStats, +} + +fn mix_str_u64(mut hash: u64, s: &str) -> u64 { + hash = mix_u64(hash, s.len() as u64); + for chunk in s.as_bytes().chunks(8) { + let mut word = 0u64; + for (i, &b) in chunk.iter().enumerate() { + word |= u64::from(b) << (i * 8); + } + hash = mix_u64(hash, word); + } + hash +} + +struct CurateBarsBenchFixture { + bars: Vec>, + qm_volumes: Vec>, + splits: SplitTable, + provider_mapping: ProviderMappingTable, + listing_currencies: std::collections::HashMap>, + key_count: usize, + split_event_count: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_dup_identical: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_dup_conflict: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_alias_identical: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_alias_conflict: usize, +} + +fn build_curate_bars_bench_fixture( + rows: usize, + key_count: usize, + date_span_limit: Option, +) -> Result { + use std::collections::HashMap; + + use crate::session_close::SESSION_CLOSE_MIN_SUPPORTED_DATE; + + assert!( + key_count >= CURATE_BARS_BENCH_KEY_COUNT && key_count % CURATE_BARS_BENCH_KEY_COUNT == 0, + "key_count ({key_count}) must be a positive multiple of {CURATE_BARS_BENCH_KEY_COUNT}" + ); + let scale = key_count / CURATE_BARS_BENCH_KEY_COUNT; + + let min_date = ymd_to_epoch_days(2008, 1, 2).expect("valid start date"); + let max_date = ymd_to_epoch_days(2025, 12, 31).expect("valid end date"); + let full_date_span = (max_date - min_date + 1) as u64; + let date_span = date_span_limit.map_or(full_date_span, |limit| limit.clamp(1, full_date_span)); + let pre_1976_start = ymd_to_epoch_days(1970, 1, 2).expect("valid pre-1976 start"); + let pre_1976_span = (SESSION_CLOSE_MIN_SUPPORTED_DATE - pre_1976_start) as u64; + let pre_2008_in_range_start = + ymd_to_epoch_days(1990, 1, 2).expect("valid pre-2008 in-range start"); + let pre_2008_in_range_end = + ymd_to_epoch_days(2007, 12, 31).expect("valid pre-2008 in-range end"); + let pre_2008_in_range_span = (pre_2008_in_range_end - pre_2008_in_range_start + 1) as u64; + let reuse_end = ymd_to_epoch_days(2016, 12, 31).expect("valid reuse end"); + let reuse_resume = ymd_to_epoch_days(2018, 1, 1).expect("valid reuse resume"); + + let single_range_end = 1_900 * scale; + let reuse_end_idx = 1_950 * scale; + let alias_end_idx = 1_970 * scale; + let missing_curr_end_idx = 1_985 * scale; + let alias_count = alias_end_idx - reuse_end_idx; + let ordinary_key_count = key_count - alias_count; + let reuse_lid_offset = key_count.max(10_000); + let split_count = CURATE_BARS_BENCH_SPLIT_COUNT * scale; + + let keys: Vec = (0..key_count) + .map(|i| { + if i % 5 == 0 { + format!("SYM{i:04}.TO") + } else { + format!("SYM{i:04}.US") + } + }) + .collect(); + + // Build provider_mapping and listing_currencies (scaled proportionally per 2,000-key block): + // - 0..single_range_end: open-ended single range -> listing (i + 1) + // - single_range_end..reuse_end_idx: two ranges with 2017 gap -> listings (i + 1) and (i + reuse_lid_offset + 1) + // - reuse_end_idx..alias_end_idx: aliases of listings 1..=alias_count (cross-source_id collisions) + // - alias_end_idx..missing_curr_end_idx: mapped to listing (i + 1) but omitted from currencies + // - missing_curr_end_idx..key_count: unmapped keys + let mut mapping_rows: Vec = + Vec::with_capacity(key_count + (reuse_end_idx - single_range_end) + 16); + let mut listing_currencies: HashMap> = + HashMap::with_capacity(key_count + (reuse_end_idx - single_range_end) + 16); + + for (i, key) in keys.iter().enumerate() { + let curr = if i % 5 == 0 { + Cow::Borrowed("CAD") + } else { + Cow::Borrowed("USD") + }; + if i < single_range_end { + let lid = (i + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "eod".to_string(), + source_id: key.clone(), + valid_from: pre_1976_start, + valid_to: None, + listing_id: lid, + }); + listing_currencies.insert(lid, curr); + } else if i < reuse_end_idx { + let lid1 = (i + 1) as i32; + let lid2 = (i + reuse_lid_offset + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "eod".to_string(), + source_id: key.clone(), + valid_from: pre_1976_start, + valid_to: Some(reuse_end), + listing_id: lid1, + }); + mapping_rows.push(ProviderMappingRow { + source: "eod".to_string(), + source_id: key.clone(), + valid_from: reuse_resume, + valid_to: None, + listing_id: lid2, + }); + listing_currencies.insert(lid1, curr.clone()); + listing_currencies.insert(lid2, curr); + } else if i < alias_end_idx { + let alias_lid = (i - reuse_end_idx + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "eod".to_string(), + source_id: key.clone(), + valid_from: pre_1976_start, + valid_to: None, + listing_id: alias_lid, + }); + } else if i < missing_curr_end_idx { + let lid = (i + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "eod".to_string(), + source_id: key.clone(), + valid_from: pre_1976_start, + valid_to: None, + listing_id: lid, + }); + // Deliberately omit from listing_currencies to exercise dropped_missing_currency. + } + } + let provider_mapping = + ProviderMappingTable::from_rows(mapping_rows).expect("valid bench provider mapping"); + + let mut rng = SplitMix64::new(CURATE_BARS_BENCH_SEED); + + let mut split_events = Vec::with_capacity(split_count); + for _ in 0..split_count { + let key_idx = (rng.next_u64() as usize) % reuse_end_idx; + let ex_date = min_date + (rng.next_u64() % date_span) as i32; + let ratio = SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()]; + split_events.push((keys[key_idx].clone(), SplitEvent { ex_date, ratio })); + } + let splits = SplitTable::from_events(split_events).unwrap_or_default(); + let split_event_count = splits.event_count(); + + let mut bars: Vec> = Vec::with_capacity(rows); + let mut qm_volumes: Vec> = Vec::with_capacity(rows / 2 + 64); + + // Per-key coprime-stride cursors with explicit usage guards guarantee unique + // (source_id, session_date) pairs for ordinary bars (up to 6,574 dates per key in + // 2008..=2025, 6,573 in 1990..=2007, and 2,190 in 1970..1976) so all builder duplicates and + // cross-source_id collisions are injected explicitly and a cursor can never wrap silently. + const DATE_STRIDE: u64 = 1_571; // prime, coprime to 6,574 = 2 * 19 * 173 + const PRE_1976_STRIDE: u64 = 397; // prime, coprime to 2,190 = 2 * 3 * 5 * 73 + const PRE_2008_IN_RANGE_STRIDE: u64 = 1_571; // prime, coprime to 6,573 = 3 * 7 * 313 + let date_stride = if date_span_limit.is_none() { + DATE_STRIDE + } else { + 1 + }; + let mut date_cursor: Vec = (0..key_count).map(|_| rng.next_u64() % date_span).collect(); + let mut pre_1976_cursor: Vec = (0..key_count) + .map(|_| rng.next_u64() % pre_1976_span) + .collect(); + let mut pre_2008_cursor: Vec = (0..key_count) + .map(|_| rng.next_u64() % pre_2008_in_range_span) + .collect(); + let mut date_used: Vec = vec![0; key_count]; + let mut pre_1976_used: Vec = vec![0; key_count]; + let mut pre_2008_used: Vec = vec![0; key_count]; + + let mut last_alias_pair: Option<(usize, EodDailyBar)> = None; + let mut last_ordinary_bar: Option> = None; + let mut injected_dup_identical = 0usize; + let mut injected_dup_conflict = 0usize; + let mut injected_alias_identical = 0usize; + let mut injected_alias_conflict = 0usize; + + for _ in 0..rows { + let roll = rng.next_u64() % 1_000; + if roll < 4 { + if let Some((alias_idx, mut prev)) = last_alias_pair.take() { + let orig_close_bits = prev.close.to_bits(); + prev.key = keys[reuse_end_idx + alias_idx].clone(); + if roll >= 2 { + // Conflicting cross-source_id collision on the same (listing_id, session_date). + prev.close = (prev.close + 0.05).min(prev.high); + if prev.close.to_bits() == orig_close_bits { + prev.adj_volume += 1.0; + } + injected_alias_conflict += 1; + } else { + injected_alias_identical += 1; + } + bars.push(prev); + continue; + } + } else if roll < 6 { + if let Some(mut prev) = last_ordinary_bar.take() { + if roll == 5 { + // Conflicting same-source_id duplicate dropped in build_bars_1d. + let orig_close_bits = prev.close.to_bits(); + prev.close = (prev.close + 0.05).min(prev.high); + if prev.close.to_bits() == orig_close_bits { + prev.adj_volume += 1.0; + } + injected_dup_conflict += 1; + } else { + injected_dup_identical += 1; + } + bars.push(prev); + continue; + } + } + + let key_idx = if roll < 10 { + (rng.next_u64() as usize) % alias_count + } else { + // Skip alias keys reuse_end_idx..alias_end_idx for ordinary bars so alias collisions + // are purely explicit. + let slot = (rng.next_u64() as usize) % ordinary_key_count; + if slot < reuse_end_idx { + slot + } else { + slot + alias_count + } + }; + let session_date = if roll == 10 || roll == 11 { + if pre_1976_used[key_idx] >= pre_1976_span { + return Err(CurateBarsBenchError::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + pool: "pre-1976", + capacity: pre_1976_span, + }); + } + pre_1976_used[key_idx] += 1; + let offset = pre_1976_cursor[key_idx]; + pre_1976_cursor[key_idx] = (offset + PRE_1976_STRIDE) % pre_1976_span; + pre_1976_start + offset as i32 + } else if (12..32).contains(&roll) { + if pre_2008_used[key_idx] >= pre_2008_in_range_span { + return Err(CurateBarsBenchError::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + pool: "1990..=2007", + capacity: pre_2008_in_range_span, + }); + } + pre_2008_used[key_idx] += 1; + let offset = pre_2008_cursor[key_idx]; + pre_2008_cursor[key_idx] = (offset + PRE_2008_IN_RANGE_STRIDE) % pre_2008_in_range_span; + pre_2008_in_range_start + offset as i32 + } else { + if date_used[key_idx] >= date_span { + return Err(CurateBarsBenchError::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + pool: "2008..=2025", + capacity: date_span, + }); + } + date_used[key_idx] += 1; + let offset = date_cursor[key_idx]; + date_cursor[key_idx] = (offset + date_stride) % date_span; + min_date + offset as i32 + }; + + let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01; + let spread = ((rng.next_u64() % 500) + 10) as f64 * 0.01; + let high = low + spread; + let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); + let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); + let adj_volume = ((rng.next_u64() % 10_000_000) + 100) as f64; + + let b = EodDailyBar { + key: keys[key_idx].clone(), + session_date, + open, + high, + low, + close, + adj_volume, + }; + if key_idx < alias_count && session_date >= min_date { + // Only record alias template when no later split differentiates the two keys. + if splits.cum_factor_after(&b.key, session_date).to_bits() == 1.0_f64.to_bits() { + last_alias_pair = Some((key_idx, b.clone())); + } + } else if (alias_count..single_range_end).contains(&key_idx) && session_date >= min_date { + last_ordinary_bar = Some(b.clone()); + } + if rng.next_u64() & 1 == 0 { + let factor = splits.cum_factor_after(&b.key, session_date); + let raw = unadjust_volume(adj_volume, factor); + let mismatch_roll = rng.next_u64() % 100; + let share_volume = if mismatch_roll == 0 { + raw * 1.15 + } else { + let jitter_bp = (rng.next_u64() % 101) as f64 - 50.0; + raw * (1.0 + jitter_bp * 0.0001) + }; + qm_volumes.push(QmRawVolume { + key: b.key.clone(), + session_date, + share_volume, + }); + } + bars.push(b); + } + + Ok(CurateBarsBenchFixture { + bars, + qm_volumes, + splits, + provider_mapping, + listing_currencies, + key_count, + split_event_count, + injected_dup_identical, + injected_dup_conflict, + injected_alias_identical, + injected_alias_conflict, + }) +} + +fn run_curate_bars_benchmark_tracked( + rows: usize, +) -> Result<(CurateBarsBenchReport, PathBuf), CurateBarsBenchError> { + use std::collections::HashMap; + + use crate::curate_bars::{curate_bars_1d, CurateBars1dStats, CurateBarsWriteError}; + + let temp = BenchTempDir::new_in_with_prefix( + &std::env::temp_dir(), + "curate-etl-bench-curate-bars", + ) + .map_err(|(path, source)| { + CurateBarsBenchError::Write(CurateBarsWriteError::Parquet(ParquetBarsError::Io { + path, + source, + })) + })?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let splits: SplitTable = SplitTable::default(); + let mapping = ProviderMappingTable::default(); + let currencies: HashMap> = HashMap::new(); + let curated = curate_bars_1d( + std::iter::empty::>(), + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + ¤cies, + )?; + let write_stats = + write_bars_1d_dataset(&temp.path, &curated.rows, Bars1dWriteOptions::default())?; + let read_back_rows = verify_parquet_bars_row_count( + &temp.path, + write_stats.rows_by_year.keys().copied(), + 0, + )?; + drop(temp); + return Ok(( + CurateBarsBenchReport { + rows: 0, + key_count: CURATE_BARS_BENCH_KEY_COUNT, + split_event_count: 0, + qm_rows_in: 0, + rows_out: 0, + pre_2008_rows_out: 0, + listings_out: 0, + mismatch_samples_out: 0, + stage_elapsed_ms: 0.0, + stage_rows_per_sec: 0.0, + stage_ns_per_row: 0.0, + stage_extrap_846m_secs: 0.0, + parquet_elapsed_ms: 0.0, + parquet_rows_per_sec: 0.0, + total_elapsed_ms: 0.0, + total_rows_per_sec: 0.0, + total_extrap_846m_secs: 0.0, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum: 0, + stats: CurateBars1dStats::default(), + }, + temp_path, + )); + } + + let key_count = curate_bars_bench_key_count(rows); + let fixture = build_curate_bars_bench_fixture(rows, key_count, None)?; + let qm_rows_in = fixture.qm_volumes.len(); + let split_event_count = fixture.split_event_count; + let fixture_key_count = fixture.key_count; + + // 1. Time pure in-memory curation stage. + let stage_start = Instant::now(); + let curated = curate_bars_1d( + fixture.bars, + &fixture.splits, + fixture.qm_volumes, + 0.01, + &fixture.provider_mapping, + "eod", + &fixture.listing_currencies, + )?; + let stage_elapsed_secs = stage_start.elapsed().as_secs_f64(); + let stage_elapsed_ms = stage_elapsed_secs * 1_000.0; + + let mut hash = 0u64; + for row in &curated.rows { + hash = mix_u64(hash, row.listing_id as u64); + hash = mix_u64(hash, row.ts_micros as u64); + hash = mix_u64(hash, row.session_date as u64); + hash = mix_u64(hash, row.open.to_bits()); + hash = mix_u64(hash, row.high.to_bits()); + hash = mix_u64(hash, row.low.to_bits()); + hash = mix_u64(hash, row.close.to_bits()); + hash = mix_u64(hash, row.volume.to_bits()); + hash = mix_str_u64(hash, row.currency.as_ref()); + hash = mix_str_u64(hash, row.source.as_ref()); + hash = mix_u64(hash, row.known_at_micros as u64); + } + for sample in &curated.mismatch_samples { + hash = mix_str_u64(hash, &sample.key); + hash = mix_u64(hash, sample.session_date as u64); + hash = mix_u64(hash, sample.volume.to_bits()); + hash = mix_u64(hash, sample.share_volume.to_bits()); + hash = mix_u64(hash, sample.rel.to_bits()); + } + let checksum = black_box(hash); + + // 2. Separately time Parquet write to temp dir. + let parquet_start = Instant::now(); + let write_stats = + write_bars_1d_dataset(&temp.path, &curated.rows, Bars1dWriteOptions::default())?; + let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64(); + let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0; + + let read_back_rows = verify_parquet_bars_row_count( + &temp.path, + write_stats.rows_by_year.keys().copied(), + curated.rows.len(), + )?; + + let (stage_rows_per_sec, stage_ns_per_row) = compute_rates(rows, stage_elapsed_secs); + let stage_extrap_846m_secs = if stage_rows_per_sec > 0.0 { + EOD_PRICES_FULL_ROW_COUNT / stage_rows_per_sec + } else { + 0.0 + }; + let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs); + let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs; + let total_elapsed_ms = total_elapsed_secs * 1_000.0; + let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); + let total_extrap_846m_secs = if total_rows_per_sec > 0.0 { + EOD_PRICES_FULL_ROW_COUNT / total_rows_per_sec + } else { + 0.0 + }; + + let pre_2008_rows_out: usize = write_stats + .rows_by_year + .iter() + .filter(|(&year, _)| year < 2008) + .map(|(_, &count)| count) + .sum(); + + let report = CurateBarsBenchReport { + rows, + key_count: fixture_key_count, + split_event_count, + qm_rows_in, + rows_out: curated.stats.rows_out, + pre_2008_rows_out, + listings_out: curated.stats.listings_out, + mismatch_samples_out: curated.mismatch_samples.len(), + stage_elapsed_ms, + stage_rows_per_sec, + stage_ns_per_row, + stage_extrap_846m_secs, + parquet_elapsed_ms, + parquet_rows_per_sec, + total_elapsed_ms, + total_rows_per_sec, + total_extrap_846m_secs, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum, + stats: curated.stats, + }; + + drop(temp); + Ok((report, temp_path)) +} + +/// Runs the fixed-seed `bars_1d` curation stage + Zstd Parquet write benchmark for `rows` +/// source-keyed `eodPrices` bars across `2,000` `String` source keys per `2,000,000`-row block +/// (`2008..=2025` plus in-range `1990..=2007`, pre-1976 out-of-range, unmapped, missing-currency, +/// and cross-`source_id` collision slices). +pub fn run_curate_bars_benchmark(rows: usize) -> Result { + let (report, _) = run_curate_bars_benchmark_tracked(rows)?; + Ok(report) +} + +pub const DEFAULT_CURATE_SHORTS_BENCH_ROWS: usize = 2_000_000; +const CURATE_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_C04A_5407; +const CURATE_SHORTS_BENCH_KEY_COUNT: usize = 12_500; +const CURATE_SHORTS_BENCH_ROWS_PER_KEY_BLOCK: usize = 1_000_000; + +/// Errors returned by [`run_curate_shorts_benchmark`]. +#[derive(Debug)] +pub enum CurateShortsBenchError { + /// Curation stage or Parquet write error. + Write(crate::curate_shorts::CurateShortsWriteError), + /// Fixture exhausted the unique semi-monthly date pool for a key before generating all + /// requested rows. + FixtureDatePoolExhausted { + rows: usize, + key_count: usize, + key_idx: usize, + capacity: usize, + }, +} + +impl std::fmt::Display for CurateShortsBenchError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Write(err) => write!(f, "{err}"), + Self::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + capacity, + } => write!( + f, + "curate-shorts benchmark fixture exhausted unique semi-monthly date pool (capacity {capacity} dates/key) for key_idx={key_idx} while generating {rows} rows across {key_count} keys" + ), + } + } +} + +impl std::error::Error for CurateShortsBenchError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Write(err) => Some(err), + Self::FixtureDatePoolExhausted { .. } => None, + } + } +} + +impl From for CurateShortsBenchError { + fn from(err: crate::curate_shorts::CurateShortsWriteError) -> Self { + Self::Write(err) + } +} + +impl From for CurateShortsBenchError { + fn from(err: crate::curate_shorts::CurateShortsError) -> Self { + Self::Write(crate::curate_shorts::CurateShortsWriteError::from(err)) + } +} + +impl From for CurateShortsBenchError { + fn from(err: ParquetShortsError) -> Self { + Self::Write(crate::curate_shorts::CurateShortsWriteError::from(err)) + } +} + +/// Scales the benchmark key space in `12,500`-key blocks per `1,000,000` rows so larger batches +/// keep ordinary `(key, report_date)` pairs unique across the `218` semi-monthly dates +/// (`2017-04-15..=2026-04-30`) without exhausting the per-key date pool. +fn curate_shorts_bench_key_count(rows: usize) -> usize { + let blocks = rows.div_ceil(CURATE_SHORTS_BENCH_ROWS_PER_KEY_BLOCK).max(1); + CURATE_SHORTS_BENCH_KEY_COUNT.saturating_mul(blocks) +} + +/// Summary metrics produced by [`run_curate_shorts_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateShortsBenchReport { + pub rows: usize, + pub key_count: usize, + pub rows_out: usize, + pub listings_out: usize, + pub stage_elapsed_ms: f64, + pub stage_rows_per_sec: f64, + pub stage_ns_per_row: f64, + pub parquet_elapsed_ms: f64, + pub parquet_rows_per_sec: f64, + pub total_elapsed_ms: f64, + pub total_rows_per_sec: f64, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub read_back_rows: usize, + pub checksum: u64, + pub stats: crate::curate_shorts::CurateShortsStats, +} + +struct CurateShortsBenchFixture { + reports: Vec>, + provider_mapping: ProviderMappingTable, + key_count: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_dup_identical: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_dup_conflict: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_alias_identical: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_alias_conflict: usize, +} + +fn build_curate_shorts_bench_fixture( + rows: usize, + key_count: usize, + date_pool_limit: Option, +) -> Result { + assert!( + key_count >= CURATE_SHORTS_BENCH_KEY_COUNT + && key_count % CURATE_SHORTS_BENCH_KEY_COUNT == 0, + "key_count ({key_count}) must be a positive multiple of {CURATE_SHORTS_BENCH_KEY_COUNT}" + ); + let scale = key_count / CURATE_SHORTS_BENCH_KEY_COUNT; + + let all_dates = semi_monthly_report_dates(); + let pool_len = date_pool_limit.map_or(all_dates.len(), |limit| limit.clamp(1, all_dates.len())); + let valid_from_start = ymd_to_epoch_days(2017, 1, 1).expect("valid start"); + let reuse_end = ymd_to_epoch_days(2021, 6, 30).expect("valid reuse end"); + let reuse_resume = ymd_to_epoch_days(2022, 1, 1).expect("valid reuse resume"); + + let single_range_end = 11_750 * scale; + let reuse_end_idx = 12_125 * scale; + let alias_end_idx = 12_250 * scale; + let alias_count = alias_end_idx - reuse_end_idx; + let ordinary_key_count = key_count - alias_count; + let reuse_lid_offset = key_count.max(100_000); + + let keys: Vec = (0..key_count).map(|i| format!("CEO{i:05}")).collect(); + + // Build provider_mapping (scaled proportionally per 12,500-key block): + // - 0..single_range_end: open-ended single range -> listing (i + 1) + // - single_range_end..reuse_end_idx: two ranges with H2-2021 gap -> listings (i + 1) and (i + reuse_lid_offset + 1) + // - reuse_end_idx..alias_end_idx: aliases of listings 1..=alias_count (cross-key collisions) + // - alias_end_idx..key_count: unmapped keys + let mut mapping_rows: Vec = + Vec::with_capacity(key_count + (reuse_end_idx - single_range_end) + 16); + for (i, key) in keys.iter().enumerate() { + if i < single_range_end { + mapping_rows.push(ProviderMappingRow { + source: "ceo".to_string(), + source_id: key.clone(), + valid_from: valid_from_start, + valid_to: None, + listing_id: (i + 1) as i32, + }); + } else if i < reuse_end_idx { + mapping_rows.push(ProviderMappingRow { + source: "ceo".to_string(), + source_id: key.clone(), + valid_from: valid_from_start, + valid_to: Some(reuse_end), + listing_id: (i + 1) as i32, + }); + mapping_rows.push(ProviderMappingRow { + source: "ceo".to_string(), + source_id: key.clone(), + valid_from: reuse_resume, + valid_to: None, + listing_id: (i + reuse_lid_offset + 1) as i32, + }); + } else if i < alias_end_idx { + let alias_lid = (i - reuse_end_idx + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "ceo".to_string(), + source_id: key.clone(), + valid_from: valid_from_start, + valid_to: None, + listing_id: alias_lid, + }); + } + } + let provider_mapping = + ProviderMappingTable::from_rows(mapping_rows).expect("valid bench provider mapping"); + + let mut rng = SplitMix64::new(CURATE_SHORTS_BENCH_SEED); + let mut reports: Vec> = Vec::with_capacity(rows); + + // Per-key coprime-stride cursors with explicit usage guards guarantee unique + // (key, report_date) pairs across the 218 semi-monthly dates (53 is prime and coprime to + // 218 = 2 * 109) so all builder duplicates and cross-key collisions are injected explicitly. + const DATE_STRIDE: usize = 53; + let date_stride = if date_pool_limit.is_none() { + DATE_STRIDE + } else { + 1 + }; + let mut date_cursor: Vec = (0..key_count) + .map(|_| (rng.next_u64() as usize) % pool_len) + .collect(); + let mut date_used: Vec = vec![0; key_count]; + + let mut last_alias_pair: Option<(usize, CeoShortReport)> = None; + let mut last_ordinary_report: Option> = None; + let mut injected_dup_identical = 0usize; + let mut injected_dup_conflict = 0usize; + let mut injected_alias_identical = 0usize; + let mut injected_alias_conflict = 0usize; + + for _ in 0..rows { + let roll = rng.next_u64() % 1_000; + if roll < 4 { + if let Some((alias_idx, mut prev)) = last_alias_pair.take() { + prev.key = keys[reuse_end_idx + alias_idx].clone(); + if roll >= 2 { + prev.shares_short += 100.0; + injected_alias_conflict += 1; + } else { + injected_alias_identical += 1; + } + reports.push(prev); + continue; + } + } else if roll < 6 { + if let Some(mut prev) = last_ordinary_report.take() { + if roll == 5 { + prev.shares_short += 50.0; + injected_dup_conflict += 1; + } else { + injected_dup_identical += 1; + } + reports.push(prev); + continue; + } + } + + let key_idx = if roll < 12 { + (rng.next_u64() as usize) % alias_count + } else { + // Skip alias keys reuse_end_idx..alias_end_idx for ordinary reports so alias + // collisions are purely explicit. + let slot = (rng.next_u64() as usize) % ordinary_key_count; + if slot < reuse_end_idx { + slot + } else { + slot + alias_count + } + }; + + if date_used[key_idx] >= pool_len { + return Err(CurateShortsBenchError::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + capacity: pool_len, + }); + } + date_used[key_idx] += 1; + let offset = date_cursor[key_idx]; + date_cursor[key_idx] = (offset + date_stride) % pool_len; + let report_date = all_dates[offset]; + + let is_invalid_shares = roll == 12 || roll == 13; + let shares_short = if roll == 12 { + -1.0 + } else if roll == 13 { + f64::NAN + } else { + ((rng.next_u64() % 5_000_000) + 100) as f64 + }; + let net_change = if roll == 14 { + Some(f64::NAN) + } else if rng.next_u64() % 5 == 0 { + None + } else { + Some(((rng.next_u64() % 200_001) as i64 - 100_000) as f64) + }; + let pct_float = if roll == 15 { + Some(f64::INFINITY) + } else if rng.next_u64() % 4 == 0 { + None + } else { + Some((rng.next_u64() % 3_500) as f64 * 0.01) + }; + + let rep = CeoShortReport { + key: keys[key_idx].clone(), + report_date, + shares_short, + net_change, + pct_float, + }; + if !is_invalid_shares { + if key_idx < alias_count { + last_alias_pair = Some((key_idx, rep.clone())); + } else if (alias_count..single_range_end).contains(&key_idx) { + last_ordinary_report = Some(rep.clone()); + } + } + reports.push(rep); + } + + Ok(CurateShortsBenchFixture { + reports, + provider_mapping, + key_count, + injected_dup_identical, + injected_dup_conflict, + injected_alias_identical, + injected_alias_conflict, + }) +} + +fn run_curate_shorts_benchmark_tracked( + rows: usize, +) -> Result<(CurateShortsBenchReport, PathBuf), CurateShortsBenchError> { + use crate::curate_shorts::{curate_shorts, CurateShortsStats, CurateShortsWriteError}; + + let temp = BenchTempDir::new_in_with_prefix( + &std::env::temp_dir(), + "curate-etl-bench-curate-shorts", + ) + .map_err(|(path, source)| { + CurateShortsBenchError::Write(CurateShortsWriteError::Parquet(ParquetShortsError::Io { + path, + source, + })) + })?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let mapping = ProviderMappingTable::default(); + let curated = curate_shorts( + std::iter::empty::>(), + "ceo", + &mapping, + )?; + let write_stats = + write_shorts_dataset(&temp.path, &curated.rows, ShortsWriteOptions::default())?; + let read_back_rows = verify_parquet_shorts_row_count(&temp.path, 0)?; + drop(temp); + return Ok(( + CurateShortsBenchReport { + rows: 0, + key_count: CURATE_SHORTS_BENCH_KEY_COUNT, + rows_out: 0, + listings_out: 0, + stage_elapsed_ms: 0.0, + stage_rows_per_sec: 0.0, + stage_ns_per_row: 0.0, + parquet_elapsed_ms: 0.0, + parquet_rows_per_sec: 0.0, + total_elapsed_ms: 0.0, + total_rows_per_sec: 0.0, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum: 0, + stats: CurateShortsStats::default(), + }, + temp_path, + )); + } + + let key_count = curate_shorts_bench_key_count(rows); + let fixture = build_curate_shorts_bench_fixture(rows, key_count, None)?; + let fixture_key_count = fixture.key_count; + + // 1. Time pure in-memory curation stage. + let stage_start = Instant::now(); + let curated = curate_shorts(fixture.reports, "ceo", &fixture.provider_mapping)?; + let stage_elapsed_secs = stage_start.elapsed().as_secs_f64(); + let stage_elapsed_ms = stage_elapsed_secs * 1_000.0; + + let mut hash = 0u64; + for row in &curated.rows { + hash = mix_u64(hash, row.listing_id as u64); + hash = mix_u64(hash, row.report_date as u64); + hash = mix_u64(hash, row.known_at_micros as u64); + hash = mix_u64(hash, row.shares_short.to_bits()); + hash = match row.net_change { + Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()), + None => mix_u64(hash, 0), + }; + hash = match row.pct_float { + Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()), + None => mix_u64(hash, 0), + }; + hash = mix_str_u64(hash, row.source.as_ref()); + } + let checksum = black_box(hash); + + // 2. Separately time Parquet write to temp dir. + let parquet_start = Instant::now(); + let write_stats = + write_shorts_dataset(&temp.path, &curated.rows, ShortsWriteOptions::default())?; + let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64(); + let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0; + + let read_back_rows = verify_parquet_shorts_row_count(&temp.path, curated.rows.len())?; + + let (stage_rows_per_sec, stage_ns_per_row) = compute_rates(rows, stage_elapsed_secs); + let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs); + let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs; + let total_elapsed_ms = total_elapsed_secs * 1_000.0; + let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); + + let report = CurateShortsBenchReport { + rows, + key_count: fixture_key_count, + rows_out: curated.stats.rows_out, + listings_out: curated.stats.listings_out, + stage_elapsed_ms, + stage_rows_per_sec, + stage_ns_per_row, + parquet_elapsed_ms, + parquet_rows_per_sec, + total_elapsed_ms, + total_rows_per_sec, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum, + stats: curated.stats, + }; + + drop(temp); + Ok((report, temp_path)) +} + +/// Runs the fixed-seed `shorts` curation stage + Zstd Parquet write benchmark for `rows` +/// source-keyed `ceoShorts` reports across `12,500` `String` source keys per `1,000,000`-row block +/// (semi-monthly dates `2017-04-15..=2026-04-30`, with date-ranged ticker reuse, unmapped keys, +/// builder duplicates, invalid numeric slices, and cross-key collisions). +pub fn run_curate_shorts_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_curate_shorts_benchmark_tracked(rows)?; + Ok(report) +} + +pub const DEFAULT_CURATE_EVENTS_BENCH_ROWS: usize = 500_000; +const CURATE_EVENTS_BENCH_SEED: u64 = 0x570C_4B07_C04A_E7E4; +const CURATE_EVENTS_BENCH_KEY_COUNT: usize = 20_000; + +/// Summary metrics produced by [`run_curate_events_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateEventsBenchReport { + pub rows: usize, + pub filings_in: usize, + pub earnings_in: usize, + pub key_count: usize, + pub rows_out: usize, + pub listings_out: usize, + pub stage_elapsed_ms: f64, + pub stage_rows_per_sec: f64, + pub stage_ns_per_row: f64, + pub parquet_elapsed_ms: f64, + pub parquet_rows_per_sec: f64, + pub total_elapsed_ms: f64, + pub total_rows_per_sec: f64, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub read_back_rows: usize, + pub checksum: u64, + pub stats: crate::curate_events::CurateEventsStats, +} + +fn run_curate_events_benchmark_tracked( + rows: usize, +) -> Result<(CurateEventsBenchReport, PathBuf), crate::curate_events::CurateEventsWriteError> { + use crate::curate_events::{curate_events, CurateEventsStats, CurateEventsWriteError}; + + let temp = BenchTempDir::new_in_with_prefix( + &std::env::temp_dir(), + "curate-etl-bench-curate-events", + ) + .map_err(|(path, source)| { + CurateEventsWriteError::Parquet(ParquetEventsError::Io { path, source }) + })?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let mapping = ProviderMappingTable::default(); + let curated = curate_events( + std::iter::empty::>(), + std::iter::empty::>(), + "qm", + &mapping, + )?; + let write_stats = + write_events_dataset(&temp.path, &curated.rows, EventsWriteOptions::default())?; + let read_back_rows = + verify_parquet_events_row_count(&temp.path, write_stats.rows_by_year.keys().copied(), 0)?; + drop(temp); + return Ok(( + CurateEventsBenchReport { + rows: 0, + filings_in: 0, + earnings_in: 0, + key_count: CURATE_EVENTS_BENCH_KEY_COUNT, + rows_out: 0, + listings_out: 0, + stage_elapsed_ms: 0.0, + stage_rows_per_sec: 0.0, + stage_ns_per_row: 0.0, + parquet_elapsed_ms: 0.0, + parquet_rows_per_sec: 0.0, + total_elapsed_ms: 0.0, + total_rows_per_sec: 0.0, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum: 0, + stats: CurateEventsStats::default(), + }, + temp_path, + )); + } + + let valid_from_start = ymd_to_epoch_days(2003, 1, 1).expect("valid start"); + let reuse_end = ymd_to_epoch_days(2021, 6, 30).expect("valid reuse end"); + let reuse_resume = ymd_to_epoch_days(2022, 1, 1).expect("valid reuse resume"); + + let key_count = CURATE_EVENTS_BENCH_KEY_COUNT; + let single_range_end = 18_800usize; + let reuse_end_idx = 19_400usize; + let alias_end_idx = 19_700usize; + let alias_count = alias_end_idx - reuse_end_idx; + let ordinary_key_count = key_count - alias_count; + + let keys: Vec = (0..key_count).map(|i| format!("QM{i:05}")).collect(); + + // Build provider_mapping: + // - 0..18_800: single open-ended range from 2003-01-01 -> listing (i + 1) + // - 18_800..19_400: two ranges with H2-2021 gap -> listings (i + 1) and (i + 100_001) + // - 19_400..19_700: alias keys for listings 1..=300 (cross-key duplicates) + // - 19_700..20_000: unmapped keys + let mut mapping_rows: Vec = + Vec::with_capacity(key_count + (reuse_end_idx - single_range_end) + 16); + for (i, key) in keys.iter().enumerate() { + if i < single_range_end { + mapping_rows.push(ProviderMappingRow { + source: "qm".to_string(), + source_id: key.clone(), + valid_from: valid_from_start, + valid_to: None, + listing_id: (i + 1) as i32, + }); + } else if i < reuse_end_idx { + mapping_rows.push(ProviderMappingRow { + source: "qm".to_string(), + source_id: key.clone(), + valid_from: valid_from_start, + valid_to: Some(reuse_end), + listing_id: (i + 1) as i32, + }); + mapping_rows.push(ProviderMappingRow { + source: "qm".to_string(), + source_id: key.clone(), + valid_from: reuse_resume, + valid_to: None, + listing_id: (i + 100_001) as i32, + }); + } else if i < alias_end_idx { + let alias_lid = (i - reuse_end_idx + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "qm".to_string(), + source_id: key.clone(), + valid_from: valid_from_start, + valid_to: None, + listing_id: alias_lid, + }); + } + } + let provider_mapping = + ProviderMappingTable::from_rows(mapping_rows).expect("valid bench provider mapping"); + + let min_filing_date = valid_from_start; + let max_filing_date = ymd_to_epoch_days(2026, 4, 30).expect("valid max filing date"); + let filing_span = (max_filing_date - min_filing_date + 1) as u64; + + let min_earning_date = ymd_to_epoch_days(2008, 1, 1).expect("valid min earning date"); + let max_earning_date = max_filing_date; + let earning_span = (max_earning_date - min_earning_date + 1) as u64; + + let earnings_target = (rows * 15) / 1_000; + let filings_target = rows - earnings_target; + + let mut rng = SplitMix64::new(CURATE_EVENTS_BENCH_SEED); + let mut filings: Vec> = Vec::with_capacity(filings_target); + let mut link_pool: Vec<(usize, i32)> = Vec::with_capacity(earnings_target.min(16_384)); + let mut last_valid_filing: Option> = None; + let mut last_alias_filing: Option<(usize, QmFiling)> = None; + + for idx in 0..filings_target { + let roll = rng.next_u64() % 1_000; + if roll < 4 { + if let Some(prev) = last_valid_filing.clone() { + filings.push(prev); + continue; + } + } else if roll < 8 { + if let Some((alias_idx, mut prev)) = last_alias_filing.take() { + prev.key = keys[reuse_end_idx + alias_idx].clone(); + filings.push(prev); + continue; + } + } + + let key_idx = if roll < 20 { + (rng.next_u64() as usize) % alias_count + } else { + let slot = (rng.next_u64() as usize) % ordinary_key_count; + if slot < reuse_end_idx { + slot + } else { + slot + alias_count + } + }; + + let epoch_day = min_filing_date + (rng.next_u64() % filing_span) as i32; + let (y, m, d) = epoch_days_to_ymd(epoch_day); + let form_idx = (rng.next_u64() as usize) % BENCH_FORM_TYPES.len(); + let form_type = BENCH_FORM_TYPES[form_idx].to_string(); + let filing_id = if rng.next_u64() % 10 == 0 { + None + } else { + Some(format!("F{idx:08}")) + }; + let url = if rng.next_u64() % 4 == 0 { + None + } else { + Some(format!("https://filings.example/{key_idx}/{idx}")) + }; + + let timefiled = match roll { + 8..=9 => "bad-timestamp".to_string(), + 10..=11 => format!("{y:04}-{m:02}-{d:02}T12:00:00 PST"), + 12..=13 => format!("{y:04}-02-30T12:00:00 EST"), + 14 => format!("{y:04}-{m:02}-{d:02}T25:00:00 EST"), + _ => { + // Mix morning, midday, and late-evening ET (crossing into next UTC day). + let hour = if roll < 65 { + 21 + (rng.next_u64() % 3) as u32 + } else { + 6 + (rng.next_u64() % 13) as u32 + }; + let minute = (rng.next_u64() % 60) as u32; + let second = (rng.next_u64() % 60) as u32; + let zone = if (4..=10).contains(&m) { "EDT" } else { "EST" }; + let ts = format!("{y:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02} {zone}"); + if matches!(form_idx, 0 | 1 | 15) && link_pool.len() < 16_384 { + link_pool.push((key_idx, epoch_day)); + } + ts + } + }; + + let row = QmFiling { + key: keys[key_idx].clone(), + timefiled, + form_type, + filing_id, + url, + }; + if roll >= 15 { + if key_idx < alias_count { + last_alias_filing = Some((key_idx, row.clone())); + } + last_valid_filing = Some(row.clone()); + } + filings.push(row); + } + + let mut earnings: Vec> = Vec::with_capacity(earnings_target); + let mut last_valid_earning: Option> = None; + + for _ in 0..earnings_target { + let roll = rng.next_u64() % 1_000; + if roll < 15 { + if let Some(prev) = last_valid_earning.clone() { + earnings.push(prev); + continue; + } + } else if roll < 25 { + if let Some(mut prev) = last_valid_earning.clone() { + prev.actual_eps = Some(prev.actual_eps.unwrap_or(0.0) + 0.10); + earnings.push(prev); + continue; + } + } + + let (key_idx, report_date) = if roll < 30 && !link_pool.is_empty() { + let slot = (rng.next_u64() as usize) % ordinary_key_count; + let k = if slot < reuse_end_idx { + slot + } else { + slot + alias_count + }; + let d = ymd_to_epoch_days(2005, 6, 15).expect("valid pre-2008 date"); + (k, d) + } else if roll < 450 && !link_pool.is_empty() { + let pick = (rng.next_u64() as usize) % link_pool.len(); + link_pool[pick] + } else { + let slot = (rng.next_u64() as usize) % ordinary_key_count; + let k = if slot < reuse_end_idx { + slot + } else { + slot + alias_count + }; + let d = min_earning_date + (rng.next_u64() % earning_span) as i32; + (k, d) + }; + + let announce_time = + BENCH_ANNOUNCE_TIMES[(rng.next_u64() as usize) % BENCH_ANNOUNCE_TIMES.len()] + .to_string(); + let actual_eps = if roll % 50 == 0 { + Some(f64::NAN) + } else { + Some((((rng.next_u64() % 1_000) as f64) - 200.0) * 0.01) + }; + let revenue = Some(((rng.next_u64() % 5_000_000) + 10_000) as f64); + + let row = QmEarning { + key: keys[key_idx].clone(), + report_date, + announce_time, + fiscal_period_end: Some(report_date - 35), + actual_eps, + revenue, + }; + if roll >= 30 { + last_valid_earning = Some(row.clone()); + } + earnings.push(row); + } + + shuffle_slice(&mut filings, &mut rng); + shuffle_slice(&mut earnings, &mut rng); + + let filings_in = filings.len(); + let earnings_in = earnings.len(); + + // 1. Time pure in-memory curation stage. + let stage_start = Instant::now(); + let curated = curate_events(filings, earnings, "qm", &provider_mapping)?; + let stage_elapsed_secs = stage_start.elapsed().as_secs_f64(); + let stage_elapsed_ms = stage_elapsed_secs * 1_000.0; + + let mut hash = 0u64; + for row in &curated.rows { + hash = mix_u64(hash, row.listing_id as u64); + hash = mix_u64(hash, row.ts_micros as u64); + hash = mix_u64(hash, row.known_at_micros as u64); + hash = mix_bytes(hash, row.known_at_source.as_bytes()); + hash = mix_bytes(hash, row.kind.as_bytes()); + hash = mix_bytes(hash, row.subtype.as_bytes()); + hash = mix_bytes(hash, row.payload_json.as_bytes()); + } + let checksum = black_box(hash); + + // 2. Separately time Parquet write to temp dir. + let parquet_start = Instant::now(); + let write_stats = + write_events_dataset(&temp.path, &curated.rows, EventsWriteOptions::default())?; + let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64(); + let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0; + + let read_back_rows = verify_parquet_events_row_count( + &temp.path, + write_stats.rows_by_year.keys().copied(), + curated.rows.len(), + )?; + + let (stage_rows_per_sec, stage_ns_per_row) = compute_rates(rows, stage_elapsed_secs); + let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs); + let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs; + let total_elapsed_ms = total_elapsed_secs * 1_000.0; + let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); + + let report = CurateEventsBenchReport { + rows, + filings_in, + earnings_in, + key_count, + rows_out: curated.stats.rows_out, + listings_out: curated.stats.listings_out, + stage_elapsed_ms, + stage_rows_per_sec, + stage_ns_per_row, + parquet_elapsed_ms, + parquet_rows_per_sec, + total_elapsed_ms, + total_rows_per_sec, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum, + stats: curated.stats, + }; + + drop(temp); + Ok((report, temp_path)) +} + +/// Runs the fixed-seed `events` curation stage + Zstd Parquet write benchmark for `rows` +/// source-keyed `qmFilings` (~98.5%) and `qmEarnings` (~1.5%) rows across `20,000` `String` +/// source keys (single-range, ticker-reuse with gap, alias duplicates, unmapped keys, pre-2008 +/// filings, late-evening ET, linked/unlinked earnings, and builder skips/duplicates). +pub fn run_curate_events_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_curate_events_benchmark_tracked(rows)?; + Ok(report) +} + +pub const DEFAULT_CURATE_FX_BENCH_ROWS: usize = 20_000; +const CURATE_FX_BENCH_SEED: u64 = 0x570C_4B07_C04A_F81D; + +/// Summary metrics produced by [`run_curate_fx_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateFxBenchReport { + pub rows: usize, + pub eod_rows_in: usize, + pub te_rows_in: usize, + pub rows_out: usize, + pub stage_elapsed_ms: f64, + pub stage_rows_per_sec: f64, + pub stage_ns_per_row: f64, + pub parquet_elapsed_ms: f64, + pub parquet_rows_per_sec: f64, + pub total_elapsed_ms: f64, + pub total_rows_per_sec: f64, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub read_back_rows: usize, + pub checksum: u64, + pub stats: crate::curate_fx::CurateFx1dStats, +} + +fn run_curate_fx_benchmark_tracked( + rows: usize, +) -> Result<(CurateFxBenchReport, PathBuf), crate::curate_fx::CurateFxWriteError> { + use crate::curate_fx::{curate_fx_1d, CurateFx1dStats, CurateFxWriteError}; + + let temp = BenchTempDir::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-curate-fx") + .map_err(|(path, source)| CurateFxWriteError::Parquet(ParquetFxError::Io { path, source }))?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let curated = curate_fx_1d(&[], &[])?; + let write_stats = + write_fx_1d_dataset(&temp.path, &curated.rows, Fx1dWriteOptions::default())?; + let read_back_rows = verify_parquet_fx_row_count(&temp.path, 0)?; + drop(temp); + return Ok(( + CurateFxBenchReport { + rows: 0, + eod_rows_in: 0, + te_rows_in: 0, + rows_out: 0, + stage_elapsed_ms: 0.0, + stage_rows_per_sec: 0.0, + stage_ns_per_row: 0.0, + parquet_elapsed_ms: 0.0, + parquet_rows_per_sec: 0.0, + total_elapsed_ms: 0.0, + total_rows_per_sec: 0.0, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum: 0, + stats: CurateFx1dStats::default(), + }, + temp_path, + )); + } + + let mut rng = SplitMix64::new(CURATE_FX_BENCH_SEED); + let (eod, te) = generate_fx_bench_inputs(rows, &mut rng); + let eod_rows_in = eod.len(); + let te_rows_in = te.len(); + + // 1. Time pure in-memory curation stage. + let stage_start = Instant::now(); + let curated = curate_fx_1d(&eod, &te)?; + let stage_elapsed_secs = stage_start.elapsed().as_secs_f64(); + let stage_elapsed_ms = stage_elapsed_secs * 1_000.0; + + let mut hash = 0u64; + for row in &curated.rows { + hash = mix_str_u64(hash, row.pair.as_ref()); + hash = mix_u64(hash, row.session_date as u64); + hash = mix_u64(hash, row.ts_micros as u64); + hash = mix_u64(hash, row.open.to_bits()); + hash = mix_u64(hash, row.high.to_bits()); + hash = mix_u64(hash, row.low.to_bits()); + hash = mix_u64(hash, row.close.to_bits()); + hash = mix_str_u64(hash, row.source.as_ref()); + hash = mix_u64(hash, row.known_at_micros as u64); + } + let checksum = black_box(hash); + + // 2. Separately time Parquet write to temp dir. + let parquet_start = Instant::now(); + let write_stats = + write_fx_1d_dataset(&temp.path, &curated.rows, Fx1dWriteOptions::default())?; + let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64(); + let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0; + + let read_back_rows = verify_parquet_fx_row_count(&temp.path, curated.rows.len())?; + + let (stage_rows_per_sec, stage_ns_per_row) = compute_rates(rows, stage_elapsed_secs); + let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs); + let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs; + let total_elapsed_ms = total_elapsed_secs * 1_000.0; + let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); + + let report = CurateFxBenchReport { + rows, + eod_rows_in, + te_rows_in, + rows_out: curated.stats.rows_out, + stage_elapsed_ms, + stage_rows_per_sec, + stage_ns_per_row, + parquet_elapsed_ms, + parquet_rows_per_sec, + total_elapsed_ms, + total_rows_per_sec, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum, + stats: curated.stats, + }; + + drop(temp); + Ok((report, temp_path)) +} + +/// Runs the fixed-seed `fx_1d` curation stage + Zstd Parquet write benchmark for `rows` total +/// daily USD/CAD bars across `CAD.FOREX` (~80%) and `teMarketData.USDCAD` (~20%), separately +/// timing in-memory `curate_fx_1d` and Zstd Parquet `write_fx_1d_dataset` into a temp directory +/// removed on drop. +pub fn run_curate_fx_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_curate_fx_benchmark_tracked(rows)?; + Ok(report) +} + #[cfg(test)] mod tests { use super::*; @@ -2390,4 +5819,906 @@ mod tests { assert!(colliding.is_dir()); assert_eq!(fs::read(&sentinel).unwrap(), b"do-not-delete"); } + + #[test] + fn parquet_shorts_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_parquet_shorts_benchmark_tracked(25_000).unwrap(); + let (b, dir_b) = run_parquet_shorts_benchmark_tracked(25_000).unwrap(); + + assert!(!dir_a.exists(), "temp dir {} should be removed", dir_a.display()); + assert!(!dir_b.exists(), "temp dir {} should be removed", dir_b.display()); + assert_eq!(a.rows, 25_000); + assert_eq!(a.read_back_rows, 25_000); + assert_eq!(a.listing_count, PARQUET_SHORTS_BENCH_BASE_LISTINGS); + assert_eq!(a.files_written, 1); + assert_eq!(a.files_written, b.files_written); + assert_eq!(a.row_groups_written, b.row_groups_written); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.raw_row_bytes, PARQUET_SHORTS_RAW_ROW_BYTES); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); + assert!(a.bytes_per_row.is_finite() && a.bytes_per_row > 0.0); + assert!(a.compression_ratio.is_finite() && a.compression_ratio > 0.0); + } + + #[test] + fn parquet_shorts_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_parquet_shorts_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.listing_count, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.row_groups_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.raw_row_bytes, PARQUET_SHORTS_RAW_ROW_BYTES); + assert_eq!(report.elapsed_ms, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.mb_per_sec, 0.0); + assert_eq!(report.bytes_per_row, 0.0); + assert_eq!(report.compression_ratio, 0.0); + } + + #[test] + fn verify_parquet_shorts_row_count_returns_error_on_mismatch() { + let temp = BenchTempDir::new_shorts().unwrap(); + let dates = semi_monthly_report_dates_with_known_at(); + let iter = ParquetShortsBenchIter::new(250, dates); + write_shorts_dataset(&temp.path, iter, ShortsWriteOptions::default()).unwrap(); + + let matched = verify_parquet_shorts_row_count(&temp.path, 250).unwrap(); + assert_eq!(matched, 250); + + let err = verify_parquet_shorts_row_count(&temp.path, 255).unwrap_err(); + let msg = err.to_string(); + assert!( + matches!(err, ParquetShortsError::Parquet { .. }), + "expected Parquet error, got {err:?}" + ); + assert!( + msg.contains("255") && msg.contains("250"), + "error must report expected (255) and actual (250) row counts, got: {msg}" + ); + } + + #[test] + fn parquet_events_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_parquet_events_benchmark_tracked(10_000).unwrap(); + let (b, dir_b) = run_parquet_events_benchmark_tracked(10_000).unwrap(); + + assert!(!dir_a.exists(), "temp dir {} should be removed", dir_a.display()); + assert!(!dir_b.exists(), "temp dir {} should be removed", dir_b.display()); + assert_eq!(a.rows, 10_000); + assert_eq!(a.read_back_rows, 10_000); + assert_eq!(a.listing_count, PARQUET_EVENTS_BENCH_BASE_LISTINGS); + assert_eq!(a.files_written, b.files_written); + assert!(a.files_written >= 2); + assert_eq!(a.row_groups_written, b.row_groups_written); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.avg_raw_row_bytes.to_bits(), b.avg_raw_row_bytes.to_bits()); + assert!( + (150.0..=350.0).contains(&a.avg_raw_row_bytes), + "unexpected avg_raw_row_bytes: {}", + a.avg_raw_row_bytes + ); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); + assert!(a.bytes_per_row.is_finite() && a.bytes_per_row > 0.0); + assert!(a.compression_ratio.is_finite() && a.compression_ratio > 0.0); + } + + #[test] + fn parquet_events_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_parquet_events_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.listing_count, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.row_groups_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.avg_raw_row_bytes, 0.0); + assert_eq!(report.elapsed_ms, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.mb_per_sec, 0.0); + assert_eq!(report.bytes_per_row, 0.0); + assert_eq!(report.compression_ratio, 0.0); + } + + #[test] + fn verify_parquet_events_row_count_returns_error_on_mismatch() { + let temp = BenchTempDir::new_events().unwrap(); + let mut raw_bytes = 0u64; + let iter = ParquetEventsBenchIter::new(250, &mut raw_bytes); + let stats = + write_events_dataset(&temp.path, iter, EventsWriteOptions::default()).unwrap(); + + let matched = + verify_parquet_events_row_count(&temp.path, stats.rows_by_year.keys().copied(), 250) + .unwrap(); + assert_eq!(matched, 250); + + let err = + verify_parquet_events_row_count(&temp.path, stats.rows_by_year.keys().copied(), 255) + .unwrap_err(); + let msg = err.to_string(); + assert!( + matches!(err, ParquetEventsError::Parquet { .. }), + "expected Parquet error, got {err:?}" + ); + assert!( + msg.contains("255") && msg.contains("250"), + "error must report expected (255) and actual (250) row counts, got: {msg}" + ); + } + + #[test] + fn parquet_fx_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_parquet_fx_benchmark_tracked(25_000).unwrap(); + let (b, dir_b) = run_parquet_fx_benchmark_tracked(25_000).unwrap(); + + assert!(!dir_a.exists(), "temp dir {} should be removed", dir_a.display()); + assert!(!dir_b.exists(), "temp dir {} should be removed", dir_b.display()); + assert_eq!(a.rows, 25_000); + assert_eq!(a.read_back_rows, 25_000); + assert_eq!(a.pair_count, PARQUET_FX_BENCH_BASE_PAIRS); + assert_eq!(a.files_written, 1); + assert_eq!(a.files_written, b.files_written); + assert_eq!(a.row_groups_written, b.row_groups_written); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.raw_row_bytes, PARQUET_FX_RAW_ROW_BYTES); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); + assert!(a.bytes_per_row.is_finite() && a.bytes_per_row > 0.0); + assert!(a.compression_ratio.is_finite() && a.compression_ratio > 0.0); + } + + #[test] + fn parquet_fx_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_parquet_fx_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.pair_count, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.row_groups_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.raw_row_bytes, PARQUET_FX_RAW_ROW_BYTES); + assert_eq!(report.elapsed_ms, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.mb_per_sec, 0.0); + assert_eq!(report.bytes_per_row, 0.0); + assert_eq!(report.compression_ratio, 0.0); + } + + #[test] + fn verify_parquet_fx_row_count_returns_error_on_mismatch() { + let temp = BenchTempDir::new_fx().unwrap(); + let weekdays = collect_bench_weekdays_1971_2026(); + let iter = ParquetFxBenchIter::new(250, weekdays); + write_fx_1d_dataset(&temp.path, iter, Fx1dWriteOptions::default()).unwrap(); + + let matched = verify_parquet_fx_row_count(&temp.path, 250).unwrap(); + assert_eq!(matched, 250); + + let err = verify_parquet_fx_row_count(&temp.path, 255).unwrap_err(); + let msg = err.to_string(); + assert!( + matches!(err, ParquetFxError::Parquet { .. }), + "expected Parquet error, got {err:?}" + ); + assert!( + msg.contains("255") && msg.contains("250"), + "error must report expected (255) and actual (250) row counts, got: {msg}" + ); + } + + #[test] + fn parquet_fx_bench_iter_pair_labels_stay_sorted_across_10000_boundary() { + let single_day = vec![ymd_to_epoch_days(2024, 1, 2).expect("valid date")]; + let iter = ParquetFxBenchIter::new(10_002, single_day); + assert_eq!(iter.pair_count, 10_002); + assert_eq!(iter.pair_width, 5); + assert_eq!(iter.pair_label(0).as_ref(), "FX00000"); + assert_eq!(iter.pair_label(9_999).as_ref(), "FX09999"); + assert_eq!(iter.pair_label(10_000).as_ref(), "FX10000"); + assert_eq!(iter.pair_label(10_001).as_ref(), FX_PAIR_USDCAD); + assert!(iter.pair_label(9_999).as_ref() < iter.pair_label(10_000).as_ref()); + assert!(iter.pair_label(10_000).as_ref() < iter.pair_label(10_001).as_ref()); + + let mut prev_pair = String::new(); + let mut count = 0usize; + for row in iter { + if count > 0 { + assert!( + prev_pair.as_str() < row.pair.as_ref(), + "pair order regressed: {prev_pair} >= {}", + row.pair + ); + } + prev_pair.clear(); + prev_pair.push_str(row.pair.as_ref()); + count += 1; + } + assert_eq!(count, 10_002); + } + + #[test] + fn parquet_adj_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_parquet_adj_benchmark_tracked(25_000).unwrap(); + let (b, dir_b) = run_parquet_adj_benchmark_tracked(25_000).unwrap(); + + assert!(!dir_a.exists(), "temp dir {} should be removed", dir_a.display()); + assert!(!dir_b.exists(), "temp dir {} should be removed", dir_b.display()); + assert_eq!(a.rows, 25_000); + assert_eq!(a.read_back_rows, 25_000); + assert_eq!(a.listing_count, PARQUET_ADJ_BENCH_BASE_LISTINGS); + assert_eq!(a.files_written, 1); + assert_eq!(a.files_written, b.files_written); + assert_eq!(a.row_groups_written, b.row_groups_written); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.raw_row_bytes, PARQUET_ADJ_RAW_ROW_BYTES); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); + assert!(a.bytes_per_row.is_finite() && a.bytes_per_row > 0.0); + assert!(a.compression_ratio.is_finite() && a.compression_ratio > 0.0); + } + + #[test] + fn parquet_adj_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_parquet_adj_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.listing_count, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.row_groups_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.raw_row_bytes, PARQUET_ADJ_RAW_ROW_BYTES); + assert_eq!(report.elapsed_ms, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.mb_per_sec, 0.0); + assert_eq!(report.bytes_per_row, 0.0); + assert_eq!(report.compression_ratio, 0.0); + } + + #[test] + fn verify_parquet_adj_row_count_returns_error_on_mismatch() { + let temp = BenchTempDir::new_adj().unwrap(); + let weekdays = collect_bench_weekdays_1990_2025(); + let iter = ParquetAdjBenchIter::new(250, weekdays); + write_adj_factors_dataset(&temp.path, iter, AdjFactorsWriteOptions::default()).unwrap(); + + let matched = verify_parquet_adj_row_count(&temp.path, 250).unwrap(); + assert_eq!(matched, 250); + + let err = verify_parquet_adj_row_count(&temp.path, 255).unwrap_err(); + let msg = err.to_string(); + assert!( + matches!(err, ParquetAdjError::Parquet { .. }), + "expected Parquet error, got {err:?}" + ); + assert!( + msg.contains("255") && msg.contains("250"), + "error must report expected (255) and actual (250) row counts, got: {msg}" + ); + } + + #[test] + fn parquet_corporate_actions_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_parquet_corporate_actions_benchmark_tracked(25_000).unwrap(); + let (b, dir_b) = run_parquet_corporate_actions_benchmark_tracked(25_000).unwrap(); + + assert!( + !dir_a.exists(), + "temp dir {} should be removed", + dir_a.display() + ); + assert!( + !dir_b.exists(), + "temp dir {} should be removed", + dir_b.display() + ); + assert_eq!(a.rows, 25_000); + assert_eq!(a.read_back_rows, 25_000); + assert_eq!(a.listing_count, PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS); + assert_eq!(a.files_written, 1); + assert_eq!(a.files_written, b.files_written); + assert_eq!(a.row_groups_written, b.row_groups_written); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.raw_row_bytes, PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); + assert!(a.bytes_per_row.is_finite() && a.bytes_per_row > 0.0); + assert!(a.compression_ratio.is_finite() && a.compression_ratio > 0.0); + } + + #[test] + fn parquet_corporate_actions_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_parquet_corporate_actions_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.listing_count, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.row_groups_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.raw_row_bytes, PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES); + assert_eq!(report.elapsed_ms, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.mb_per_sec, 0.0); + assert_eq!(report.bytes_per_row, 0.0); + assert_eq!(report.compression_ratio, 0.0); + } + + #[test] + fn verify_parquet_corporate_actions_row_count_returns_error_on_mismatch() { + let temp = BenchTempDir::new_corporate_actions().unwrap(); + let weekdays = collect_bench_weekdays_1990_2025(); + let iter = ParquetCorporateActionsBenchIter::new(250, weekdays); + write_corporate_actions_dataset(&temp.path, iter, CorporateActionsWriteOptions::default()) + .unwrap(); + + let matched = verify_parquet_corporate_actions_row_count(&temp.path, 250).unwrap(); + assert_eq!(matched, 250); + + let err = verify_parquet_corporate_actions_row_count(&temp.path, 255).unwrap_err(); + let msg = err.to_string(); + assert!( + matches!(err, ParquetCorporateActionsError::Parquet { .. }), + "expected Parquet error, got {err:?}" + ); + assert!( + msg.contains("255") && msg.contains("250"), + "error must report expected (255) and actual (250) row counts, got: {msg}" + ); + } + + #[test] + fn bson_eod_prices_benchmark_small_run_is_deterministic() { + let a = run_bson_eod_prices_benchmark(20_000); + let b = run_bson_eod_prices_benchmark(20_000); + + assert_eq!(a.rows, 20_000); + assert_eq!(a.bytes, b.bytes); + assert!(a.bytes > 0); + assert_eq!(a.checksum, b.checksum); + assert_eq!(a.stats, b.stats); + assert_eq!(a.stats.docs_in, 20_000); + assert_eq!(a.stats.decoded + a.stats.rejected_total(), a.stats.docs_in); + assert!(a.stats.decoded > 19_000); + assert!(a.stats.rejected_total() > 0); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); + assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0); + } + + #[test] + fn bson_eod_prices_benchmark_zero_rows_handles_cleanly() { + let report = run_bson_eod_prices_benchmark(0); + assert_eq!(report.rows, 0); + assert_eq!(report.bytes, 0); + assert_eq!(report.elapsed_ms, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.mb_per_sec, 0.0); + assert_eq!(report.ns_per_row, 0.0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stats, BsonEodDecodeStats::default()); + } + + #[test] + fn curate_bars_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_curate_bars_benchmark_tracked(20_000).unwrap(); + let (b, dir_b) = run_curate_bars_benchmark_tracked(20_000).unwrap(); + + assert!( + !dir_a.exists(), + "temp dir {} should be removed", + dir_a.display() + ); + assert!( + !dir_b.exists(), + "temp dir {} should be removed", + dir_b.display() + ); + assert_eq!(a.rows, 20_000); + assert_eq!(a.stats.builder.bars_in, 20_000); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.read_back_rows, a.rows_out); + assert_eq!(a.listings_out, b.listings_out); + assert_eq!(a.files_written, b.files_written); + assert!(a.files_written >= 2); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.stage_rows_per_sec.is_finite() && a.stage_rows_per_sec >= 0.0); + assert!(a.stage_extrap_846m_secs.is_finite() && a.stage_extrap_846m_secs >= 0.0); + assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0); + assert!(a.total_rows_per_sec.is_finite() && a.total_rows_per_sec >= 0.0); + assert!(a.total_extrap_846m_secs.is_finite() && a.total_extrap_846m_secs >= 0.0); + assert!(a.stats.builder.duplicate_collapsed > 0); + assert!(a.stats.builder.duplicate_conflict_dropped > 0); + assert_eq!( + a.stats.builder.bars_in, + a.stats.builder.rows_out + + a.stats.builder.dropped_invalid_ohlc + + a.stats.builder.dropped_inconsistent_ohlc + + a.stats.builder.dropped_invalid_volume + + a.stats.builder.duplicate_collapsed + + a.stats.builder.duplicate_conflict_dropped + ); + assert_eq!(a.stats.rows_in, a.stats.builder.rows_out); + assert_eq!( + a.stats.rows_in, + a.stats.rows_out + + a.stats.dropped_unmapped + + a.stats.dropped_missing_currency + + a.stats.dropped_ts_out_of_range + + a.stats.listing_collision_collapsed + + a.stats.listing_collision_dropped + ); + assert!( + a.rows_out > a.rows * 90 / 100, + "expected >90% retention with unique ordinary pairs, got {}/{}", + a.rows_out, + a.rows + ); + assert!(a.stats.dropped_unmapped > 0); + assert!(a.stats.dropped_missing_currency > 0); + assert!(a.stats.dropped_ts_out_of_range > 0); + assert!(a.pre_2008_rows_out > 0); + assert_eq!(a.pre_2008_rows_out, b.pre_2008_rows_out); + assert!(a.stats.listing_collision_collapsed > 0); + assert!(a.stats.listing_collision_dropped > 0); + } + + #[test] + fn curate_bars_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_curate_bars_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.pre_2008_rows_out, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.listings_out, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stage_rows_per_sec, 0.0); + assert_eq!(report.stage_extrap_846m_secs, 0.0); + assert_eq!(report.parquet_rows_per_sec, 0.0); + assert_eq!(report.total_rows_per_sec, 0.0); + assert_eq!(report.total_extrap_846m_secs, 0.0); + } + + #[test] + fn curate_bars_benchmark_distinguishes_deliberate_duplicates_from_cursor_exhaustion() { + use crate::curate_bars::curate_bars_1d; + + // 1. Below cursor exhaustion: every builder duplicate and listing collision must match + // the explicitly injected counts with zero accidental cursor-wrap conflicts. + let fixture = + build_curate_bars_bench_fixture(5_000, CURATE_BARS_BENCH_KEY_COUNT, Some(12)) + .expect("5,000 rows across 2,000 keys fits within 12 dates/key"); + assert!(fixture.injected_dup_identical > 0); + assert!(fixture.injected_dup_conflict > 0); + assert!(fixture.injected_alias_identical > 0); + assert!(fixture.injected_alias_conflict > 0); + + let curated = curate_bars_1d( + fixture.bars, + &fixture.splits, + fixture.qm_volumes, + 0.01, + &fixture.provider_mapping, + "eod", + &fixture.listing_currencies, + ) + .unwrap(); + assert_eq!( + curated.stats.builder.duplicate_collapsed, + fixture.injected_dup_identical, + "builder identical duplicates must match explicit injections only" + ); + assert_eq!( + curated.stats.builder.duplicate_conflict_dropped, + fixture.injected_dup_conflict * 2, + "builder conflicting duplicates must match explicit injections only (2 rows per pair)" + ); + assert_eq!( + curated.stats.listing_collision_collapsed, + fixture.injected_alias_identical, + "listing identical collisions must match explicit injections only" + ); + assert_eq!( + curated.stats.listing_collision_dropped, + fixture.injected_alias_conflict * 2, + "listing conflicting collisions must match explicit injections only (2 rows per pair)" + ); + + // 2. Past cursor exhaustion: the fixture must reject the run with a clear error rather + // than silently wrapping and turning ordinary bars into accidental conflicts. + let err = match build_curate_bars_bench_fixture(40_000, CURATE_BARS_BENCH_KEY_COUNT, Some(12)) + { + Ok(_) => panic!("40,000 rows across 2,000 keys must exhaust a 12-date pool"), + Err(err) => err, + }; + assert!( + matches!( + err, + CurateBarsBenchError::FixtureDatePoolExhausted { + rows: 40_000, + key_count: CURATE_BARS_BENCH_KEY_COUNT, + pool: "2008..=2025", + capacity: 12, + .. + } + ), + "expected FixtureDatePoolExhausted, got {err:?}" + ); + let msg = err.to_string(); + assert!( + msg.contains("2008..=2025") + && msg.contains("12") + && msg.contains("40000") + && msg.contains("2000"), + "error message should explain the fixture limit, got: {msg}" + ); + } + + #[test] + fn curate_bars_benchmark_scales_key_space_for_large_batches() { + use crate::curate_bars::curate_bars_1d; + + assert_eq!(curate_bars_bench_key_count(0), 2_000); + assert_eq!(curate_bars_bench_key_count(2_000_000), 2_000); + assert_eq!(curate_bars_bench_key_count(2_000_001), 4_000); + assert_eq!(curate_bars_bench_key_count(20_000_000), 20_000); + + let scaled_keys = curate_bars_bench_key_count(20_000_000); + let fixture = build_curate_bars_bench_fixture(20_000, scaled_keys, None).unwrap(); + assert_eq!(fixture.key_count, 20_000); + + let curated = curate_bars_1d( + fixture.bars, + &fixture.splits, + fixture.qm_volumes, + 0.01, + &fixture.provider_mapping, + "eod", + &fixture.listing_currencies, + ) + .unwrap(); + assert_eq!( + curated.stats.builder.duplicate_collapsed, + fixture.injected_dup_identical + ); + assert_eq!( + curated.stats.builder.duplicate_conflict_dropped, + fixture.injected_dup_conflict * 2 + ); + assert_eq!( + curated.stats.listing_collision_collapsed, + fixture.injected_alias_identical + ); + assert_eq!( + curated.stats.listing_collision_dropped, + fixture.injected_alias_conflict * 2 + ); + assert!(curated.stats.rows_out > 20_000 * 90 / 100); + } + + #[test] + fn curate_shorts_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_curate_shorts_benchmark_tracked(25_000).unwrap(); + let (b, dir_b) = run_curate_shorts_benchmark_tracked(25_000).unwrap(); + + assert!( + !dir_a.exists(), + "temp dir {} should be removed", + dir_a.display() + ); + assert!( + !dir_b.exists(), + "temp dir {} should be removed", + dir_b.display() + ); + assert_eq!(a.rows, 25_000); + assert_eq!(a.stats.builder.rows_in, 25_000); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.read_back_rows, a.rows_out); + assert_eq!(a.listings_out, b.listings_out); + assert_eq!(a.files_written, 1); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.stage_rows_per_sec.is_finite() && a.stage_rows_per_sec >= 0.0); + assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0); + assert!(a.total_rows_per_sec.is_finite() && a.total_rows_per_sec >= 0.0); + assert!(a.stats.builder.dropped_invalid_shares_short > 0); + assert!(a.stats.builder.nulled_invalid_net_change > 0); + assert!(a.stats.builder.nulled_invalid_pct_float > 0); + assert!(a.stats.builder.duplicate_collapsed > 0); + assert!(a.stats.builder.duplicate_conflict_dropped > 0); + assert_eq!( + a.stats.builder.rows_in, + a.stats.builder.rows_out + + a.stats.builder.dropped_invalid_shares_short + + a.stats.builder.duplicate_collapsed + + a.stats.builder.duplicate_conflict_dropped + ); + assert_eq!(a.stats.rows_in, a.stats.builder.rows_out); + assert_eq!( + a.stats.rows_in, + a.stats.rows_out + + a.stats.dropped_unmapped + + a.stats.listing_collision_collapsed + + a.stats.listing_collision_dropped + ); + assert!(a.stats.dropped_unmapped > 0); + assert!(a.stats.listing_collision_collapsed > 0); + assert!(a.stats.listing_collision_dropped > 0); + assert!( + a.rows_out > a.rows * 90 / 100, + "expected >90% retention with unique ordinary pairs, got {}/{}", + a.rows_out, + a.rows + ); + } + + #[test] + fn curate_shorts_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_curate_shorts_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.listings_out, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stage_rows_per_sec, 0.0); + assert_eq!(report.parquet_rows_per_sec, 0.0); + assert_eq!(report.total_rows_per_sec, 0.0); + } + + #[test] + fn curate_shorts_benchmark_distinguishes_deliberate_duplicates_from_cursor_exhaustion() { + use crate::curate_shorts::curate_shorts; + + // 1. Below cursor exhaustion: every builder duplicate and cross-key listing collision + // must match the explicitly injected counts with zero accidental cursor wraps. + let fixture = + build_curate_shorts_bench_fixture(10_000, CURATE_SHORTS_BENCH_KEY_COUNT, Some(8)) + .expect("10,000 rows across 12,500 keys fits within 8 dates/key"); + assert!(fixture.injected_dup_identical > 0); + assert!(fixture.injected_dup_conflict > 0); + assert!(fixture.injected_alias_identical > 0); + assert!(fixture.injected_alias_conflict > 0); + + let curated = curate_shorts(fixture.reports, "ceo", &fixture.provider_mapping).unwrap(); + assert_eq!( + curated.stats.builder.duplicate_collapsed, + fixture.injected_dup_identical, + "builder identical duplicates must match explicit injections only" + ); + assert_eq!( + curated.stats.builder.duplicate_conflict_dropped, + fixture.injected_dup_conflict * 2, + "builder conflicting duplicates must match explicit injections only (2 rows per pair)" + ); + assert_eq!( + curated.stats.listing_collision_collapsed, + fixture.injected_alias_identical, + "listing identical collisions must match explicit injections only" + ); + assert_eq!( + curated.stats.listing_collision_dropped, + fixture.injected_alias_conflict * 2, + "listing conflicting collisions must match explicit injections only (2 rows per pair)" + ); + + // 2. Past cursor exhaustion: the fixture must reject the run with a clear error rather + // than silently wrapping. + let err = match build_curate_shorts_bench_fixture( + 120_000, + CURATE_SHORTS_BENCH_KEY_COUNT, + Some(4), + ) { + Ok(_) => panic!("120,000 rows across 12,500 keys must exhaust a 4-date pool"), + Err(err) => err, + }; + assert!( + matches!( + err, + CurateShortsBenchError::FixtureDatePoolExhausted { + rows: 120_000, + key_count: CURATE_SHORTS_BENCH_KEY_COUNT, + capacity: 4, + .. + } + ), + "expected FixtureDatePoolExhausted, got {err:?}" + ); + let msg = err.to_string(); + assert!( + msg.contains("4") && msg.contains("120000") && msg.contains("12500"), + "error message should explain the fixture limit, got: {msg}" + ); + } + + #[test] + fn curate_shorts_benchmark_scales_key_space_for_large_batches() { + use crate::curate_shorts::curate_shorts; + + assert_eq!(curate_shorts_bench_key_count(0), 12_500); + assert_eq!(curate_shorts_bench_key_count(1_000_000), 12_500); + assert_eq!(curate_shorts_bench_key_count(1_000_001), 25_000); + assert_eq!(curate_shorts_bench_key_count(2_000_000), 25_000); + assert_eq!(curate_shorts_bench_key_count(5_000_000), 62_500); + + let scaled_keys = curate_shorts_bench_key_count(2_000_000); + let fixture = build_curate_shorts_bench_fixture(25_000, scaled_keys, None).unwrap(); + assert_eq!(fixture.key_count, 25_000); + + let curated = curate_shorts(fixture.reports, "ceo", &fixture.provider_mapping).unwrap(); + assert_eq!( + curated.stats.builder.duplicate_collapsed, + fixture.injected_dup_identical + ); + assert_eq!( + curated.stats.builder.duplicate_conflict_dropped, + fixture.injected_dup_conflict * 2 + ); + assert_eq!( + curated.stats.listing_collision_collapsed, + fixture.injected_alias_identical + ); + assert_eq!( + curated.stats.listing_collision_dropped, + fixture.injected_alias_conflict * 2 + ); + assert!(curated.stats.rows_out > 25_000 * 90 / 100); + } + + #[test] + fn curate_events_benchmark_small_runs_are_deterministic_and_clean_up() { + for &n in &[20_000usize, 1_000usize] { + let (a, dir_a) = run_curate_events_benchmark_tracked(n).unwrap(); + let (b, dir_b) = run_curate_events_benchmark_tracked(n).unwrap(); + + assert!( + !dir_a.exists(), + "temp dir {} should be removed", + dir_a.display() + ); + assert!( + !dir_b.exists(), + "temp dir {} should be removed", + dir_b.display() + ); + assert_eq!(a.rows, n); + assert_eq!(a.filings_in + a.earnings_in, n); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.read_back_rows, a.rows_out); + assert_eq!(a.listings_out, b.listings_out); + assert_eq!(a.files_written, b.files_written); + assert!(a.files_written >= 2); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.stage_rows_per_sec.is_finite() && a.stage_rows_per_sec >= 0.0); + assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0); + assert!(a.total_rows_per_sec.is_finite() && a.total_rows_per_sec >= 0.0); + assert_eq!(a.stats.rows_in, a.stats.builder.rows_out); + assert_eq!( + a.stats.rows_in, + a.stats.rows_out + + a.stats.dropped_unmapped + + a.stats.listing_duplicate_collapsed + ); + assert_eq!(a.stats.rows_out, a.stats.filings_out + a.stats.earnings_out); + if n >= 20_000 { + assert!(a.stats.filings_out > 0); + assert!(a.stats.earnings_out > 0); + assert!(a.stats.dropped_unmapped > 0); + assert!(a.stats.listing_duplicate_collapsed > 0); + } + } + } + + #[test] + fn curate_events_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_curate_events_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.filings_in, 0); + assert_eq!(report.earnings_in, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.listings_out, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stage_rows_per_sec, 0.0); + assert_eq!(report.parquet_rows_per_sec, 0.0); + assert_eq!(report.total_rows_per_sec, 0.0); + } + + #[test] + fn curate_fx_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_curate_fx_benchmark_tracked(2_000).unwrap(); + let (b, dir_b) = run_curate_fx_benchmark_tracked(2_000).unwrap(); + + assert!( + !dir_a.exists(), + "temp dir {} should be removed", + dir_a.display() + ); + assert!( + !dir_b.exists(), + "temp dir {} should be removed", + dir_b.display() + ); + assert_eq!(a.rows, 2_000); + assert_eq!(a.eod_rows_in + a.te_rows_in, 2_000); + assert!(a.rows_out > 0); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.read_back_rows, a.rows_out); + assert_eq!(a.stats.rows_in, a.stats.builder.rows_out); + assert_eq!(a.stats.rows_out, a.stats.rows_in); + assert_eq!(a.files_written, 1); + assert_eq!(a.row_groups_written, b.row_groups_written); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.stage_rows_per_sec.is_finite() && a.stage_rows_per_sec >= 0.0); + assert!(a.stage_ns_per_row.is_finite() && a.stage_ns_per_row >= 0.0); + assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0); + assert!(a.total_rows_per_sec.is_finite() && a.total_rows_per_sec >= 0.0); + assert!(a.stats.builder.eod.dropped_invalid_ohlc > 0); + assert!(a.stats.builder.eod.dropped_inconsistent_ohlc > 0); + assert!(a.stats.builder.eod.duplicate_collapsed > 0); + assert!(a.stats.builder.eod.duplicate_conflict_dropped > 0); + assert!(a.stats.builder.te_superseded_by_eod > 0); + assert!(a.stats.builder.overlap_within_tolerance > 0); + assert!(a.stats.builder.overlap_mismatched > 0); + assert!(a.stats.builder.te_rows_out > 0); + } + + #[test] + fn curate_fx_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_curate_fx_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.eod_rows_in, 0); + assert_eq!(report.te_rows_in, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.row_groups_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stage_elapsed_ms, 0.0); + assert_eq!(report.stage_rows_per_sec, 0.0); + assert_eq!(report.stage_ns_per_row, 0.0); + assert_eq!(report.parquet_elapsed_ms, 0.0); + assert_eq!(report.parquet_rows_per_sec, 0.0); + assert_eq!(report.total_elapsed_ms, 0.0); + assert_eq!(report.total_rows_per_sec, 0.0); + assert_eq!(report.stats, crate::curate_fx::CurateFx1dStats::default()); + } } diff --git a/tools/curate-etl/src/bson_eod_prices.rs b/tools/curate-etl/src/bson_eod_prices.rs new file mode 100644 index 00000000..9547f250 --- /dev/null +++ b/tools/curate-etl/src/bson_eod_prices.rs @@ -0,0 +1,633 @@ +//! Zero-copy raw BSON decoder for MongoDB `eodPrices` documents (`M1.2o`). +//! +//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into +//! borrowed [`RawEodDailyBar`] views without allocating a `String` or `bson::Document` per row. +//! Callers convert borrowed views into [`crate::bars::EodDailyBar`] via a caller-supplied key +//! mapper (for example [`crate::provider_mapping::ProviderMappingTable::resolve`] or an interned +//! integer symbol ID), keeping the 846M-document path free of per-row `String` allocations. +//! +//! # Empirical Field Contract +//! +//! Field names and semantics are grounded in the repository's ingestion writer, pipeline reader, +//! and empirical data contract: +//! - `apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts:4-56` (`persistEodPrices` +//! writes `eodSearchCode`, `date`, `open`, `high`, `low`, `close`, `volume`, plus metadata fields +//! `symbol`, `exchange`, `providerExchange`, `source`, and optional `adjustedClose`) +//! - `apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts:105-157` (calls +//! `persistEodPrices` with `{ symbol, exchange, eodSearchCode }` and EODHD JSON OHLCV records) +//! - `apps/stock/data-pipeline/src/normalization/bar-spans.ts:12-18` (`eodPrices` keyed by +//! `eodSearchCode` and `date`) +//! - `design/DATA-CONTRACTS.md` §1 (line 13): `eodPrices` (~845.7M docs) stores **raw** +//! `open`/`high`/`low`/`close`, while `volume` is **retroactively split-adjusted** and therefore +//! maps directly to [`EodDailyBar::adj_volume`]. +//! +//! Accepted BSON field representations: +//! - `eodSearchCode`: BSON UTF-8 `String` (stored verbatim; empty or whitespace-only is rejected). +//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via +//! [`crate::split::ymd_to_epoch_days`]) or BSON `DateTime` (UTC epoch day via +//! `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check). +//! - `open`, `high`, `low`, `close`, `volume`: BSON `Double`, `Int32`, or `Int64` (every numeric +//! representation MongoDB can store for a JS number); must be finite and `>= 0.0` (`-0.0` is +//! normalized to `+0.0`). +//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `providerExchange`, `source`, +//! `adjustedClose`, `adjusted_close`, `created_at`, `updated_at`, nested objects/arrays, etc.) +//! are skipped without decoding their values. + +use std::error::Error; +use std::fmt; + +use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement}; +use bson::spec::ElementType; + +use crate::bars::EodDailyBar; +use crate::split::ymd_to_epoch_days; + +const MILLIS_PER_DAY: i64 = 86_400_000; +const MIN_BSON_DOC_LEN: i32 = 5; + +/// Borrowed zero-copy view of a single decoded `eodPrices` BSON document. +/// +/// Borrows `eod_search_code` directly from the underlying `&RawDocument` byte slice. +/// Per `design/DATA-CONTRACTS.md` §1, `open`/`high`/`low`/`close` are raw and `adj_volume` holds +/// the retroactively split-adjusted `eodPrices.volume`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RawEodDailyBar<'a> { + pub eod_search_code: &'a str, + /// Session date as days since `1970-01-01` (UTC Gregorian). + pub session_date: i32, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + /// Retroactively split-adjusted `eodPrices.volume`. + pub adj_volume: f64, +} + +impl<'a> RawEodDailyBar<'a> { + /// Converts this borrowed view into an [`EodDailyBar`] using a caller-supplied key mapper. + /// + /// `map_key` receives `(eod_search_code, session_date)` so callers can resolve an integer + /// `listing_id` or interned key without allocating a per-row `String`. + #[inline] + pub fn into_eod_daily_bar(self, map_key: F) -> EodDailyBar + where + F: FnOnce(&'a str, i32) -> K, + { + EodDailyBar { + key: map_key(self.eod_search_code, self.session_date), + session_date: self.session_date, + open: self.open, + high: self.high, + low: self.low, + close: self.close, + adj_volume: self.adj_volume, + } + } + + /// Fallible conversion into [`EodDailyBar`] using a caller-supplied key resolver + /// (for example `|code, date| mapping.resolve("eod", code, date)`). + #[inline] + pub fn try_into_eod_daily_bar(self, map_key: F) -> Option> + where + F: FnOnce(&'a str, i32) -> Option, + { + let key = map_key(self.eod_search_code, self.session_date)?; + Some(EodDailyBar { + key, + session_date: self.session_date, + open: self.open, + high: self.high, + low: self.low, + close: self.close, + adj_volume: self.adj_volume, + }) + } +} + +/// Typed errors returned while decoding raw `eodPrices` BSON documents or length-prefixed buffers. +/// +/// Every field-level error names the offending BSON field in both its structure and `Display` +/// output; no input path panics. +#[derive(Debug, Clone, PartialEq)] +pub enum BsonEodPriceError { + /// A required field was absent from the document. + MissingField { field: &'static str }, + /// A required string field was empty or contained only whitespace. + EmptyField { field: &'static str }, + /// A required field had an unexpected BSON element type. + WrongType { + field: &'static str, + actual: ElementType, + }, + /// `date` string was not a valid strict `YYYY-MM-DD` Gregorian date or BSON `DateTime` + /// overflowed `i32` epoch days. + MalformedDate { field: &'static str }, + /// A numeric OHLC or `volume` field was non-finite (`NaN`, `±inf`) or `< 0.0`. + InvalidNumber { field: &'static str, value: f64 }, + /// Buffer ended before a complete 4-byte length prefix or declared document body. + TruncatedDocument { + offset: usize, + remaining: usize, + declared_len: Option, + }, + /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single + /// document slice). + CorruptDocumentLength { offset: usize, declared_len: i32 }, + /// Underlying BSON framing or element bytes were malformed. + CorruptBson { offset: usize, detail: String }, +} + +impl fmt::Display for BsonEodPriceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MissingField { field } => { + write!(f, "eodPrices BSON missing required field '{field}'") + } + Self::EmptyField { field } => { + write!(f, "eodPrices BSON field '{field}' must not be empty or blank") + } + Self::WrongType { field, actual } => { + write!( + f, + "eodPrices BSON field '{field}' has unexpected BSON type {actual:?}" + ) + } + Self::MalformedDate { field } => { + write!( + f, + "eodPrices BSON field '{field}' is not a valid YYYY-MM-DD date or in-range DateTime" + ) + } + Self::InvalidNumber { field, value } => { + write!( + f, + "eodPrices BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0" + ) + } + Self::TruncatedDocument { + offset, + remaining, + declared_len, + } => match declared_len { + Some(len) => write!( + f, + "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" + ), + None => write!( + f, + "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" + ), + }, + Self::CorruptDocumentLength { + offset, + declared_len, + } => write!( + f, + "corrupt BSON document length {declared_len} at byte offset {offset}" + ), + Self::CorruptBson { offset, detail } => { + write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") + } + } + } +} + +impl Error for BsonEodPriceError {} + +/// Per-batch decode and rejection accounting for [`decode_eod_price_buffer`]. +/// +/// Conservation invariant: `decoded + rejected_total() == docs_in`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BsonEodDecodeStats { + pub docs_in: usize, + pub decoded: usize, + pub rejected_missing_field: usize, + pub rejected_empty_field: usize, + pub rejected_wrong_type: usize, + pub rejected_malformed_date: usize, + pub rejected_invalid_number: usize, + pub rejected_corrupt_document: usize, +} + +impl BsonEodDecodeStats { + /// Total number of rejected documents across all error categories. + #[inline] + pub fn rejected_total(&self) -> usize { + self.rejected_missing_field + + self.rejected_empty_field + + self.rejected_wrong_type + + self.rejected_malformed_date + + self.rejected_invalid_number + + self.rejected_corrupt_document + } + + /// Increments the rejection counter corresponding to `err`. + #[inline] + pub fn record_error(&mut self, err: &BsonEodPriceError) { + match err { + BsonEodPriceError::MissingField { .. } => self.rejected_missing_field += 1, + BsonEodPriceError::EmptyField { .. } => self.rejected_empty_field += 1, + BsonEodPriceError::WrongType { .. } => self.rejected_wrong_type += 1, + BsonEodPriceError::MalformedDate { .. } => self.rejected_malformed_date += 1, + BsonEodPriceError::InvalidNumber { .. } => self.rejected_invalid_number += 1, + BsonEodPriceError::TruncatedDocument { .. } + | BsonEodPriceError::CorruptDocumentLength { .. } + | BsonEodPriceError::CorruptBson { .. } => self.rejected_corrupt_document += 1, + } + } +} + +#[inline] +fn parse_ascii_digits_u32(bytes: &[u8]) -> Option { + let mut acc: u32 = 0; + for &b in bytes { + if !b.is_ascii_digit() { + return None; + } + acc = acc * 10 + u32::from(b - b'0'); + } + Some(acc) +} + +#[inline] +fn parse_ymd_strict(s: &str) -> Result { + let bytes = s.as_bytes(); + if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + } + let Some(year_u32) = parse_ascii_digits_u32(&bytes[0..4]) else { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + }; + let Some(month) = parse_ascii_digits_u32(&bytes[5..7]) else { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + }; + let Some(day) = parse_ascii_digits_u32(&bytes[8..10]) else { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + }; + ymd_to_epoch_days(year_u32 as i32, month, day) + .map_err(|_| BsonEodPriceError::MalformedDate { field: "date" }) +} + +#[inline] +fn decode_element_value<'a>( + field: &'static str, + elem: RawElement<'a>, + offset: usize, +) -> Result, BsonEodPriceError> { + elem.value().map_err(|err| BsonEodPriceError::CorruptBson { + offset, + detail: format!("field '{field}': {err}"), + }) +} + +#[inline] +fn decode_non_negative_number( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::Double(v) => { + if !v.is_finite() || v < 0.0 { + return Err(BsonEodPriceError::InvalidNumber { field, value: v }); + } + if v == 0.0 { + Ok(0.0) + } else { + Ok(v) + } + } + RawBsonRef::Int32(v) => { + if v < 0 { + return Err(BsonEodPriceError::InvalidNumber { + field, + value: f64::from(v), + }); + } + Ok(f64::from(v)) + } + RawBsonRef::Int64(v) => { + if v < 0 { + return Err(BsonEodPriceError::InvalidNumber { + field, + value: v as f64, + }); + } + Ok(v as f64) + } + other => Err(BsonEodPriceError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +fn decode_eod_price_doc_at<'a>( + doc: &'a RawDocument, + offset: usize, +) -> Result, BsonEodPriceError> { + let mut eod_search_code: Option<&'a str> = None; + let mut session_date: Option = None; + let mut open: Option = None; + let mut high: Option = None; + let mut low: Option = None; + let mut close: Option = None; + let mut adj_volume: Option = None; + + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonEodPriceError::CorruptBson { + offset, + detail: err.to_string(), + })?; + let key = elem.key(); + + if key == cstr!("eodSearchCode") { + match decode_element_value("eodSearchCode", elem, offset)? { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + return Err(BsonEodPriceError::EmptyField { + field: "eodSearchCode", + }); + } + eod_search_code = Some(s); + } + other => { + return Err(BsonEodPriceError::WrongType { + field: "eodSearchCode", + actual: other.element_type(), + }); + } + } + } else if key == cstr!("date") { + match decode_element_value("date", elem, offset)? { + RawBsonRef::String(s) => { + session_date = Some(parse_ymd_strict(s)?); + } + RawBsonRef::DateTime(dt) => { + let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); + let day_i32 = i32::try_from(days) + .map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })?; + session_date = Some(day_i32); + } + other => { + return Err(BsonEodPriceError::WrongType { + field: "date", + actual: other.element_type(), + }); + } + } + } else if key == cstr!("open") { + let val = decode_element_value("open", elem, offset)?; + open = Some(decode_non_negative_number("open", val)?); + } else if key == cstr!("high") { + let val = decode_element_value("high", elem, offset)?; + high = Some(decode_non_negative_number("high", val)?); + } else if key == cstr!("low") { + let val = decode_element_value("low", elem, offset)?; + low = Some(decode_non_negative_number("low", val)?); + } else if key == cstr!("close") { + let val = decode_element_value("close", elem, offset)?; + close = Some(decode_non_negative_number("close", val)?); + } else if key == cstr!("volume") { + let val = decode_element_value("volume", elem, offset)?; + adj_volume = Some(decode_non_negative_number("volume", val)?); + } + // Unknown extra fields are skipped without calling `elem.value()`. + } + + let Some(eod_search_code) = eod_search_code else { + return Err(BsonEodPriceError::MissingField { + field: "eodSearchCode", + }); + }; + let Some(session_date) = session_date else { + return Err(BsonEodPriceError::MissingField { field: "date" }); + }; + let Some(open) = open else { + return Err(BsonEodPriceError::MissingField { field: "open" }); + }; + let Some(high) = high else { + return Err(BsonEodPriceError::MissingField { field: "high" }); + }; + let Some(low) = low else { + return Err(BsonEodPriceError::MissingField { field: "low" }); + }; + let Some(close) = close else { + return Err(BsonEodPriceError::MissingField { field: "close" }); + }; + let Some(adj_volume) = adj_volume else { + return Err(BsonEodPriceError::MissingField { field: "volume" }); + }; + + Ok(RawEodDailyBar { + eod_search_code, + session_date, + open, + high, + low, + close, + adj_volume, + }) +} + +/// Decodes a single `&RawDocument` representing an `eodPrices` MongoDB document in one forward pass +/// without allocating a `String` or owned `bson::Document`. +#[inline] +pub fn decode_eod_price_doc<'a>( + doc: &'a RawDocument, +) -> Result, BsonEodPriceError> { + decode_eod_price_doc_at(doc, 0) +} + +/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed +/// [`RawEodDailyBar`]. +pub fn decode_eod_price_bytes<'a>( + bytes: &'a [u8], +) -> Result, BsonEodPriceError> { + if bytes.len() < 4 { + return Err(BsonEodPriceError::TruncatedDocument { + offset: 0, + remaining: bytes.len(), + declared_len: None, + }); + } + let declared_len = i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); + if declared_len < MIN_BSON_DOC_LEN { + return Err(BsonEodPriceError::CorruptDocumentLength { + offset: 0, + declared_len, + }); + } + let len_usize = declared_len as usize; + if len_usize > bytes.len() { + return Err(BsonEodPriceError::TruncatedDocument { + offset: 0, + remaining: bytes.len(), + declared_len: Some(declared_len), + }); + } + if len_usize < bytes.len() { + return Err(BsonEodPriceError::CorruptDocumentLength { + offset: 0, + declared_len, + }); + } + let doc = RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson { + offset: 0, + detail: err.to_string(), + })?; + decode_eod_price_doc_at(doc, 0) +} + +/// Zero-copy iterator over concatenated length-prefixed BSON documents (wire / `mongodump` layout). +#[derive(Debug, Clone)] +pub struct RawBsonDocIter<'a> { + buf: &'a [u8], + offset: usize, + terminated: bool, +} + +/// Item returned by [`RawBsonDocIter::next_with_offset`]. +pub type RawBsonDocWithOffset<'a> = Result<(usize, &'a RawDocument), (usize, BsonEodPriceError)>; + +impl<'a> RawBsonDocIter<'a> { + /// Creates a new iterator starting at byte offset `0`. + #[inline] + pub fn new(buf: &'a [u8]) -> Self { + Self { + buf, + offset: 0, + terminated: false, + } + } + + /// Returns the next framed `&RawDocument` along with its starting byte offset in the buffer. + /// + /// Unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) terminate the + /// iterator cleanly so iteration never loops infinitely or slices out of bounds. A validly + /// length-framed document with invalid BSON framing bytes returns `CorruptBson` and advances + /// past the framed document so subsequent documents can still be read. + pub fn next_with_offset(&mut self) -> Option> { + if self.terminated || self.offset >= self.buf.len() { + return None; + } + + let offset = self.offset; + let remaining = self.buf.len() - offset; + if remaining < 4 { + self.terminated = true; + return Some(Err(( + offset, + BsonEodPriceError::TruncatedDocument { + offset, + remaining, + declared_len: None, + }, + ))); + } + + let declared_len = i32::from_le_bytes([ + self.buf[offset], + self.buf[offset + 1], + self.buf[offset + 2], + self.buf[offset + 3], + ]); + if declared_len < MIN_BSON_DOC_LEN { + self.terminated = true; + return Some(Err(( + offset, + BsonEodPriceError::CorruptDocumentLength { + offset, + declared_len, + }, + ))); + } + + let doc_len = declared_len as usize; + if doc_len > remaining { + self.terminated = true; + return Some(Err(( + offset, + BsonEodPriceError::TruncatedDocument { + offset, + remaining, + declared_len: Some(declared_len), + }, + ))); + } + + let slice = &self.buf[offset..offset + doc_len]; + self.offset += doc_len; + + match RawDocument::from_bytes(slice) { + Ok(doc) => Some(Ok((offset, doc))), + Err(err) => Some(Err(( + offset, + BsonEodPriceError::CorruptBson { + offset, + detail: err.to_string(), + }, + ))), + } + } +} + +impl<'a> Iterator for RawBsonDocIter<'a> { + type Item = Result<&'a RawDocument, BsonEodPriceError>; + + #[inline] + fn next(&mut self) -> Option { + self.next_with_offset() + .map(|res| res.map(|(_, doc)| doc).map_err(|(_, err)| err)) + } +} + +/// Walks a contiguous byte buffer of concatenated length-prefixed BSON documents, yielding +/// zero-copy `&RawDocument` slices. +#[inline] +pub fn iter_raw_bson_docs<'a>(buf: &'a [u8]) -> RawBsonDocIter<'a> { + RawBsonDocIter::new(buf) +} + +/// Streams a concatenated length-prefixed BSON buffer through [`decode_eod_price_doc`], invoking +/// `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected document +/// without aborting the stream on per-document errors. +/// +/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`. +pub fn decode_eod_price_buffer<'a, F, E>( + buf: &'a [u8], + mut on_bar: F, + mut on_error: E, +) -> BsonEodDecodeStats +where + F: FnMut(RawEodDailyBar<'a>), + E: FnMut(usize, BsonEodPriceError), +{ + let mut stats = BsonEodDecodeStats::default(); + let mut iter = iter_raw_bson_docs(buf); + + while let Some(item) = iter.next_with_offset() { + stats.docs_in += 1; + match item { + Ok((doc_offset, doc)) => match decode_eod_price_doc_at(doc, doc_offset) { + Ok(bar) => { + stats.decoded += 1; + on_bar(bar); + } + Err(err) => { + stats.record_error(&err); + on_error(doc_offset, err); + } + }, + Err((doc_offset, err)) => { + stats.record_error(&err); + on_error(doc_offset, err); + } + } + } + + stats +} + +#[cfg(test)] +#[path = "bson_eod_prices_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bson_eod_prices_tests.rs b/tools/curate-etl/src/bson_eod_prices_tests.rs new file mode 100644 index 00000000..e5a614b5 --- /dev/null +++ b/tools/curate-etl/src/bson_eod_prices_tests.rs @@ -0,0 +1,785 @@ +use bson::oid::ObjectId; +use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; +use bson::spec::ElementType; +use bson::DateTime; + +use super::*; +use crate::bars::{build_bars_1d, QmRawVolume}; +use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable}; +use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).unwrap() +} + +fn make_valid_doc( + code: &str, + date: &str, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc +} + +fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { + let diff = (actual - expected).abs(); + let scale = expected.abs().max(1.0); + assert!( + diff <= rel_tol * scale, + "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" + ); +} + +#[test] +fn decodes_realistic_eod_price_doc_and_ignores_extra_fields() { + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("provider"), "eodhd"); + nested.append(cstr!("version"), 2_i32); + + let mut tags = RawArrayBuf::new(); + tags.push("us"); + tags.push("equity"); + + let mut doc = RawDocumentBuf::new(); + doc.append( + cstr!("_id"), + ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), + ); + doc.append(cstr!("symbol"), "NVDA"); + doc.append(cstr!("exchange"), "NASDAQ"); + doc.append(cstr!("providerExchange"), "US"); + doc.append(cstr!("source"), "eod"); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("date"), "2024-06-07"); + doc.append(cstr!("open"), 1197.70_f64); + doc.append(cstr!("high"), 1216.92_f64); + doc.append(cstr!("low"), 1180.22_f64); + doc.append(cstr!("close"), 1208.88_f64); + doc.append(cstr!("adjustedClose"), 120.888_f64); + doc.append(cstr!("adjusted_close"), 120.888_f64); + doc.append(cstr!("volume"), 412_390_000_i64); + doc.append(cstr!("created_at"), DateTime::from_millis(1_717_804_800_000)); + doc.append(cstr!("updated_at"), DateTime::from_millis(1_717_891_200_000)); + doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); + + let bar = decode_eod_price_doc(&doc).unwrap(); + assert_eq!(bar.eod_search_code, "NVDA.US"); + assert_eq!(bar.session_date, day(2024, 6, 7)); + assert_eq!(bar.open.to_bits(), 1197.70_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 1216.92_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 1180.22_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 1208.88_f64.to_bits()); + assert_eq!(bar.adj_volume.to_bits(), 412_390_000.0_f64.to_bits()); + + // Verify decode_eod_price_bytes matches decode_eod_price_doc bit-for-bit. + let from_bytes = decode_eod_price_bytes(doc.as_bytes()).unwrap(); + assert_eq!(from_bytes, bar); +} + +#[test] +fn decodes_double_int32_int64_numerics_and_zero_volume_normalization() { + // Mixed Int32, Int64, and Double across OHLC and volume. + let mut mixed = RawDocumentBuf::new(); + mixed.append(cstr!("eodSearchCode"), "SHOP.TO"); + mixed.append(cstr!("date"), "2024-02-29"); + mixed.append(cstr!("open"), 100_i32); + mixed.append(cstr!("high"), 105_i64); + mixed.append(cstr!("low"), 99.5_f64); + mixed.append(cstr!("close"), 104_i32); + mixed.append(cstr!("volume"), 5_000_000_000_i64); + + let bar = decode_eod_price_doc(&mixed).unwrap(); + assert_eq!(bar.eod_search_code, "SHOP.TO"); + assert_eq!(bar.session_date, day(2024, 2, 29)); + assert_eq!(bar.open.to_bits(), 100.0_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 105.0_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 99.5_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 104.0_f64.to_bits()); + assert_eq!(bar.adj_volume.to_bits(), 5_000_000_000.0_f64.to_bits()); + + // Zero volume in Double (+0.0, -0.0), Int32 (0), Int64 (0) all normalize to +0.0. + let zero_cases: [RawBsonRef<'_>; 4] = [ + RawBsonRef::Double(0.0), + RawBsonRef::Double(-0.0), + RawBsonRef::Int32(0), + RawBsonRef::Int64(0), + ]; + for zero_val in zero_cases { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "ZERO.US"); + doc.append(cstr!("date"), "2024-06-07"); + doc.append(cstr!("open"), -0.0_f64); + doc.append(cstr!("high"), 10_i32); + doc.append(cstr!("low"), 0_i64); + doc.append(cstr!("close"), 5.5_f64); + doc.append(cstr!("volume"), zero_val); + + let decoded = decode_eod_price_doc(&doc).unwrap(); + assert_eq!(decoded.open.to_bits(), 0.0_f64.to_bits()); + assert_eq!(decoded.low.to_bits(), 0.0_f64.to_bits()); + assert_eq!(decoded.adj_volume.to_bits(), 0.0_f64.to_bits()); + } +} + +#[test] +fn decodes_ymd_string_and_bson_datetime_to_identical_epoch_days() { + let cases = [ + ("1969-12-31", day(1969, 12, 31)), + ("1970-01-01", day(1970, 1, 1)), + ("2024-02-29", day(2024, 2, 29)), + ("2024-06-07", day(2024, 6, 7)), + ]; + + for (date_str, expected_day) in cases { + let str_doc = make_valid_doc("TEST.US", date_str, 10.0, 11.0, 9.5, 10.5, 1000.0); + let decoded_str = decode_eod_price_doc(&str_doc).unwrap(); + assert_eq!(decoded_str.session_date, expected_day); + + // Midnight UTC DateTime. + let midnight_ms = i64::from(expected_day) * MILLIS_PER_DAY; + let mut dt_mid = RawDocumentBuf::new(); + dt_mid.append(cstr!("eodSearchCode"), "TEST.US"); + dt_mid.append(cstr!("date"), DateTime::from_millis(midnight_ms)); + dt_mid.append(cstr!("open"), 10.0_f64); + dt_mid.append(cstr!("high"), 11.0_f64); + dt_mid.append(cstr!("low"), 9.5_f64); + dt_mid.append(cstr!("close"), 10.5_f64); + dt_mid.append(cstr!("volume"), 1000.0_f64); + assert_eq!( + decode_eod_price_doc(&dt_mid).unwrap().session_date, + expected_day + ); + + // Mid-day UTC DateTime (12:34:56.789 UTC) — critically tests pre-1970 Euclidean division + // (`1969-12-31T12:34:56.789Z` must be -1, NOT 0). + let midday_ms = midnight_ms + (12 * 3_600 + 34 * 60 + 56) * 1_000 + 789; + let mut dt_midday = RawDocumentBuf::new(); + dt_midday.append(cstr!("eodSearchCode"), "TEST.US"); + dt_midday.append(cstr!("date"), DateTime::from_millis(midday_ms)); + dt_midday.append(cstr!("open"), 10.0_f64); + dt_midday.append(cstr!("high"), 11.0_f64); + dt_midday.append(cstr!("low"), 9.5_f64); + dt_midday.append(cstr!("close"), 10.5_f64); + dt_midday.append(cstr!("volume"), 1000.0_f64); + assert_eq!( + decode_eod_price_doc(&dt_midday).unwrap().session_date, + expected_day + ); + } +} + +#[test] +fn missing_each_required_field_returns_typed_error_naming_field() { + let required = [ + "eodSearchCode", + "date", + "open", + "high", + "low", + "close", + "volume", + ]; + + for omit in required { + let mut doc = RawDocumentBuf::new(); + if omit != "eodSearchCode" { + doc.append(cstr!("eodSearchCode"), "AAPL.US"); + } + if omit != "date" { + doc.append(cstr!("date"), "2024-06-07"); + } + if omit != "open" { + doc.append(cstr!("open"), 190.0_f64); + } + if omit != "high" { + doc.append(cstr!("high"), 195.0_f64); + } + if omit != "low" { + doc.append(cstr!("low"), 189.0_f64); + } + if omit != "close" { + doc.append(cstr!("close"), 194.5_f64); + } + if omit != "volume" { + doc.append(cstr!("volume"), 50_000_000_i64); + } + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!(err, BsonEodPriceError::MissingField { field: omit }); + assert!( + err.to_string().contains(omit), + "error message should name '{omit}', got: {err}" + ); + } +} + +#[test] +fn empty_or_whitespace_eod_search_code_returns_empty_field_error() { + for blank in ["", " ", "\t\n"] { + let doc = make_valid_doc(blank, "2024-06-07", 10.0, 11.0, 9.0, 10.5, 100.0); + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::EmptyField { + field: "eodSearchCode" + } + ); + assert!(err.to_string().contains("eodSearchCode")); + } +} + +#[test] +fn wrong_bson_types_return_typed_error_naming_field() { + let oid = ObjectId::from_bytes([0xAA; 12]); + let mut arr = RawArrayBuf::new(); + arr.push(1_i32); + + // Wrong types for eodSearchCode. + for (bad_val, expected_ty) in [ + (RawBsonRef::Int32(42), ElementType::Int32), + (RawBsonRef::Boolean(true), ElementType::Boolean), + (RawBsonRef::Null, ElementType::Null), + (RawBsonRef::ObjectId(oid), ElementType::ObjectId), + (RawBsonRef::Array(arr.as_ref()), ElementType::Array), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), bad_val); + doc.append(cstr!("date"), "2024-06-07"); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 100_i32); + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::WrongType { + field: "eodSearchCode", + actual: expected_ty, + } + ); + assert!(err.to_string().contains("eodSearchCode")); + } + + // Wrong types for date. + for (bad_val, expected_ty) in [ + (RawBsonRef::Int64(20240607), ElementType::Int64), + (RawBsonRef::Boolean(false), ElementType::Boolean), + (RawBsonRef::Null, ElementType::Null), + (RawBsonRef::ObjectId(oid), ElementType::ObjectId), + (RawBsonRef::Array(arr.as_ref()), ElementType::Array), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "AAPL.US"); + doc.append(cstr!("date"), bad_val); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 100_i32); + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::WrongType { + field: "date", + actual: expected_ty, + } + ); + assert!(err.to_string().contains("date")); + } + + // Wrong types for each numeric field (open, high, low, close, volume). + let numeric_fields = ["open", "high", "low", "close", "volume"]; + for target in numeric_fields { + for (bad_val, expected_ty) in [ + (RawBsonRef::String("10.5"), ElementType::String), + (RawBsonRef::Boolean(true), ElementType::Boolean), + (RawBsonRef::Null, ElementType::Null), + (RawBsonRef::ObjectId(oid), ElementType::ObjectId), + (RawBsonRef::Array(arr.as_ref()), ElementType::Array), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "AAPL.US"); + doc.append(cstr!("date"), "2024-06-07"); + for &field in &numeric_fields { + let key = match field { + "open" => cstr!("open"), + "high" => cstr!("high"), + "low" => cstr!("low"), + "close" => cstr!("close"), + _ => cstr!("volume"), + }; + if field == target { + doc.append(key, bad_val); + } else { + doc.append(key, 10.0_f64); + } + } + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::WrongType { + field: target, + actual: expected_ty, + } + ); + assert!(err.to_string().contains(target)); + } + } +} + +#[test] +fn malformed_dates_and_out_of_range_datetimes_return_malformed_date_error() { + for bad_date in [ + "2023-02-29", + "1900-02-29", + "2024-6-7", + "2024-06-07T00:00:00Z", + "2024-13-01", + "2024-00-10", + "2024-04-31", + "", + " 2024-06-07", + "2024/06/07", + "abcd-ef-gh", + ] { + let doc = make_valid_doc("BAD.US", bad_date, 10.0, 11.0, 9.0, 10.5, 100.0); + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::MalformedDate { field: "date" }, + "expected MalformedDate for '{bad_date}'" + ); + assert!(err.to_string().contains("date")); + } + + for extreme_ms in [i64::MAX, i64::MIN] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "BAD.US"); + doc.append(cstr!("date"), DateTime::from_millis(extreme_ms)); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 100_i32); + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!(err, BsonEodPriceError::MalformedDate { field: "date" }); + assert!(err.to_string().contains("date")); + } +} + +#[test] +fn non_finite_and_negative_prices_or_volume_return_invalid_number_error() { + let fields = ["open", "high", "low", "close", "volume"]; + let bad_values: [RawBsonRef<'_>; 6] = [ + RawBsonRef::Double(f64::NAN), + RawBsonRef::Double(f64::INFINITY), + RawBsonRef::Double(f64::NEG_INFINITY), + RawBsonRef::Double(-0.01), + RawBsonRef::Int32(-1), + RawBsonRef::Int64(-100), + ]; + + for target in fields { + for bad_val in bad_values { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NUM.US"); + doc.append(cstr!("date"), "2024-06-07"); + for &field in &fields { + let key = match field { + "open" => cstr!("open"), + "high" => cstr!("high"), + "low" => cstr!("low"), + "close" => cstr!("close"), + _ => cstr!("volume"), + }; + if field == target { + doc.append(key, bad_val); + } else { + doc.append(key, 10.0_f64); + } + } + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert!( + matches!(err, BsonEodPriceError::InvalidNumber { field, .. } if field == target), + "expected InvalidNumber for {target} with {bad_val:?}, got {err:?}" + ); + assert!(err.to_string().contains(target)); + } + } +} + +#[test] +fn truncated_and_corrupt_length_prefixed_buffers_return_typed_errors_without_panicking() { + // 1. Truncated header (< 4 bytes). + let err = decode_eod_price_bytes(&[0x05, 0x00, 0x00]).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::TruncatedDocument { + offset: 0, + remaining: 3, + declared_len: None, + } + ); + + // 2. Declared length < 5 (0, 4, negative). + for bad_len in [0_i32, 4_i32, -12_i32] { + let mut buf = Vec::from(bad_len.to_le_bytes()); + buf.push(0); + let err = decode_eod_price_bytes(&buf).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::CorruptDocumentLength { + offset: 0, + declared_len: bad_len, + } + ); + } + + // 3. Truncated body (declared_len > remaining). + let valid = make_valid_doc("NVDA.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 100.0); + let full_bytes = valid.as_bytes(); + let truncated = &full_bytes[..full_bytes.len() - 5]; + let err = decode_eod_price_bytes(truncated).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::TruncatedDocument { + offset: 0, + remaining: truncated.len(), + declared_len: Some(full_bytes.len() as i32), + } + ); + + // 4. Corrupt trailing terminator (last byte != 0x00). + let mut bad_term = full_bytes.to_vec(); + *bad_term.last_mut().unwrap() = 0xFF; + let err = decode_eod_price_bytes(&bad_term).unwrap_err(); + assert!( + matches!(err, BsonEodPriceError::CorruptBson { offset: 0, .. }), + "expected CorruptBson for bad terminator, got {err:?}" + ); + + // 5. Corrupt element framing inside a length-valid document (bad element type byte 0x7F). + let mut bad_elem: Vec = Vec::new(); + let declared: i32 = 10; + bad_elem.extend_from_slice(&declared.to_le_bytes()); + bad_elem.extend_from_slice(&[0x7F, b'a', 0x00, 0x01, 0x02, 0x00]); + let err = decode_eod_price_bytes(&bad_elem).unwrap_err(); + assert!( + matches!(err, BsonEodPriceError::CorruptBson { offset: 0, .. }), + "expected CorruptBson for corrupt element framing, got {err:?}" + ); + + // 6. Iterator terminates cleanly on framing errors without looping. + let mut iter = iter_raw_bson_docs(truncated); + assert!(matches!( + iter.next(), + Some(Err(BsonEodPriceError::TruncatedDocument { .. })) + )); + assert!(iter.next().is_none()); +} + +#[test] +fn multi_document_buffer_skips_bad_docs_and_reconciles_per_reason_stats() { + let good_1 = make_valid_doc("AAPL.US", "2024-06-05", 194.0, 196.9, 193.5, 195.87, 54_000_000.0); + + // Bad 1: missing field (`volume`). + let mut bad_missing = RawDocumentBuf::new(); + bad_missing.append(cstr!("eodSearchCode"), "MISS.US"); + bad_missing.append(cstr!("date"), "2024-06-05"); + bad_missing.append(cstr!("open"), 10.0_f64); + bad_missing.append(cstr!("high"), 11.0_f64); + bad_missing.append(cstr!("low"), 9.0_f64); + bad_missing.append(cstr!("close"), 10.5_f64); + + // Bad 2: empty `eodSearchCode`. + let bad_empty = make_valid_doc(" ", "2024-06-05", 10.0, 11.0, 9.0, 10.5, 100.0); + + // Bad 3: wrong BSON type (`open` is string). + let mut bad_type = RawDocumentBuf::new(); + bad_type.append(cstr!("eodSearchCode"), "TYPE.US"); + bad_type.append(cstr!("date"), "2024-06-05"); + bad_type.append(cstr!("open"), "not-a-number"); + bad_type.append(cstr!("high"), 11.0_f64); + bad_type.append(cstr!("low"), 9.0_f64); + bad_type.append(cstr!("close"), 10.5_f64); + bad_type.append(cstr!("volume"), 100_i32); + + // Bad 4: malformed date. + let bad_date = make_valid_doc("DATE.US", "2023-02-29", 10.0, 11.0, 9.0, 10.5, 100.0); + + // Bad 5: negative price. + let bad_price = make_valid_doc("NEG.US", "2024-06-05", -1.0, 11.0, 9.0, 10.5, 100.0); + + // Bad 6: NaN volume. + let bad_vol = make_valid_doc("NAN.US", "2024-06-05", 10.0, 11.0, 9.0, 10.5, f64::NAN); + + // Bad 7: length-valid document with corrupt trailing null byte (stream still continues past it). + let mut bad_corrupt = make_valid_doc("COR.US", "2024-06-05", 10.0, 11.0, 9.0, 10.5, 100.0) + .as_bytes() + .to_vec(); + *bad_corrupt.last_mut().unwrap() = 0xEE; + + let good_2 = make_valid_doc("MSFT.US", "2024-06-06", 423.0, 425.3, 420.5, 424.52, 14_800_000.0); + + let mut buffer = Vec::new(); + buffer.extend_from_slice(good_1.as_bytes()); + buffer.extend_from_slice(bad_missing.as_bytes()); + buffer.extend_from_slice(bad_empty.as_bytes()); + buffer.extend_from_slice(bad_type.as_bytes()); + buffer.extend_from_slice(bad_date.as_bytes()); + buffer.extend_from_slice(bad_price.as_bytes()); + buffer.extend_from_slice(bad_vol.as_bytes()); + buffer.extend_from_slice(&bad_corrupt); + buffer.extend_from_slice(good_2.as_bytes()); + + let mut decoded_codes: Vec = Vec::new(); + let mut errors: Vec<(usize, BsonEodPriceError)> = Vec::new(); + + let stats = decode_eod_price_buffer( + &buffer, + |bar| decoded_codes.push(bar.eod_search_code.to_string()), + |offset, err| errors.push((offset, err)), + ); + + assert_eq!(decoded_codes, vec!["AAPL.US", "MSFT.US"]); + assert_eq!(stats.docs_in, 9); + assert_eq!(stats.decoded, 2); + assert_eq!(stats.rejected_missing_field, 1); + assert_eq!(stats.rejected_empty_field, 1); + assert_eq!(stats.rejected_wrong_type, 1); + assert_eq!(stats.rejected_malformed_date, 1); + assert_eq!(stats.rejected_invalid_number, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.rejected_total(), 7); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + assert_eq!(errors.len(), 7); +} + +#[test] +fn decoded_nvda_split_buffer_feeds_build_bars_1d_with_non_string_key_mapper() { + let pre_split = day(2024, 6, 7); + let ex_date = day(2024, 6, 10); + let post_split = day(2024, 6, 11); + const NVDA_LISTING_ID: i32 = 42; + + // Encode NVDA 10:1 split fixture with mixed Int64 / Int32 / Double volume representations. + let mut doc_pre = RawDocumentBuf::new(); + doc_pre.append(cstr!("eodSearchCode"), "NVDA.US"); + doc_pre.append(cstr!("date"), "2024-06-07"); + doc_pre.append(cstr!("open"), 1197.70_f64); + doc_pre.append(cstr!("high"), 1216.92_f64); + doc_pre.append(cstr!("low"), 1180.22_f64); + doc_pre.append(cstr!("close"), 1208.88_f64); + doc_pre.append(cstr!("volume"), 412_390_000_i64); + + let mut doc_ex = RawDocumentBuf::new(); + doc_ex.append(cstr!("eodSearchCode"), "NVDA.US"); + doc_ex.append(cstr!("date"), "2024-06-10"); + doc_ex.append(cstr!("open"), 120.37_f64); + doc_ex.append(cstr!("high"), 123.10_f64); + doc_ex.append(cstr!("low"), 117.01_f64); + doc_ex.append(cstr!("close"), 121.79_f64); + doc_ex.append(cstr!("volume"), 314_162_700_i32); + + let mut doc_post = RawDocumentBuf::new(); + doc_post.append(cstr!("eodSearchCode"), "NVDA.US"); + doc_post.append( + cstr!("date"), + DateTime::from_millis(i64::from(post_split) * MILLIS_PER_DAY), + ); + doc_post.append(cstr!("open"), 121.77_f64); + doc_post.append(cstr!("high"), 122.87_f64); + doc_post.append(cstr!("low"), 118.74_f64); + doc_post.append(cstr!("close"), 120.91_f64); + doc_post.append(cstr!("volume"), 222_551_200.0_f64); + + // Include an unmapped symbol to prove try_into_eod_daily_bar filters unmapped keys cleanly. + let doc_unmapped = make_valid_doc("UNKNOWN.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 1_000.0); + + let mut buf = Vec::new(); + buf.extend_from_slice(doc_pre.as_bytes()); + buf.extend_from_slice(doc_ex.as_bytes()); + buf.extend_from_slice(doc_post.as_bytes()); + buf.extend_from_slice(doc_unmapped.as_bytes()); + + let mapping = ProviderMappingTable::from_rows([ProviderMappingRow { + source: "eod".to_string(), + source_id: "NVDA.US".to_string(), + valid_from: day(1999, 1, 22), + valid_to: None, + listing_id: NVDA_LISTING_ID, + }]) + .unwrap(); + + let mut bars: Vec> = Vec::new(); + let stats = decode_eod_price_buffer( + &buf, + |raw| { + if let Some(bar) = + raw.try_into_eod_daily_bar(|code, dt| mapping.resolve("eod", code, dt)) + { + bars.push(bar); + } + }, + |offset, err| panic!("unexpected decode error at offset {offset}: {err}"), + ); + + assert_eq!(stats.docs_in, 4); + assert_eq!(stats.decoded, 4); + assert_eq!(stats.rejected_total(), 0); + assert_eq!(bars.len(), 3); + + let splits: SplitTable = SplitTable::from_events([( + NVDA_LISTING_ID, + SplitEvent { + ex_date, + ratio: 10.0, + }, + )]) + .unwrap(); + + let built = + build_bars_1d(bars, &splits, std::iter::empty::>(), 0.01).unwrap(); + assert_eq!(built.rows.len(), 3); + + // Pre-split 2024-06-07: raw OHLC preserved bit-for-bit, volume un-adjusted by / 10. + let r0 = &built.rows[0]; + assert_eq!(r0.key, NVDA_LISTING_ID); + assert_eq!(r0.session_date, pre_split); + assert_eq!(r0.open.to_bits(), 1197.70_f64.to_bits()); + assert_eq!(r0.high.to_bits(), 1216.92_f64.to_bits()); + assert_eq!(r0.low.to_bits(), 1180.22_f64.to_bits()); + assert_eq!(r0.close.to_bits(), 1208.88_f64.to_bits()); + assert_rel_eq(r0.volume, 41_239_000.0, 1e-12); + + // Ex-date 2024-06-10: factor = 1.0, volume unchanged. + let r1 = &built.rows[1]; + assert_eq!(r1.session_date, ex_date); + assert_eq!(r1.close.to_bits(), 121.79_f64.to_bits()); + assert_eq!(r1.volume.to_bits(), 314_162_700.0_f64.to_bits()); + + // Post-split 2024-06-11: factor = 1.0, volume unchanged. + let r2 = &built.rows[2]; + assert_eq!(r2.session_date, post_split); + assert_eq!(r2.close.to_bits(), 120.91_f64.to_bits()); + assert_eq!(r2.volume.to_bits(), 222_551_200.0_f64.to_bits()); +} + +#[test] +fn invalid_utf8_in_known_field_names_field_and_stream_continues() { + let good_1 = make_valid_doc("AAPL.US", "2024-06-05", 194.0, 196.9, 193.5, 195.87, 54_000_000.0); + let good_2 = make_valid_doc("MSFT.US", "2024-06-06", 423.0, 425.3, 420.5, 424.52, 14_800_000.0); + + // Build a length-valid document and corrupt a byte inside the `eodSearchCode` string value + // to invalid UTF-8 (`0xFF`) while leaving all framing and null terminators intact. + let mut bad_utf8 = make_valid_doc("BADX.US", "2024-06-05", 10.0, 11.0, 9.0, 10.5, 100.0) + .as_bytes() + .to_vec(); + let needle = b"BADX.US"; + let pos = bad_utf8 + .windows(needle.len()) + .position(|w| w == needle) + .expect("fixture should contain sentinel eodSearchCode bytes"); + bad_utf8[pos] = 0xFF; + + // Single-document decode reports CorruptBson naming the field. + let err = decode_eod_price_bytes(&bad_utf8).unwrap_err(); + match &err { + BsonEodPriceError::CorruptBson { offset, detail } => { + assert_eq!(*offset, 0); + assert!( + detail.contains("eodSearchCode"), + "CorruptBson detail should name 'eodSearchCode', got: {detail}" + ); + } + other => panic!("expected CorruptBson for invalid UTF-8, got {other:?}"), + } + assert!( + err.to_string().contains("eodSearchCode"), + "Display output should name 'eodSearchCode', got: {err}" + ); + + // Stream continues past the invalid-UTF-8 document and decodes the following document. + let mut buffer = Vec::new(); + buffer.extend_from_slice(good_1.as_bytes()); + let bad_offset = buffer.len(); + buffer.extend_from_slice(&bad_utf8); + buffer.extend_from_slice(good_2.as_bytes()); + + let mut decoded_codes: Vec = Vec::new(); + let mut errors: Vec<(usize, BsonEodPriceError)> = Vec::new(); + let stats = decode_eod_price_buffer( + &buffer, + |bar| decoded_codes.push(bar.eod_search_code.to_string()), + |offset, err| errors.push((offset, err)), + ); + + assert_eq!(decoded_codes, vec!["AAPL.US", "MSFT.US"]); + assert_eq!(stats.docs_in, 3); + assert_eq!(stats.decoded, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.rejected_total(), 1); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].0, bad_offset); + assert!( + errors[0].1.to_string().contains("eodSearchCode"), + "stream error should name 'eodSearchCode', got: {}", + errors[0].1 + ); +} + +#[test] +fn corrupt_length_prefix_in_middle_stops_stream_cleanly() { + let good_1 = make_valid_doc("AAPL.US", "2024-06-05", 194.0, 196.9, 193.5, 195.87, 54_000_000.0); + let good_2 = make_valid_doc("MSFT.US", "2024-06-06", 423.0, 425.3, 420.5, 424.52, 14_800_000.0); + + let mut buffer = Vec::new(); + buffer.extend_from_slice(good_1.as_bytes()); + let bad_offset = buffer.len(); + buffer.extend_from_slice(&2_i32.to_le_bytes()); + buffer.extend_from_slice(good_2.as_bytes()); + + let mut decoded_codes: Vec = Vec::new(); + let mut errors: Vec<(usize, BsonEodPriceError)> = Vec::new(); + let stats = decode_eod_price_buffer( + &buffer, + |bar| decoded_codes.push(bar.eod_search_code.to_string()), + |offset, err| errors.push((offset, err)), + ); + + assert_eq!(decoded_codes, vec!["AAPL.US"]); + assert_eq!(stats.docs_in, 2); + assert_eq!(stats.decoded, 1); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.rejected_total(), 1); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + assert_eq!( + errors, + vec![( + bad_offset, + BsonEodPriceError::CorruptDocumentLength { + offset: bad_offset, + declared_len: 2, + } + )] + ); +} diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index b03e400c..95fc40b6 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -5,9 +5,13 @@ use crate::bench::{ DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, - DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, - DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, - DEFAULT_SHORTS_BENCH_ROWS, + DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, + DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_EVENTS_BENCH_ROWS, + DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, + DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, + DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, + DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, + DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, }; /// Parsed CLI command to execute. @@ -24,6 +28,16 @@ pub enum CliAction { BenchEvents(usize), BenchProviderMapping(usize), BenchParquetBars(usize), + BenchParquetShorts(usize), + BenchParquetEvents(usize), + BenchParquetFx(usize), + BenchParquetAdj(usize), + BenchParquetCorporateActions(usize), + BenchBsonEodPrices(usize), + BenchCurateBars(usize), + BenchCurateShorts(usize), + BenchCurateEvents(usize), + BenchCurateFx(usize), } /// Formats full help text including binary name and version. @@ -42,7 +56,17 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\ {name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\ {name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})\n\ - {name} bench-parquet-bars [rows] Run fixed-seed bars_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_BARS_BENCH_ROWS})" + {name} bench-parquet-bars [rows] Run fixed-seed bars_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_BARS_BENCH_ROWS})\n\ + {name} bench-parquet-shorts [rows] Run fixed-seed shorts Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_SHORTS_BENCH_ROWS})\n\ + {name} bench-parquet-events [rows] Run fixed-seed events Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_EVENTS_BENCH_ROWS})\n\ + {name} bench-parquet-fx [rows] Run fixed-seed fx_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_FX_BENCH_ROWS})\n\ + {name} bench-parquet-adj [rows] Run fixed-seed adj_factors Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_ADJ_BENCH_ROWS})\n\ + {name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})\n\ + {name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\ + {name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\ + {name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\ + {name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})\n\ + {name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})" ) } @@ -60,7 +84,17 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-shorts [rows]\n\ {name} bench-events [rows]\n\ {name} bench-provider-mapping [lookups]\n\ - {name} bench-parquet-bars [rows]" + {name} bench-parquet-bars [rows]\n\ + {name} bench-parquet-shorts [rows]\n\ + {name} bench-parquet-events [rows]\n\ + {name} bench-parquet-fx [rows]\n\ + {name} bench-parquet-adj [rows]\n\ + {name} bench-parquet-corporate-actions [rows]\n\ + {name} bench-bson-eod-prices [rows]\n\ + {name} bench-curate-bars [rows]\n\ + {name} bench-curate-shorts [rows]\n\ + {name} bench-curate-events [rows]\n\ + {name} bench-curate-fx [rows]" ) } @@ -157,6 +191,116 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-parquet-bars", _, ..] => { Err("too many arguments for bench-parquet-bars".to_string()) } + ["bench-parquet-shorts"] => Ok(CliAction::BenchParquetShorts( + DEFAULT_PARQUET_SHORTS_BENCH_ROWS, + )), + ["bench-parquet-shorts", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchParquetShorts(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-parquet-shorts", _, ..] => { + Err("too many arguments for bench-parquet-shorts".to_string()) + } + ["bench-parquet-events"] => Ok(CliAction::BenchParquetEvents( + DEFAULT_PARQUET_EVENTS_BENCH_ROWS, + )), + ["bench-parquet-events", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchParquetEvents(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-parquet-events", _, ..] => { + Err("too many arguments for bench-parquet-events".to_string()) + } + ["bench-parquet-fx"] => Ok(CliAction::BenchParquetFx(DEFAULT_PARQUET_FX_BENCH_ROWS)), + ["bench-parquet-fx", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchParquetFx(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-parquet-fx", _, ..] => { + Err("too many arguments for bench-parquet-fx".to_string()) + } + ["bench-parquet-adj"] => Ok(CliAction::BenchParquetAdj(DEFAULT_PARQUET_ADJ_BENCH_ROWS)), + ["bench-parquet-adj", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchParquetAdj(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-parquet-adj", _, ..] => { + Err("too many arguments for bench-parquet-adj".to_string()) + } + ["bench-parquet-corporate-actions"] => Ok(CliAction::BenchParquetCorporateActions( + DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, + )), + ["bench-parquet-corporate-actions", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchParquetCorporateActions(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-parquet-corporate-actions", _, ..] => { + Err("too many arguments for bench-parquet-corporate-actions".to_string()) + } + ["bench-bson-eod-prices"] => Ok(CliAction::BenchBsonEodPrices( + DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, + )), + ["bench-bson-eod-prices", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchBsonEodPrices(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-bson-eod-prices", _, ..] => { + Err("too many arguments for bench-bson-eod-prices".to_string()) + } + ["bench-curate-bars"] => Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)), + ["bench-curate-bars", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchCurateBars(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-curate-bars", _, ..] => { + Err("too many arguments for bench-curate-bars".to_string()) + } + ["bench-curate-shorts"] => { + Ok(CliAction::BenchCurateShorts(DEFAULT_CURATE_SHORTS_BENCH_ROWS)) + } + ["bench-curate-shorts", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchCurateShorts(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-curate-shorts", _, ..] => { + Err("too many arguments for bench-curate-shorts".to_string()) + } + ["bench-curate-events"] => { + Ok(CliAction::BenchCurateEvents(DEFAULT_CURATE_EVENTS_BENCH_ROWS)) + } + ["bench-curate-events", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchCurateEvents(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-curate-events", _, ..] => { + Err("too many arguments for bench-curate-events".to_string()) + } + ["bench-curate-fx"] => Ok(CliAction::BenchCurateFx(DEFAULT_CURATE_FX_BENCH_ROWS)), + ["bench-curate-fx", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchCurateFx(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-curate-fx", _, ..] => Err("too many arguments for bench-curate-fx".to_string()), [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -340,6 +484,110 @@ mod tests { assert!(parse_args(&to_args(&["bench-parquet-bars", "10", "20"])).is_err()); } + #[test] + fn parses_and_validates_bench_parquet_shorts_args() { + assert_eq!( + parse_args(&to_args(&["bench-parquet-shorts"])), + Ok(CliAction::BenchParquetShorts( + DEFAULT_PARQUET_SHORTS_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-parquet-shorts", "50000"])), + Ok(CliAction::BenchParquetShorts(50_000)) + ); + assert!(parse_args(&to_args(&["bench-parquet-shorts", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-shorts", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-shorts", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-shorts", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_parquet_events_args() { + assert_eq!( + parse_args(&to_args(&["bench-parquet-events"])), + Ok(CliAction::BenchParquetEvents( + DEFAULT_PARQUET_EVENTS_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-parquet-events", "20000"])), + Ok(CliAction::BenchParquetEvents(20_000)) + ); + assert!(parse_args(&to_args(&["bench-parquet-events", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-events", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-events", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-events", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_parquet_fx_args() { + assert_eq!( + parse_args(&to_args(&["bench-parquet-fx"])), + Ok(CliAction::BenchParquetFx(DEFAULT_PARQUET_FX_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-parquet-fx", "20000"])), + Ok(CliAction::BenchParquetFx(20_000)) + ); + assert!(parse_args(&to_args(&["bench-parquet-fx", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-fx", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-fx", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-fx", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_parquet_adj_args() { + assert_eq!( + parse_args(&to_args(&["bench-parquet-adj"])), + Ok(CliAction::BenchParquetAdj(DEFAULT_PARQUET_ADJ_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-parquet-adj", "25000"])), + Ok(CliAction::BenchParquetAdj(25_000)) + ); + assert!(parse_args(&to_args(&["bench-parquet-adj", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-adj", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-adj", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-adj", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_parquet_corporate_actions_args() { + assert_eq!( + parse_args(&to_args(&["bench-parquet-corporate-actions"])), + Ok(CliAction::BenchParquetCorporateActions( + DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-parquet-corporate-actions", "25000"])), + Ok(CliAction::BenchParquetCorporateActions(25_000)) + ); + assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_bson_eod_prices_args() { + assert_eq!( + parse_args(&to_args(&["bench-bson-eod-prices"])), + Ok(CliAction::BenchBsonEodPrices( + DEFAULT_BSON_EOD_PRICES_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-bson-eod-prices", "250000"])), + Ok(CliAction::BenchBsonEodPrices(250_000)) + ); + assert!(parse_args(&to_args(&["bench-bson-eod-prices", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-eod-prices", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-eod-prices", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-eod-prices", "10", "20"])).is_err()); + } + #[test] fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); @@ -352,6 +600,16 @@ mod tests { assert!(full.contains("bench-events")); assert!(full.contains("bench-provider-mapping")); assert!(full.contains("bench-parquet-bars")); + assert!(full.contains("bench-parquet-shorts")); + assert!(full.contains("bench-parquet-events")); + assert!(full.contains("bench-parquet-fx")); + assert!(full.contains("bench-parquet-adj")); + assert!(full.contains("bench-parquet-corporate-actions")); + assert!(full.contains("bench-bson-eod-prices")); + assert!(full.contains("bench-curate-bars")); + assert!(full.contains("bench-curate-shorts")); + assert!(full.contains("bench-curate-events")); + assert!(full.contains("bench-curate-fx")); let short = format_usage_stderr("curate-etl"); assert!(short.contains("bench-split")); @@ -363,5 +621,83 @@ mod tests { assert!(short.contains("bench-events")); assert!(short.contains("bench-provider-mapping")); assert!(short.contains("bench-parquet-bars")); + assert!(short.contains("bench-parquet-shorts")); + assert!(short.contains("bench-parquet-events")); + assert!(short.contains("bench-parquet-fx")); + assert!(short.contains("bench-parquet-adj")); + assert!(short.contains("bench-parquet-corporate-actions")); + assert!(short.contains("bench-bson-eod-prices")); + assert!(short.contains("bench-curate-bars")); + assert!(short.contains("bench-curate-shorts")); + assert!(short.contains("bench-curate-events")); + assert!(short.contains("bench-curate-fx")); + } + + #[test] + fn parses_and_validates_bench_curate_bars_args() { + assert_eq!( + parse_args(&to_args(&["bench-curate-bars"])), + Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-curate-bars", "100000"])), + Ok(CliAction::BenchCurateBars(100_000)) + ); + assert!(parse_args(&to_args(&["bench-curate-bars", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-bars", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-bars", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-bars", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_curate_shorts_args() { + assert_eq!( + parse_args(&to_args(&["bench-curate-shorts"])), + Ok(CliAction::BenchCurateShorts( + DEFAULT_CURATE_SHORTS_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-curate-shorts", "100000"])), + Ok(CliAction::BenchCurateShorts(100_000)) + ); + assert!(parse_args(&to_args(&["bench-curate-shorts", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-shorts", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-shorts", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-shorts", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_curate_events_args() { + assert_eq!( + parse_args(&to_args(&["bench-curate-events"])), + Ok(CliAction::BenchCurateEvents( + DEFAULT_CURATE_EVENTS_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-curate-events", "1000"])), + Ok(CliAction::BenchCurateEvents(1_000)) + ); + assert!(parse_args(&to_args(&["bench-curate-events", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-events", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-events", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-events", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_curate_fx_args() { + assert_eq!( + parse_args(&to_args(&["bench-curate-fx"])), + Ok(CliAction::BenchCurateFx(DEFAULT_CURATE_FX_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-curate-fx", "100000"])), + Ok(CliAction::BenchCurateFx(100_000)) + ); + assert!(parse_args(&to_args(&["bench-curate-fx", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-fx", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-fx", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-fx", "10", "20"])).is_err()); } } diff --git a/tools/curate-etl/src/curate_bars.rs b/tools/curate-etl/src/curate_bars.rs new file mode 100644 index 00000000..515b3f8d --- /dev/null +++ b/tools/curate-etl/src/curate_bars.rs @@ -0,0 +1,399 @@ +//! Pure, in-memory `bars_1d` curation stage joining [`crate::bars::build_bars_1d`], +//! [`crate::provider_mapping::ProviderMappingTable`], listing currency metadata, and +//! [`crate::parquet_bars::write_bars_1d_dataset`] into contract [`Bars1dParquetRow`]s. +//! +//! # Contract & Point-in-Time Rules +//! - Calls [`build_bars_1d`] unchanged to validate OHLCV, un-adjust `eodPrices` share volume via +//! `SplitTable`, and cross-check against optional `qmPrices.sharevolume` observations. +//! - Resolves each output row's `(mapping_source, source_id, session_date)` to a permanent +//! `listing_id: i32` via [`ProviderMappingTable::cursor_for`] / [`ProviderMappingCursor::resolve`] +//! (one cursor per contiguous `key` run, since `build_bars_1d` emits rows sorted by +//! `(key, session_date)`). +//! - Stamps `ts_micros = known_at_micros = 16:00:00 America/New_York` (`16:00 ET`) converted to +//! UTC microseconds via [`crate::session_close::et_session_close_utc_micros`] +//! (`design/PLATFORM-PLAN.md`: "`known_at` = session close"). +//! - **Early-close half days** (e.g., `13:00 ET` on Christmas Eve or the day after US +//! Thanksgiving) still use `16:00 ET`, which is strictly later than the real close and +//! therefore never introduces look-ahead bias. +//! - **North American DST eras (`America/New_York` == `America/Toronto` over `1976..=2030`):** +//! `et_session_close_utc_micros` applies the three identical US/Canada DST eras (`1976..=1986` +//! last Sun Apr → last Sun Oct; `1987..=2006` first Sun Apr → last Sun Oct; `2007..=2030` +//! second Sun Mar → first Sun Nov; EDT `UTC-4` = `20:00 UTC`, EST `UTC-5` = `21:00 UTC`). +//! - **Calendar window:** covers `1976-01-01..=2030-12-31` +//! ([`crate::session_close::SESSION_CLOSE_MIN_SUPPORTED_DATE`]..=[`crate::session_close::SESSION_CLOSE_MAX_SUPPORTED_DATE`]). +//! The lower bound is `1976-01-01` because US emergency DST in `1974–1975` diverged from +//! Toronto; pre-1976 or post-2030 dates are dropped into +//! [`CurateBars1dStats::dropped_ts_out_of_range`] rather than panicking or guessing. +//! - Sets `vwap = None` and `source = Cow::Borrowed(BARS_1D_SOURCE_EOD)` (`"eod_unadj"`). +//! - Re-sorts mapped rows in place by `(listing_id, session_date)` and compacts cross-`source_id` +//! collisions on the same `(listing_id, session_date)`: bitwise-identical OHLCV collapses to one +//! row (`listing_collision_collapsed`), while any OHLCV conflict drops the entire group +//! (`listing_collision_dropped`), mirroring `build_bars_1d`'s duplicate policy. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::error::Error; +use std::fmt; +use std::hash::Hash; +use std::path::Path; + +use crate::bars::{ + build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume, VolumeMismatchSample, +}; +use crate::parquet_bars::{ + write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, Bars1dWriteStats, ParquetBarsError, +}; +use crate::provider_mapping::ProviderMappingTable; +use crate::session_close::et_session_close_utc_micros; +use crate::split::SplitTable; + +/// Canonical contract `source` provenance label for un-adjusted `eodPrices` daily bars. +pub const BARS_1D_SOURCE_EOD: &str = "eod_unadj"; + +/// Regular North American equity session close hour in Eastern Time (`16:00 ET`). +pub const BARS_1D_SESSION_CLOSE_HOUR_ET: u8 = 16; + +/// Regular North American equity session close minute in Eastern Time (`16:00 ET`). +pub const BARS_1D_SESSION_CLOSE_MINUTE_ET: u8 = 0; + +/// Regular North American equity session close second in Eastern Time (`16:00 ET`). +pub const BARS_1D_SESSION_CLOSE_SECOND_ET: u8 = 0; + +/// Accounting summary produced alongside [`CurateBars1dOutput::rows`]. +/// +/// Conservation invariants: +/// - `rows_in == builder.rows_out` +/// - `rows_in == rows_out + dropped_unmapped + dropped_missing_currency + dropped_ts_out_of_range + listing_collision_collapsed + listing_collision_dropped` +/// - `builder` independently satisfies all [`Bars1dStats`] conservation invariants. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct CurateBars1dStats { + pub builder: Bars1dStats, + pub rows_in: usize, + pub rows_out: usize, + pub listings_out: usize, + pub dropped_unmapped: usize, + pub dropped_missing_currency: usize, + pub dropped_ts_out_of_range: usize, + pub listing_collision_collapsed: usize, + pub listing_collision_dropped: usize, +} + +/// Output of [`curate_bars_1d`]: contract Parquet rows sorted and unique by +/// `(listing_id, session_date)`, full stage + builder stats, and untouched mismatch samples. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateBars1dOutput { + pub rows: Vec, + pub stats: CurateBars1dStats, + pub mismatch_samples: Vec>, +} + +/// Typed caller errors returned by [`curate_bars_1d`]. +/// +/// Bad single rows (unmapped dates, missing currencies, out-of-range timestamps, and +/// cross-`source_id` collisions) are dropped and counted in [`CurateBars1dStats`] rather than +/// aborting the stage. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum CurateBarsError { + /// Error propagated from [`build_bars_1d`] (e.g., invalid `rel_tolerance`). + Bars(BarsError), + /// Caller-supplied `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, +} + +impl fmt::Display for CurateBarsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::Bars(err) => write!(f, "{err}"), + Self::EmptyMappingSource => { + write!(f, "mapping_source must not be empty or blank") + } + } + } +} + +impl Error for CurateBarsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Bars(err) => Some(err), + Self::EmptyMappingSource => None, + } + } +} + +impl From for CurateBarsError { + fn from(err: BarsError) -> Self { + Self::Bars(err) + } +} + +/// Combined stats and mismatch samples returned by [`curate_and_write_bars_1d`]. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateBars1dWriteReport { + pub curate_stats: CurateBars1dStats, + pub write_stats: Bars1dWriteStats, + pub mismatch_samples: Vec>, +} + +/// Typed error returned by [`curate_and_write_bars_1d`]. +#[derive(Debug)] +pub enum CurateBarsWriteError { + Curate(CurateBarsError), + Parquet(ParquetBarsError), +} + +impl fmt::Display for CurateBarsWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => write!(f, "bars_1d curation failed: {err}"), + Self::Parquet(err) => write!(f, "bars_1d Parquet write failed: {err}"), + } + } +} + +impl Error for CurateBarsWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CurateBarsWriteError { + fn from(err: CurateBarsError) -> Self { + Self::Curate(err) + } +} + +impl From for CurateBarsWriteError { + fn from(err: ParquetBarsError) -> Self { + Self::Parquet(err) + } +} + +#[inline] +fn parquet_row_ohlcv_bit_eq(a: &Bars1dParquetRow, b: &Bars1dParquetRow) -> bool { + a.open.to_bits() == b.open.to_bits() + && a.high.to_bits() == b.high.to_bits() + && a.low.to_bits() == b.low.to_bits() + && a.close.to_bits() == b.close.to_bits() + && a.volume.to_bits() == b.volume.to_bits() +} + +/// Pure `bars_1d` curation stage: un-adjusts and cross-checks source-keyed `eodPrices` bars via +/// [`build_bars_1d`], resolves `(mapping_source, source_id, session_date) -> listing_id` through +/// `provider_mapping`, attaches listing currency and `16:00 ET` session-close UTC timestamps, and +/// emits contract [`Bars1dParquetRow`]s sorted and unique by `(listing_id, session_date)`. +/// +/// Drop priority per built row: +/// 1. No mapping range covers `(mapping_source, source_id, session_date)` → `dropped_unmapped`. +/// 2. Resolved `listing_id` is absent from `listing_currencies` or maps to a blank string → +/// `dropped_missing_currency`. +/// 3. `et_session_close_utc_micros(session_date)` fails (date outside `1976-01-01..=2030-12-31`) → +/// `dropped_ts_out_of_range`. +/// +/// After re-sorting in place by `(listing_id, session_date)`, cross-`source_id` collisions on the +/// same `(listing_id, session_date)` collapse to one row when OHLCV is bitwise identical +/// (`listing_collision_collapsed += g - 1`) and drop the entire group when any OHLCV field differs +/// (`listing_collision_dropped += g`). +pub fn curate_bars_1d( + bars: B, + splits: &SplitTable, + qm_volumes: Q, + rel_tolerance: f64, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, + listing_currencies: &HashMap>, +) -> Result, CurateBarsError> +where + K: Ord + Eq + Hash + Clone + AsRef, + B: IntoIterator>, + Q: IntoIterator>, +{ + if !rel_tolerance.is_finite() || rel_tolerance < 0.0 { + return Err(BarsError::InvalidTolerance { rel_tolerance }.into()); + } + if mapping_source.trim().is_empty() { + return Err(CurateBarsError::EmptyMappingSource); + } + + let built = build_bars_1d(bars, splits, qm_volumes, rel_tolerance)?; + + let mut stats = CurateBars1dStats { + builder: built.stats, + rows_in: built.rows.len(), + ..CurateBars1dStats::default() + }; + + let mut rows: Vec = Vec::with_capacity(built.rows.len()); + let total_built = built.rows.len(); + let mut idx = 0usize; + + while idx < total_built { + let run_start = idx; + let run_key = &built.rows[run_start].key; + idx += 1; + while idx < total_built && built.rows[idx].key == *run_key { + idx += 1; + } + let run_end = idx; + + let mut cursor = provider_mapping.cursor_for(mapping_source, run_key.as_ref()); + if cursor.ranges().is_empty() { + stats.dropped_unmapped += run_end - run_start; + continue; + } + + let mut cached_currency: Option<(i32, Option<&Cow<'static, str>>)> = None; + + for bar in &built.rows[run_start..run_end] { + let Some(listing_id) = cursor.resolve(bar.session_date) else { + stats.dropped_unmapped += 1; + continue; + }; + + let currency = match cached_currency { + Some((cached_id, cached)) if cached_id == listing_id => cached, + _ => { + let looked_up = listing_currencies + .get(&listing_id) + .filter(|c| !c.trim().is_empty()); + cached_currency = Some((listing_id, looked_up)); + looked_up + } + }; + let Some(currency) = currency else { + stats.dropped_missing_currency += 1; + continue; + }; + + let Ok(ts_micros) = et_session_close_utc_micros(bar.session_date) else { + stats.dropped_ts_out_of_range += 1; + continue; + }; + + rows.push(Bars1dParquetRow { + listing_id, + ts_micros, + session_date: bar.session_date, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + vwap: None, + currency: currency.clone(), + source: Cow::Borrowed(BARS_1D_SOURCE_EOD), + known_at_micros: ts_micros, + }); + } + } + + // Free builder rows before sorting/compacting mapped contract rows to cut peak RAM. + drop(built.rows); + + rows.sort_unstable_by(|a, b| { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.session_date.cmp(&b.session_date)) + }); + + let mut write_idx = 0usize; + let mut read_idx = 0usize; + let total_mapped = rows.len(); + let mut last_listing_id: Option = None; + + while read_idx < total_mapped { + let listing_id = rows[read_idx].listing_id; + let session_date = rows[read_idx].session_date; + let mut group_end = read_idx + 1; + while group_end < total_mapped + && rows[group_end].listing_id == listing_id + && rows[group_end].session_date == session_date + { + group_end += 1; + } + let group_len = group_end - read_idx; + + if group_len == 1 { + if write_idx != read_idx { + rows.swap(write_idx, read_idx); + } + if last_listing_id != Some(listing_id) { + stats.listings_out += 1; + last_listing_id = Some(listing_id); + } + write_idx += 1; + } else { + let first = &rows[read_idx]; + let all_identical = rows[read_idx + 1..group_end] + .iter() + .all(|other| parquet_row_ohlcv_bit_eq(first, other)); + + if all_identical { + stats.listing_collision_collapsed += group_len - 1; + if write_idx != read_idx { + rows.swap(write_idx, read_idx); + } + if last_listing_id != Some(listing_id) { + stats.listings_out += 1; + last_listing_id = Some(listing_id); + } + write_idx += 1; + } else { + stats.listing_collision_dropped += group_len; + } + } + + read_idx = group_end; + } + rows.truncate(write_idx); + stats.rows_out = rows.len(); + + Ok(CurateBars1dOutput { + rows, + stats, + mismatch_samples: built.mismatch_samples, + }) +} + +/// Thin end-to-end wrapper running [`curate_bars_1d`] and publishing the resulting contract rows +/// via [`write_bars_1d_dataset`] to `/bars_1d/year=YYYY/part.parquet`. +#[allow(clippy::too_many_arguments)] +pub fn curate_and_write_bars_1d( + out_dir: P, + bars: B, + splits: &SplitTable, + qm_volumes: Q, + rel_tolerance: f64, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, + listing_currencies: &HashMap>, + options: Bars1dWriteOptions, +) -> Result, CurateBarsWriteError> +where + P: AsRef, + K: Ord + Eq + Hash + Clone + AsRef, + B: IntoIterator>, + Q: IntoIterator>, +{ + let curated = curate_bars_1d( + bars, + splits, + qm_volumes, + rel_tolerance, + provider_mapping, + mapping_source, + listing_currencies, + )?; + let write_stats = write_bars_1d_dataset(out_dir, &curated.rows, options)?; + Ok(CurateBars1dWriteReport { + curate_stats: curated.stats, + write_stats, + mismatch_samples: curated.mismatch_samples, + }) +} + +#[cfg(test)] +#[path = "curate_bars_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_bars_tests.rs b/tools/curate-etl/src/curate_bars_tests.rs new file mode 100644 index 00000000..2b23f5cd --- /dev/null +++ b/tools/curate-etl/src/curate_bars_tests.rs @@ -0,0 +1,927 @@ +use std::borrow::Cow; +use std::collections::HashMap; +use std::error::Error; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::bars::build_bars_1d; +use crate::provider_mapping::ProviderMappingRow; +use crate::session_close::{SESSION_CLOSE_MAX_SUPPORTED_DATE, SESSION_CLOSE_MIN_SUPPORTED_DATE}; +use crate::shorts::epoch_days_to_ymd; +use crate::split::{ymd_to_epoch_days, SplitEvent}; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!("curate-etl-curate-bars-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = day(y, m, d); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000_000 +} + +fn bar( + key: &str, + session_date: i32, + open: f64, + high: f64, + low: f64, + close: f64, + adj_volume: f64, +) -> EodDailyBar { + EodDailyBar { + key: key.to_string(), + session_date, + open, + high, + low, + close, + adj_volume, + } +} + +fn qm(key: &str, session_date: i32, share_volume: f64) -> QmRawVolume { + QmRawVolume { + key: key.to_string(), + session_date, + share_volume, + } +} + +fn map_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +fn currencies(entries: &[(i32, &'static str)]) -> HashMap> { + entries + .iter() + .map(|&(id, curr)| (id, Cow::Borrowed(curr))) + .collect() +} + +fn assert_conservation_and_order(out: &CurateBars1dOutput) { + let s = &out.stats; + assert_eq!(s.rows_in, s.builder.rows_out, "rows_in != builder.rows_out: {s:?}"); + assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); + assert_eq!( + s.rows_in, + s.rows_out + + s.dropped_unmapped + + s.dropped_missing_currency + + s.dropped_ts_out_of_range + + s.listing_collision_collapsed + + s.listing_collision_dropped, + "curate accounting conservation mismatch: {s:?}" + ); + assert_eq!( + s.builder.bars_in, + s.builder.rows_out + + s.builder.dropped_invalid_ohlc + + s.builder.dropped_inconsistent_ohlc + + s.builder.dropped_invalid_volume + + s.builder.duplicate_collapsed + + s.builder.duplicate_conflict_dropped, + "builder accounting conservation mismatch: {s:?}" + ); + + let mut distinct_listings = 0usize; + let mut prev_listing: Option = None; + for row in &out.rows { + assert_eq!(row.vwap, None); + assert_eq!(row.source.as_ref(), BARS_1D_SOURCE_EOD); + assert_eq!(row.ts_micros, row.known_at_micros); + if prev_listing != Some(row.listing_id) { + distinct_listings += 1; + prev_listing = Some(row.listing_id); + } + } + assert_eq!(s.listings_out, distinct_listings); + + for pair in out.rows.windows(2) { + assert!( + (pair[0].listing_id, pair[0].session_date) + < (pair[1].listing_id, pair[1].session_date), + "output rows must be strictly sorted and unique by (listing_id, session_date): {:?} vs {:?}", + (pair[0].listing_id, pair[0].session_date), + (pair[1].listing_id, pair[1].session_date), + ); + } +} + +fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let listing_id = read_i32_col(rg_reader.get_column_reader(0).unwrap(), num_rows); + let ts_micros = read_i64_col(rg_reader.get_column_reader(1).unwrap(), num_rows); + let session_date = read_i32_col(rg_reader.get_column_reader(2).unwrap(), num_rows); + let open = read_req_f64_col(rg_reader.get_column_reader(3).unwrap(), num_rows); + let high = read_req_f64_col(rg_reader.get_column_reader(4).unwrap(), num_rows); + let low = read_req_f64_col(rg_reader.get_column_reader(5).unwrap(), num_rows); + let close = read_req_f64_col(rg_reader.get_column_reader(6).unwrap(), num_rows); + let volume = read_req_f64_col(rg_reader.get_column_reader(7).unwrap(), num_rows); + let vwap = read_opt_f64_col(rg_reader.get_column_reader(8).unwrap(), num_rows); + let currency = read_str_col(rg_reader.get_column_reader(9).unwrap(), num_rows); + let source = read_str_col(rg_reader.get_column_reader(10).unwrap(), num_rows); + let known_at_micros = read_i64_col(rg_reader.get_column_reader(11).unwrap(), num_rows); + + for i in 0..num_rows { + out.push(Bars1dParquetRow { + listing_id: listing_id[i], + ts_micros: ts_micros[i], + session_date: session_date[i], + open: open[i], + high: high[i], + low: low[i], + close: close[i], + volume: volume[i], + vwap: vwap[i], + currency: Cow::Owned(currency[i].clone()), + source: Cow::Owned(source[i].clone()), + known_at_micros: known_at_micros[i], + }); + } + } + out +} + +fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int32ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int32ColumnReader"), + } + values +} + +fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int64ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int64ColumnReader"), + } + values +} + +fn read_req_f64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + values +} + +fn read_opt_f64_col(reader: ColumnReader, expected: usize) -> Vec> { + let mut raw_values = Vec::with_capacity(expected); + let mut def_levels = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, levels) = r + .read_records(expected, Some(&mut def_levels), None, &mut raw_values) + .unwrap(); + assert_eq!(records, expected); + assert_eq!(levels, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + let mut out = Vec::with_capacity(expected); + let mut val_idx = 0usize; + for lvl in def_levels { + if lvl == 1 { + out.push(Some(raw_values[val_idx])); + val_idx += 1; + } else { + out.push(None); + } + } + assert_eq!(val_idx, raw_values.len()); + out +} + +fn read_str_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected ByteArrayColumnReader"), + } + values + .into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8")) + .collect() +} + +fn assert_row_bitwise_eq(actual: &Bars1dParquetRow, expected: &Bars1dParquetRow) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.ts_micros, expected.ts_micros); + assert_eq!(actual.session_date, expected.session_date); + assert_eq!(actual.open.to_bits(), expected.open.to_bits()); + assert_eq!(actual.high.to_bits(), expected.high.to_bits()); + assert_eq!(actual.low.to_bits(), expected.low.to_bits()); + assert_eq!(actual.close.to_bits(), expected.close.to_bits()); + assert_eq!(actual.volume.to_bits(), expected.volume.to_bits()); + assert_eq!( + actual.vwap.map(f64::to_bits), + expected.vwap.map(f64::to_bits) + ); + assert_eq!(actual.currency, expected.currency); + assert_eq!(actual.source, expected.source); + assert_eq!(actual.known_at_micros, expected.known_at_micros); +} + +#[test] +fn happy_path_two_sources_nvda_split_unadjusts_volume_and_resorts_by_listing_id() { + // Deliberately assign RY.TO (lexicographically after NVDA.US) a smaller listing_id (10 vs 20) + // to verify post-mapping re-sorting by (listing_id, session_date). + let d_pre = day(2024, 6, 7); + let d_ex = day(2024, 6, 10); + let d_post = day(2024, 6, 11); + + let splits = SplitTable::from_events([( + "NVDA.US".to_string(), + SplitEvent { + ex_date: d_ex, + ratio: 10.0, + }, + )]) + .unwrap(); + + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "NVDA.US", day(2010, 1, 1), None, 20), + map_row("eod", "RY.TO", day(2010, 1, 1), None, 10), + ]) + .unwrap(); + let curr = currencies(&[(10, "CAD"), (20, "USD")]); + + let input_bars = vec![ + bar("NVDA.US", d_pre, 1197.7, 1216.92, 1180.22, 1208.88, 412_390_000.0), + bar("NVDA.US", d_ex, 120.37, 123.1, 117.01, 121.79, 314_162_700.0), + bar("NVDA.US", d_post, 121.77, 122.87, 118.74, 120.91, 222_551_200.0), + bar("RY.TO", d_pre, 146.10, 147.25, 145.80, 146.95, 2_500_000.0), + bar("RY.TO", d_ex, 147.00, 148.10, 146.50, 147.85, 2_100_000.0), + ]; + let qm_partners = vec![ + qm("NVDA.US", d_pre, 41_239_000.0), + qm("NVDA.US", d_ex, 314_162_700.0), + qm("RY.TO", d_pre, 2_500_000.0), + ]; + + let out = curate_bars_1d( + input_bars.clone(), + &splits, + qm_partners, + 0.01, + &mapping, + "eod", + &curr, + ) + .unwrap(); + + assert_conservation_and_order(&out); + assert_eq!(out.rows.len(), 5); + assert_eq!(out.stats.listings_out, 2); + assert_eq!(out.stats.builder.volume_checked, 3); + assert_eq!(out.stats.builder.volume_within_tolerance, 3); + assert!(out.mismatch_samples.is_empty()); + + // Listing 10 (RY.TO) comes first despite "RY.TO" > "NVDA.US". + assert_eq!(out.rows[0].listing_id, 10); + assert_eq!(out.rows[0].session_date, d_pre); + assert_eq!(out.rows[0].open.to_bits(), 146.10_f64.to_bits()); + assert_eq!(out.rows[0].high.to_bits(), 147.25_f64.to_bits()); + assert_eq!(out.rows[0].low.to_bits(), 145.80_f64.to_bits()); + assert_eq!(out.rows[0].close.to_bits(), 146.95_f64.to_bits()); + assert_eq!(out.rows[0].volume.to_bits(), 2_500_000.0_f64.to_bits()); + assert_eq!(out.rows[0].currency.as_ref(), "CAD"); + + assert_eq!(out.rows[1].listing_id, 10); + assert_eq!(out.rows[1].session_date, d_ex); + assert_eq!(out.rows[1].currency.as_ref(), "CAD"); + + // Listing 20 (NVDA.US): pre-split volume divided by 10, ex-date & post-split unchanged, + // raw OHLC bit-identical. + let nvda_pre = &out.rows[2]; + assert_eq!(nvda_pre.listing_id, 20); + assert_eq!(nvda_pre.session_date, d_pre); + assert_eq!(nvda_pre.open.to_bits(), 1197.7_f64.to_bits()); + assert_eq!(nvda_pre.high.to_bits(), 1216.92_f64.to_bits()); + assert_eq!(nvda_pre.low.to_bits(), 1180.22_f64.to_bits()); + assert_eq!(nvda_pre.close.to_bits(), 1208.88_f64.to_bits()); + assert_eq!(nvda_pre.volume.to_bits(), (412_390_000.0_f64 / 10.0).to_bits()); + assert_eq!(nvda_pre.currency.as_ref(), "USD"); + assert_eq!(nvda_pre.vwap, None); + assert_eq!(nvda_pre.source.as_ref(), BARS_1D_SOURCE_EOD); + + let nvda_ex = &out.rows[3]; + assert_eq!(nvda_ex.listing_id, 20); + assert_eq!(nvda_ex.session_date, d_ex); + assert_eq!(nvda_ex.open.to_bits(), 120.37_f64.to_bits()); + assert_eq!(nvda_ex.volume.to_bits(), 314_162_700.0_f64.to_bits()); + + let nvda_post = &out.rows[4]; + assert_eq!(nvda_post.listing_id, 20); + assert_eq!(nvda_post.session_date, d_post); + assert_eq!(nvda_post.volume.to_bits(), 222_551_200.0_f64.to_bits()); +} + +#[test] +fn timestamps_match_1600_et_in_winter_summer_dst_transitions_and_drop_out_of_range() { + let mapping = + ProviderMappingTable::from_rows([map_row("eod", "AAPL.US", i32::MIN, None, 1)]).unwrap(); + let curr = currencies(&[(1, "USD")]); + let splits: SplitTable = SplitTable::default(); + + // Cover pre-2008 eras (1976, 1999, 2006) plus 2024 DST transitions (spring-forward + // 2024-03-10, fall-back 2024-11-03). Keep ascending by date to match sorted output. + let cases = [ + // (y, m, d, expected_utc_hour) + (1976, 4, 25, 20), // Era 1 spring-forward Sunday (last Sun Apr, EDT -> 20:00 UTC) + (1999, 1, 15, 21), // Era 2 winter EST -> 21:00 UTC + (2006, 6, 15, 20), // Era 2 summer EDT -> 20:00 UTC + (2024, 1, 15, 21), // Winter EST (UTC-5) -> 21:00 UTC + (2024, 3, 8, 21), // Friday before spring-forward (EST) + (2024, 3, 10, 20), // Spring-forward Sunday 16:00 EDT -> 20:00 UTC + (2024, 3, 11, 20), // Monday after spring-forward (EDT) + (2024, 7, 15, 20), // Summer EDT (UTC-4) -> 20:00 UTC + (2024, 11, 1, 20), // Friday before fall-back (EDT) + (2024, 11, 3, 21), // Fall-back Sunday 16:00 EST -> 21:00 UTC + (2024, 11, 4, 21), // Monday after fall-back (EST) + ]; + + let mut input_bars: Vec> = cases + .iter() + .map(|&(y, m, d, _)| bar("AAPL.US", day(y, m, d), 100.0, 101.0, 99.0, 100.5, 1_000.0)) + .collect(); + // Add out-of-range dates just outside [SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]. + input_bars.push(bar( + "AAPL.US", + SESSION_CLOSE_MIN_SUPPORTED_DATE - 1, // 1975-12-31 + 100.0, + 101.0, + 99.0, + 100.5, + 1_000.0, + )); + input_bars.push(bar( + "AAPL.US", + SESSION_CLOSE_MAX_SUPPORTED_DATE + 1, // 2031-01-01 + 100.0, + 101.0, + 99.0, + 100.5, + 1_000.0, + )); + + let out = curate_bars_1d( + input_bars, + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + ) + .unwrap(); + + assert_conservation_and_order(&out); + assert_eq!(out.stats.dropped_ts_out_of_range, 2); + assert_eq!(out.rows.len(), cases.len()); + + for (row, &(y, m, d, expected_utc_hour)) in out.rows.iter().zip(cases.iter()) { + let expected_ts = utc_micros(y, m, d, expected_utc_hour, 0, 0); + assert_eq!(row.session_date, day(y, m, d)); + assert_eq!( + row.ts_micros, expected_ts, + "mismatch for {y:04}-{m:02}-{d:02}" + ); + assert_eq!(row.known_at_micros, expected_ts); + } +} + +#[test] +fn pre_2008_bars_emit_exact_1600_et_timestamps_and_1975_bar_drops_out_of_range() { + let mapping = + ProviderMappingTable::from_rows([map_row("eod", "IBM.US", i32::MIN, None, 42)]).unwrap(); + let curr = currencies(&[(42, "USD")]); + let splits: SplitTable = SplitTable::default(); + + let d_1975 = day(1975, 6, 16); + let d_1999 = day(1999, 1, 15); + let d_2006 = day(2006, 6, 15); + + let input_bars = vec![ + bar("IBM.US", d_1975, 50.0, 51.0, 49.0, 50.5, 500_000.0), + bar("IBM.US", d_1999, 90.0, 92.0, 89.0, 91.25, 1_200_000.0), + bar("IBM.US", d_2006, 78.0, 79.5, 77.5, 79.0, 2_300_000.0), + ]; + + let out = curate_bars_1d( + input_bars, + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + ) + .unwrap(); + + assert_conservation_and_order(&out); + assert_eq!(out.stats.dropped_ts_out_of_range, 1); + assert_eq!(out.rows.len(), 2); + + // 1999-01-15 (EST -> 21:00 UTC) + let expected_1999 = utc_micros(1999, 1, 15, 21, 0, 0); + assert_eq!(out.rows[0].listing_id, 42); + assert_eq!(out.rows[0].session_date, d_1999); + assert_eq!(out.rows[0].ts_micros, expected_1999); + assert_eq!(out.rows[0].known_at_micros, expected_1999); + + // 2006-06-15 (EDT -> 20:00 UTC) + let expected_2006 = utc_micros(2006, 6, 15, 20, 0, 0); + assert_eq!(out.rows[1].listing_id, 42); + assert_eq!(out.rows[1].session_date, d_2006); + assert_eq!(out.rows[1].ts_micros, expected_2006); + assert_eq!(out.rows[1].known_at_micros, expected_2006); +} + +#[test] +fn date_ranged_mapping_routes_ticker_reuse_and_counts_unmapped_and_missing_currency() { + // FB.US: Meta (listing 100) 2012-05-18..=2022-06-08, gap, ETF (listing 200) 2025-01-02.. + // NOCURR.US: listing 300 (absent from currency map) + // BLANKCURR.US: listing 301 (whitespace-only currency) + // UNKNOWN.US: absent from mapping table + let d_pre = day(2012, 5, 17); + let d_meta_start = day(2012, 5, 18); + let d_meta_end = day(2022, 6, 8); + let d_gap1 = day(2022, 6, 9); + let d_gap2 = day(2025, 1, 1); + let d_etf_start = day(2025, 1, 2); + let d_etf_later = day(2025, 6, 2); + + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "FB.US", d_meta_start, Some(d_meta_end), 100), + map_row("eod", "FB.US", d_etf_start, None, 200), + map_row("eod", "NOCURR.US", i32::MIN, None, 300), + map_row("eod", "BLANKCURR.US", i32::MIN, None, 301), + ]) + .unwrap(); + + let mut curr = currencies(&[(100, "USD"), (200, "USD")]); + curr.insert(301, Cow::Borrowed(" ")); + + let splits: SplitTable = SplitTable::default(); + let input_bars = vec![ + bar("FB.US", d_pre, 38.0, 40.0, 37.0, 38.5, 100.0), // unmapped (pre) + bar("FB.US", d_meta_start, 42.0, 45.0, 38.0, 38.23, 500.0), // -> 100 + bar("FB.US", d_meta_end, 194.0, 197.0, 193.0, 196.64, 400.0), // -> 100 + bar("FB.US", d_gap1, 190.0, 195.0, 189.0, 191.0, 300.0), // unmapped (gap) + bar("FB.US", d_gap2, 25.0, 26.0, 24.0, 25.5, 200.0), // unmapped (gap) + bar("FB.US", d_etf_start, 25.0, 26.0, 24.5, 25.2, 600.0), // -> 200 + bar("FB.US", d_etf_later, 27.0, 28.0, 26.5, 27.4, 700.0), // -> 200 + bar("UNKNOWN.US", d_etf_start, 10.0, 11.0, 9.0, 10.5, 50.0), // unmapped (unknown key) + // Missing currency + pre-1976 date tests priority: missing currency wins over ts_out_of_range + bar("NOCURR.US", SESSION_CLOSE_MIN_SUPPORTED_DATE - 5, 10.0, 11.0, 9.0, 10.5, 50.0), + bar("NOCURR.US", d_etf_start, 10.0, 11.0, 9.0, 10.5, 50.0), + bar("BLANKCURR.US", d_etf_start, 10.0, 11.0, 9.0, 10.5, 50.0), + ]; + + let out = curate_bars_1d( + input_bars, + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + ) + .unwrap(); + + assert_conservation_and_order(&out); + assert_eq!(out.stats.dropped_unmapped, 4); + assert_eq!(out.stats.dropped_missing_currency, 3); + assert_eq!(out.stats.dropped_ts_out_of_range, 0); + assert_eq!(out.stats.rows_out, 4); + assert_eq!(out.stats.listings_out, 2); + + let keys: Vec<(i32, i32)> = out + .rows + .iter() + .map(|r| (r.listing_id, r.session_date)) + .collect(); + assert_eq!( + keys, + vec![ + (100, d_meta_start), + (100, d_meta_end), + (200, d_etf_start), + (200, d_etf_later), + ] + ); +} + +#[test] +fn cross_source_id_collisions_collapse_identical_and_drop_conflicting_groups() { + let d1 = day(2024, 5, 1); + let d2 = day(2024, 5, 2); + let d3 = day(2024, 5, 3); + + // Three source_ids mapped to listing 10; two source_ids mapped to listing 20 (all conflicting). + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "A.US", day(2020, 1, 1), None, 10), + map_row("eod", "B.US", day(2020, 1, 1), None, 10), + map_row("eod", "C.US", day(2020, 1, 1), None, 10), + map_row("eod", "X.US", day(2020, 1, 1), None, 20), + map_row("eod", "Y.US", day(2020, 1, 1), None, 20), + ]) + .unwrap(); + let curr = currencies(&[(10, "USD"), (20, "USD")]); + let splits: SplitTable = SplitTable::default(); + + let input_bars = vec![ + // d1 on listing 10: 3-way bitwise-identical OHLCV -> collapses to 1 (+2 collapsed) + bar("A.US", d1, 10.0, 12.0, 9.5, 11.25, 1_000.0), + bar("B.US", d1, 10.0, 12.0, 9.5, 11.25, 1_000.0), + bar("C.US", d1, 10.0, 12.0, 9.5, 11.25, 1_000.0), + // d2 on listing 10: 2 identical + 1 differing close -> entire group of 3 dropped + bar("A.US", d2, 10.0, 12.0, 9.5, 11.25, 1_000.0), + bar("B.US", d2, 10.0, 12.0, 9.5, 11.25, 1_000.0), + bar("C.US", d2, 10.0, 12.0, 9.5, 11.26, 1_000.0), + // d3 on listing 10: single uncontested bar -> kept + bar("A.US", d3, 11.0, 13.0, 10.5, 12.0, 2_000.0), + // d1 on listing 20: conflicting volume -> entire group of 2 dropped; listing 20 has 0 rows out + bar("X.US", d1, 50.0, 52.0, 49.0, 51.0, 5_000.0), + bar("Y.US", d1, 50.0, 52.0, 49.0, 51.0, 5_001.0), + ]; + + let out = curate_bars_1d( + input_bars, + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + ) + .unwrap(); + + assert_conservation_and_order(&out); + assert_eq!(out.stats.rows_in, 9); + assert_eq!(out.stats.rows_out, 2); + assert_eq!(out.stats.listings_out, 1); // listing 20 lost its only bar + assert_eq!(out.stats.listing_collision_collapsed, 2); + assert_eq!(out.stats.listing_collision_dropped, 5); + assert_eq!(out.rows[0].listing_id, 10); + assert_eq!(out.rows[0].session_date, d1); + assert_eq!(out.rows[1].listing_id, 10); + assert_eq!(out.rows[1].session_date, d3); +} + +#[test] +fn mixed_fixture_conservation_passthrough_permutation_invariance_and_empty_input() { + let d1 = day(2024, 2, 1); + let d2 = day(2024, 2, 2); + let d3 = day(2024, 2, 5); + let d_old = day(1975, 6, 16); + + let splits = SplitTable::from_events([( + "S1.US".to_string(), + SplitEvent { + ex_date: d2, + ratio: 2.0, + }, + )]) + .unwrap(); + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "S1.US", i32::MIN, None, 5), + map_row("eod", "S1_DUP.US", i32::MIN, None, 5), + map_row("eod", "NOCURR.US", i32::MIN, None, 9), + ]) + .unwrap(); + let curr = currencies(&[(5, "USD")]); + + let bars = vec![ + // Valid bar with split + QM mismatch (raw vol = 500, QM = 100 -> rel = 4.0) + bar("S1.US", d1, 20.0, 22.0, 19.0, 21.0, 1_000.0), + // Cross-source identical collision on (5, d1) (un-adjusted vol 500 == 500) + bar("S1_DUP.US", d1, 20.0, 22.0, 19.0, 21.0, 500.0), + // Cross-source conflicting collision on (5, d2) + bar("S1.US", d2, 10.0, 11.0, 9.5, 10.5, 2_000.0), + bar("S1_DUP.US", d2, 10.0, 11.0, 9.5, 10.6, 2_000.0), + // Builder invalid OHLC (dropped before curate stage) + bar("S1.US", d3, -1.0, 11.0, 9.0, 10.0, 100.0), + // Pre-1976 timestamp out of range + bar("S1.US", d_old, 5.0, 6.0, 4.5, 5.5, 100.0), + // Missing currency + bar("NOCURR.US", d3, 15.0, 16.0, 14.0, 15.5, 250.0), + // Unmapped key + bar("GHOST.US", d3, 15.0, 16.0, 14.0, 15.5, 250.0), + ]; + let qms = vec![qm("S1.US", d1, 100.0)]; + + // Compare builder stats and mismatch_samples directly against build_bars_1d. + let raw_built = build_bars_1d(bars.clone(), &splits, qms.clone(), 0.01).unwrap(); + let curated = curate_bars_1d( + bars.clone(), + &splits, + qms.clone(), + 0.01, + &mapping, + "eod", + &curr, + ) + .unwrap(); + + assert_conservation_and_order(&curated); + assert_eq!(curated.stats.builder, raw_built.stats); + assert_eq!(curated.mismatch_samples, raw_built.mismatch_samples); + assert_eq!(curated.mismatch_samples.len(), 1); + assert_eq!(curated.stats.dropped_unmapped, 1); + assert_eq!(curated.stats.dropped_missing_currency, 1); + assert_eq!(curated.stats.dropped_ts_out_of_range, 1); + assert_eq!(curated.stats.listing_collision_collapsed, 1); + assert_eq!(curated.stats.listing_collision_dropped, 2); + assert_eq!(curated.stats.rows_out, 1); + + // Permutation invariance: reversed input yields bitwise-identical rows, stats, and samples. + let mut rev_bars = bars; + rev_bars.reverse(); + let curated_rev = curate_bars_1d(rev_bars, &splits, qms, 0.01, &mapping, "eod", &curr).unwrap(); + assert_eq!(curated_rev.stats, curated.stats); + assert_eq!(curated_rev.mismatch_samples, curated.mismatch_samples); + assert_eq!(curated_rev.rows.len(), curated.rows.len()); + for (a, b) in curated_rev.rows.iter().zip(curated.rows.iter()) { + assert_row_bitwise_eq(a, b); + } + + // Empty input satisfies conservation cleanly. + let empty = curate_bars_1d( + std::iter::empty::>(), + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + ) + .unwrap(); + assert_conservation_and_order(&empty); + assert_eq!(empty.stats, CurateBars1dStats::default()); + assert!(empty.rows.is_empty()); + assert!(empty.mismatch_samples.is_empty()); +} + +#[test] +fn typed_caller_errors_and_write_wrapper_error_propagation() { + let splits: SplitTable = SplitTable::default(); + let mapping = ProviderMappingTable::default(); + let curr: HashMap> = HashMap::new(); + + // Invalid rel_tolerance takes precedence even if mapping_source is blank. + for bad_tol in [f64::NAN, -0.01, f64::INFINITY, f64::NEG_INFINITY] { + let err = curate_bars_1d( + std::iter::empty::>(), + &splits, + std::iter::empty::>(), + bad_tol, + &mapping, + " ", + &curr, + ) + .unwrap_err(); + assert!(matches!( + err, + CurateBarsError::Bars(BarsError::InvalidTolerance { .. }) + )); + assert!(err.source().is_some()); + assert!(err.to_string().contains("tolerance")); + } + + // Blank mapping_source returns EmptyMappingSource. + for blank in ["", " ", "\t\n"] { + let err = curate_bars_1d( + std::iter::empty::>(), + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + blank, + &curr, + ) + .unwrap_err(); + assert_eq!(err, CurateBarsError::EmptyMappingSource); + assert!(err.source().is_none()); + assert!(err.to_string().contains("mapping_source")); + } + + // Write wrapper propagates CurateBarsError and ParquetBarsError. + let tmp = TempDirGuard::new("errors"); + let curate_err = curate_and_write_bars_1d( + tmp.path(), + std::iter::empty::>(), + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "", + &curr, + Bars1dWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + curate_err, + CurateBarsWriteError::Curate(CurateBarsError::EmptyMappingSource) + )); + assert!(curate_err.source().is_some()); + assert!(curate_err.to_string().contains("curation failed")); + + let pq_err = curate_and_write_bars_1d( + tmp.path(), + std::iter::empty::>(), + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + Bars1dWriteOptions { + row_group_rows: 0, + ..Bars1dWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!( + pq_err, + CurateBarsWriteError::Parquet(ParquetBarsError::InvalidRowGroupRows) + )); + assert!(pq_err.source().is_some()); + assert!(pq_err.to_string().contains("Parquet write failed")); +} + +#[test] +fn curate_and_write_bars_1d_round_trips_multi_year_parquet_partitions_bit_for_bit() { + let tmp = TempDirGuard::new("round-trip"); + let splits = SplitTable::from_events([( + "NVDA.US".to_string(), + SplitEvent { + ex_date: day(2024, 6, 10), + ratio: 10.0, + }, + )]) + .unwrap(); + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "NVDA.US", day(2015, 1, 1), None, 20), + map_row("eod", "RY.TO", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + let curr = currencies(&[(10, "CAD"), (20, "USD")]); + + let bars = vec![ + bar("NVDA.US", day(2022, 6, 15), 160.0, 166.5, 158.2, 165.27, 450_000_000.0), + bar("NVDA.US", day(2023, 11, 6), 452.85, 459.35, 448.99, 457.51, 400_000_000.0), + bar("NVDA.US", day(2024, 6, 11), 121.77, 122.87, 118.74, 120.91, 222_551_200.0), + bar("RY.TO", day(2022, 12, 30), 127.0, 128.1, 126.4, 127.3, 1_800_000.0), + bar("RY.TO", day(2024, 1, 15), 133.5, 134.9, 132.8, 134.2, 2_100_000.0), + ]; + + let stage = curate_bars_1d( + bars.clone(), + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + ) + .unwrap(); + let report = curate_and_write_bars_1d( + tmp.path(), + bars, + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + Bars1dWriteOptions::default(), + ) + .unwrap(); + + assert_eq!(report.curate_stats, stage.stats); + assert_eq!(report.mismatch_samples, stage.mismatch_samples); + assert_eq!(report.write_stats.rows_written, stage.rows.len()); + assert_eq!(report.write_stats.files_written, 3); + assert_eq!(report.write_stats.rows_by_year.get(&2022), Some(&2)); + assert_eq!(report.write_stats.rows_by_year.get(&2023), Some(&1)); + assert_eq!(report.write_stats.rows_by_year.get(&2024), Some(&2)); + + let bars_dir = tmp.path().join("bars_1d"); + assert!( + !bars_dir.join(".write.lock").exists(), + "transient .write.lock must be cleaned up" + ); + + let mut read_back_all = Vec::new(); + for year in [2022, 2023, 2024] { + let year_dir = bars_dir.join(format!("year={year:04}")); + let part_path = year_dir.join("part.parquet"); + assert!(part_path.exists(), "expected {}", part_path.display()); + + // Ensure no transient .tmp or .bak files remain in the partition directory. + for entry in fs::read_dir(&year_dir).expect("read year dir") { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!( + name, "part.parquet", + "unexpected transient file '{name}' in {}", + year_dir.display() + ); + } + + let year_rows = read_parquet_rows(&part_path); + let expected_year_rows: Vec<&Bars1dParquetRow> = stage + .rows + .iter() + .filter(|r| epoch_days_to_ymd(r.session_date).0 == year) + .collect(); + assert_eq!(year_rows.len(), expected_year_rows.len()); + for (actual, expected) in year_rows.iter().zip(expected_year_rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + read_back_all.extend(year_rows); + } + + read_back_all.sort_unstable_by(|a, b| { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.session_date.cmp(&b.session_date)) + }); + assert_eq!(read_back_all.len(), stage.rows.len()); + for (actual, expected) in read_back_all.iter().zip(stage.rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } +} diff --git a/tools/curate-etl/src/curate_events.rs b/tools/curate-etl/src/curate_events.rs new file mode 100644 index 00000000..84a074d6 --- /dev/null +++ b/tools/curate-etl/src/curate_events.rs @@ -0,0 +1,273 @@ +//! Pure, in-memory `events` curation stage joining [`crate::events::build_events`], +//! [`crate::provider_mapping::ProviderMappingTable`], and +//! [`crate::parquet_events::write_events_dataset`] into contract [`EventsParquetRow`]s. +//! +//! # Contract & Point-in-Time Rules +//! - Calls the [`crate::events::build_events`] pipeline unchanged on source keys so same-day +//! earnings↔filing linking (`8-K` / `News release`), form classification, timestamp parsing, +//! conservative `16:05 ET` fallback, and per-key deduplication run before `provider_mapping` +//! resolution. +//! - **Exact Eastern local `event_date` mechanism:** Internally uses the crate-private +//! [`crate::events::build_events_with_dates`] helper (zero overhead on public `build_events`, +//! unchanged `EventsParquetRow` schema) to carry each row's already-parsed Eastern local +//! calendar date (`ParsedFilingTime::et_date` for filings; `QmEarning::report_date` for +//! earnings) alongside the row. This guarantees exact Eastern-date `provider_mapping` lookup +//! across all supported years—including pre-2008 historical filings and late-evening EST/EDT +//! filings whose UTC date has already rolled over to the next day—never using UTC date or +//! `known_at` date. +//! - Resolves each row's `(mapping_source, key, event_date)` to a permanent `listing_id: i32` via +//! [`ProviderMappingTable::cursor_for`] / [`ProviderMappingCursor::resolve`] (opening one cursor +//! per contiguous `key` run, since `build_events_with_dates` emits rows sorted by `key` then +//! `ts_micros`). Rows with no covering mapping range are dropped into `dropped_unmapped`. +//! - Moves `subtype` and `payload_json` without cloning, keeps `known_at_source` and `kind` as +//! `Cow::Borrowed`, and frees builder rows before re-sorting in place by the exact 7-field +//! writer key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, +//! known_at_source)`. +//! - Cross-`key` rows mapping to the same `listing_id` that are equal on all seven fields collapse +//! to one row (`listing_duplicate_collapsed`); rows differing in any single field are all kept +//! (events are not unique per `(listing_id, ts)`). + +use std::borrow::Cow; +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; +use std::path::Path; + +use crate::events::{ + build_events_with_dates, EventRowWithDate, EventsStats, QmEarning, QmFiling, + EVENT_KIND_EARNINGS, EVENT_KIND_FILING, +}; +use crate::parquet_events::{ + write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, + ParquetEventsError, +}; +use crate::provider_mapping::{ProviderMappingCursor, ProviderMappingTable}; + +/// Accounting summary produced alongside [`CurateEventsOutput::rows`]. +/// +/// Conservation invariants: +/// - `rows_in == builder.rows_out` +/// - `rows_in == rows_out + dropped_unmapped + listing_duplicate_collapsed` +/// - `rows_out == filings_out + earnings_out` +/// - `builder` independently satisfies all [`EventsStats`] conservation invariants. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateEventsStats { + pub builder: EventsStats, + pub rows_in: usize, + pub rows_out: usize, + pub listings_out: usize, + pub filings_out: usize, + pub earnings_out: usize, + pub dropped_unmapped: usize, + pub listing_duplicate_collapsed: usize, +} + +/// Output of [`curate_events`]: contract Parquet rows strictly ascending in the 7-field writer +/// sort key and full stage + builder stats. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateEventsOutput { + pub rows: Vec, + pub stats: CurateEventsStats, +} + +/// Typed caller errors returned by [`curate_events`]. +/// +/// Bad or unmapped single rows are skipped/dropped and counted in [`CurateEventsStats`] rather +/// than aborting the stage. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CurateEventsError { + /// Caller-supplied `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, +} + +impl fmt::Display for CurateEventsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::EmptyMappingSource => { + write!(f, "mapping_source must not be empty or blank") + } + } + } +} + +impl Error for CurateEventsError {} + +/// Combined stats returned by [`curate_and_write_events`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateEventsWriteReport { + pub curate_stats: CurateEventsStats, + pub write_stats: EventsWriteStats, +} + +/// Typed error returned by [`curate_and_write_events`]. +#[derive(Debug)] +pub enum CurateEventsWriteError { + Curate(CurateEventsError), + Parquet(ParquetEventsError), +} + +impl fmt::Display for CurateEventsWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => write!(f, "events curation failed: {err}"), + Self::Parquet(err) => write!(f, "events Parquet write failed: {err}"), + } + } +} + +impl Error for CurateEventsWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CurateEventsWriteError { + fn from(err: CurateEventsError) -> Self { + Self::Curate(err) + } +} + +impl From for CurateEventsWriteError { + fn from(err: ParquetEventsError) -> Self { + Self::Parquet(err) + } +} + +#[inline] +fn compare_event_rows(a: &EventsParquetRow, b: &EventsParquetRow) -> Ordering { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) +} + +/// Pure `events` curation stage: builds point-in-time `qmFilings` + `qmEarnings` rows on source +/// keys, resolves `(mapping_source, key, event_date) -> listing_id` on each event's exact Eastern +/// local calendar date via `provider_mapping`, and emits contract [`EventsParquetRow`]s strictly +/// ascending in the 7-field writer key. +/// +/// `event_date` is the filing's `timefiled` Eastern local calendar date for filings and +/// `report_date` for earnings—never the UTC date and never the `known_at` date. Rows with no +/// covering mapping range are dropped into `dropped_unmapped`. Cross-`key` rows that map to the +/// same `listing_id` and match on all seven fields collapse to one row +/// (`listing_duplicate_collapsed`); rows differing in any field are all kept. +pub fn curate_events( + filings: IF, + earnings: IE, + mapping_source: &str, + mapping: &ProviderMappingTable, +) -> Result +where + K: Ord + Clone + AsRef, + IF: IntoIterator>, + IE: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CurateEventsError::EmptyMappingSource); + } + + let (built_rows, builder_stats) = build_events_with_dates(filings, earnings); + + let mut stats = CurateEventsStats { + builder: builder_stats, + rows_in: built_rows.len(), + ..CurateEventsStats::default() + }; + + let mut rows: Vec = Vec::with_capacity(built_rows.len()); + let mut current_key: Option = None; + let mut current_cursor: Option> = None; + + for EventRowWithDate { row, event_date } in built_rows { + if current_key.as_ref() != Some(&row.key) { + current_cursor = Some(mapping.cursor_for(mapping_source, row.key.as_ref())); + current_key = Some(row.key); + } + + let cursor = current_cursor + .as_mut() + .expect("cursor initialized for current key run"); + if cursor.ranges().is_empty() { + stats.dropped_unmapped += 1; + continue; + } + + let Some(listing_id) = cursor.resolve(event_date) else { + stats.dropped_unmapped += 1; + continue; + }; + + rows.push(EventsParquetRow { + listing_id, + ts_micros: row.ts_micros, + known_at_micros: row.known_at_micros, + known_at_source: Cow::Borrowed(row.known_at_source), + kind: Cow::Borrowed(row.kind), + subtype: row.subtype, + payload_json: row.payload_json, + }); + } + + // `built_rows` has been consumed by value; drop key state before re-sorting. + drop(current_key); + + rows.sort_unstable_by(compare_event_rows); + + let mapped_len = rows.len(); + rows.dedup(); + stats.listing_duplicate_collapsed = mapped_len - rows.len(); + + let mut last_listing_id: Option = None; + for row in &rows { + if last_listing_id != Some(row.listing_id) { + stats.listings_out += 1; + last_listing_id = Some(row.listing_id); + } + match row.kind.as_ref() { + EVENT_KIND_FILING => stats.filings_out += 1, + EVENT_KIND_EARNINGS => stats.earnings_out += 1, + other => unreachable!("unexpected event kind from build_events: {other:?}"), + } + } + stats.rows_out = rows.len(); + + Ok(CurateEventsOutput { rows, stats }) +} + +/// Thin end-to-end wrapper running [`curate_events`] and publishing the resulting contract rows +/// via [`write_events_dataset`] to `/events/year=YYYY/part.parquet`. +/// +/// Any [`CurateEventsError`] returns before [`write_events_dataset`] is invoked, leaving +/// `out_dir` untouched. +pub fn curate_and_write_events( + out_dir: P, + filings: IF, + earnings: IE, + mapping_source: &str, + mapping: &ProviderMappingTable, + options: EventsWriteOptions, +) -> Result +where + P: AsRef, + K: Ord + Clone + AsRef, + IF: IntoIterator>, + IE: IntoIterator>, +{ + let curated = curate_events(filings, earnings, mapping_source, mapping)?; + let write_stats = write_events_dataset(out_dir, &curated.rows, options)?; + Ok(CurateEventsWriteReport { + curate_stats: curated.stats, + write_stats, + }) +} + +#[cfg(test)] +#[path = "curate_events_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_events_tests.rs b/tools/curate-etl/src/curate_events_tests.rs new file mode 100644 index 00000000..d680c87e --- /dev/null +++ b/tools/curate-etl/src/curate_events_tests.rs @@ -0,0 +1,891 @@ +use std::borrow::Cow; +use std::cmp::Ordering; +use std::collections::BTreeMap; +use std::error::Error; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::events::{ + build_events, partition_year_utc, EVENT_KIND_EARNINGS, EVENT_KIND_FILING, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::provider_mapping::ProviderMappingRow; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-curate-events-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn filing( + key: &str, + timefiled: &str, + form_type: &str, + filing_id: Option<&str>, + url: Option<&str>, +) -> QmFiling { + QmFiling { + key: key.to_string(), + timefiled: timefiled.to_string(), + form_type: form_type.to_string(), + filing_id: filing_id.map(str::to_string), + url: url.map(str::to_string), + } +} + +fn earning( + key: &str, + report_date: i32, + announce_time: &str, + fiscal_period_end: Option, + actual_eps: Option, + revenue: Option, +) -> QmEarning { + QmEarning { + key: key.to_string(), + report_date, + announce_time: announce_time.to_string(), + fiscal_period_end, + actual_eps, + revenue, + } +} + +fn map_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +fn assert_conservation_and_order(out: &CurateEventsOutput) { + let s = &out.stats; + assert_eq!( + s.rows_in, s.builder.rows_out, + "rows_in != builder.rows_out: {s:?}" + ); + assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); + assert_eq!( + s.rows_in, + s.rows_out + s.dropped_unmapped + s.listing_duplicate_collapsed, + "curate accounting conservation mismatch: {s:?}" + ); + assert_eq!( + s.rows_out, + s.filings_out + s.earnings_out, + "rows_out != filings_out + earnings_out: {s:?}" + ); + assert_eq!( + s.builder.filings_in, + s.builder.filings_out + + s.builder.filings_skipped_malformed_timestamp + + s.builder.filings_skipped_unknown_zone + + s.builder.filings_skipped_invalid_date_time + + s.builder.filings_duplicate_collapsed, + "builder filings conservation mismatch: {s:?}" + ); + assert_eq!( + s.builder.earnings_in, + s.builder.earnings_out + + s.builder.earnings_skipped_out_of_range + + s.builder.earnings_duplicate_collapsed + + s.builder.earnings_duplicate_conflict_dropped, + "builder earnings conservation mismatch: {s:?}" + ); + assert_eq!( + s.builder.rows_out, + s.builder.filings_out + s.builder.earnings_out + ); + + let mut distinct_listings = 0usize; + let mut prev_listing: Option = None; + let mut filings_count = 0usize; + let mut earnings_count = 0usize; + for row in &out.rows { + if prev_listing != Some(row.listing_id) { + distinct_listings += 1; + prev_listing = Some(row.listing_id); + } + match row.kind.as_ref() { + EVENT_KIND_FILING => filings_count += 1, + EVENT_KIND_EARNINGS => earnings_count += 1, + other => panic!("unexpected event kind: {other:?}"), + } + } + assert_eq!(s.listings_out, distinct_listings); + assert_eq!(s.filings_out, filings_count); + assert_eq!(s.earnings_out, earnings_count); + + for pair in out.rows.windows(2) { + assert_eq!( + compare_event_rows(&pair[0], &pair[1]), + Ordering::Less, + "output rows must be strictly ascending in 7-field writer key:\n left: {:?}\n right: {:?}", + pair[0], + pair[1] + ); + } +} + +fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int32ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int32ColumnReader"), + } + values +} + +fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int64ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int64ColumnReader"), + } + values +} + +fn read_str_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected ByteArrayColumnReader"), + } + values + .into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8")) + .collect() +} + +fn read_events_parquet_file(path: &Path) -> (usize, Vec) { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let footer_rows = metadata.file_metadata().num_rows() as usize; + let mut out = Vec::with_capacity(footer_rows); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let listing_id = read_i32_col(rg_reader.get_column_reader(0).unwrap(), num_rows); + let ts_micros = read_i64_col(rg_reader.get_column_reader(1).unwrap(), num_rows); + let known_at_micros = read_i64_col(rg_reader.get_column_reader(2).unwrap(), num_rows); + let known_at_source = read_str_col(rg_reader.get_column_reader(3).unwrap(), num_rows); + let kind = read_str_col(rg_reader.get_column_reader(4).unwrap(), num_rows); + let subtype = read_str_col(rg_reader.get_column_reader(5).unwrap(), num_rows); + let payload_json = read_str_col(rg_reader.get_column_reader(6).unwrap(), num_rows); + + for i in 0..num_rows { + out.push(EventsParquetRow { + listing_id: listing_id[i], + ts_micros: ts_micros[i], + known_at_micros: known_at_micros[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + (footer_rows, out) +} + +fn read_all_events_partitions(out_dir: &Path) -> (BTreeMap>, Vec) { + let events_dir = out_dir.join("events"); + let mut by_year: BTreeMap> = BTreeMap::new(); + let mut all_rows: Vec = Vec::new(); + + for entry in fs::read_dir(&events_dir).expect("read events dir") { + let entry = entry.unwrap(); + let name = entry.file_name().to_string_lossy().into_owned(); + let year_str = name + .strip_prefix("year=") + .unwrap_or_else(|| panic!("unexpected entry '{name}' in {}", events_dir.display())); + let year: i32 = year_str + .parse() + .unwrap_or_else(|_| panic!("invalid year dir '{name}'")); + let year_dir = entry.path(); + + let mut saw_part = false; + for file_entry in fs::read_dir(&year_dir).expect("read year dir") { + let fname = file_entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!( + fname, + "part.parquet", + "unexpected transient file '{fname}' in {}", + year_dir.display() + ); + saw_part = true; + } + assert!(saw_part, "missing part.parquet in {}", year_dir.display()); + + let (footer_rows, rows) = read_events_parquet_file(&year_dir.join("part.parquet")); + assert_eq!(footer_rows, rows.len()); + all_rows.extend(rows.iter().cloned()); + by_year.insert(year, rows); + } + + all_rows.sort_unstable_by(compare_event_rows); + (by_year, all_rows) +} + +#[test] +fn happy_path_mixed_filings_and_earnings_multi_key_multi_year_round_trips_parquet() { + // Assign "QM_B" a smaller listing_id (10) than "QM_A" (20) to verify re-sorting by listing_id. + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "QM_A", day(2015, 1, 1), None, 20), + map_row("qm", "QM_B", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + + let filings = vec![ + filing( + "QM_A", + "2023-11-02T16:30:00 EDT", + "8-K", + Some("ACC-A-2023"), + Some("https://sec.example/a-2023"), + ), + filing( + "QM_A", + "2024-02-28T07:15:00 EST", + "10-K", + Some("ACC-A-2024"), + None, + ), + filing( + "QM_B", + "2024-05-01T17:05:00 EDT", + "News release", + Some("NR-B-2024"), + Some("https://sedar.example/b-2024"), + ), + filing( + "QM_B", + "2025-03-10T08:00:00 EDT", + "Annual financial statements", + Some("AFS-B-2025"), + None, + ), + ]; + + let earnings = vec![ + // Linked to QM_A's 2023-11-02 8-K + earning( + "QM_A", + day(2023, 11, 2), + "AMC", + Some(day(2023, 9, 30)), + Some(1.42), + Some(500_000_000.0), + ), + // Unlinked on 2024-08-01 -> 16:05 EDT statutory lag + earning( + "QM_A", + day(2024, 8, 1), + "BTO", + Some(day(2024, 6, 30)), + Some(1.55), + Some(520_000_000.0), + ), + // Linked to QM_B's 2024-05-01 News release + earning( + "QM_B", + day(2024, 5, 1), + "N/A", + Some(day(2024, 3, 31)), + Some(0.38), + None, + ), + ]; + + let raw_built = build_events(filings.clone(), earnings.clone()); + let curated = curate_events(filings.clone(), earnings.clone(), "qm", &mapping).unwrap(); + + assert_conservation_and_order(&curated); + assert_eq!(curated.stats.builder, raw_built.stats); + assert_eq!(curated.stats.rows_in, 7); + assert_eq!(curated.stats.rows_out, 7); + assert_eq!(curated.stats.listings_out, 2); + assert_eq!(curated.stats.filings_out, 4); + assert_eq!(curated.stats.earnings_out, 3); + assert_eq!(curated.stats.dropped_unmapped, 0); + assert_eq!(curated.stats.listing_duplicate_collapsed, 0); + + // Listing 10 (QM_B: 2 filings + 1 earnings = 3 rows) precedes Listing 20 (QM_A: 4 rows). + assert_eq!( + curated.rows.iter().map(|r| r.listing_id).collect::>(), + vec![10, 10, 10, 20, 20, 20, 20] + ); + + // Round-trip through curate_and_write_events and read back every year partition. + let tmp = TempDirGuard::new("happy-roundtrip"); + let report = curate_and_write_events( + tmp.path(), + filings, + earnings, + "qm", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap(); + + assert_eq!(report.curate_stats, curated.stats); + assert_eq!(report.write_stats.rows_written, curated.rows.len()); + assert_eq!(report.write_stats.files_written, 3); // 2023, 2024, 2025 + + let (by_year, read_back_all) = read_all_events_partitions(tmp.path()); + assert_eq!(by_year.keys().copied().collect::>(), vec![2023, 2024, 2025]); + assert_eq!(read_back_all, curated.rows); + + // Verify each year partition contains exactly the rows whose UTC partition year matches. + for (year, year_rows) in &by_year { + let expected_for_year: Vec = curated + .rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == *year) + .cloned() + .collect(); + assert_eq!(year_rows, &expected_for_year); + } +} + +#[test] +fn point_in_time_et_date_mapping_boundaries_late_evening_year_end_pre_2008_and_linked_earnings() { + // Ticker "SWITCH" changes listing on 2003-07-16 (pre-2008) and D = 2024-06-15: + // listing 90: 2000-01-01 ..= 2003-07-15 + // listing 100: 2003-07-16 ..= 2024-06-14 (D - 1) + // listing 200: 2024-06-15 ..= 2024-12-31 + // listing 300: 2025-01-01 .. (open-ended) + let d_pre2008_before = day(2003, 7, 15); + let d_pre2008_switch = day(2003, 7, 16); + let d_switch = day(2024, 6, 15); + let d_before = day(2024, 6, 14); + + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "SWITCH", day(2000, 1, 1), Some(d_pre2008_before), 90), + map_row("qm", "SWITCH", d_pre2008_switch, Some(d_before), 100), + map_row("qm", "SWITCH", d_switch, Some(day(2024, 12, 31)), 200), + map_row("qm", "SWITCH", day(2025, 1, 1), None, 300), + ]) + .unwrap(); + + let filings = vec![ + // (c) Pre-2008 afternoon filing (2003-07-15 EDT) -> listing 90 + filing( + "SWITCH", + "2003-07-15T14:30:00 EDT", + "10-Q", + Some("PRE-2008"), + None, + ), + // (c2) Pre-2008 late-evening filing (2003-07-15T22:30:00 EDT -> UTC 2003-07-16T02:30:00Z). + // Crosses the 2003-07-16 listing switch in UTC; must map on ET date 2003-07-15 -> OLD listing 90! + filing( + "SWITCH", + "2003-07-15T22:30:00 EDT", + "8-K", + Some("PRE-2008-LATE-EVE"), + None, + ), + // (a) Before switch date D -> listing 100 + filing( + "SWITCH", + "2024-06-14T10:00:00 EDT", + "10-Q", + Some("BEFORE-D"), + None, + ), + // (b) 23:30:00 EST on D-1 (2024-06-14) whose UTC timestamp is 2024-06-15T04:30:00Z (UTC date = D). + // Must resolve on ET date 2024-06-14 -> OLD listing 100, NOT listing 200! + // Also serves as the qualifying 8-K for (d) same-day linked earnings on report_date = D-1. + filing( + "SWITCH", + "2024-06-14T23:30:00 EST", + "8-K", + Some("LATE-EVE-D-MINUS-1"), + None, + ), + // (a) On switch date D -> NEW listing 200 + filing( + "SWITCH", + "2024-06-15T09:00:00 EDT", + "10-K", + Some("ON-D"), + None, + ), + // Dec 31 21:30:00 EST (UTC = 2025-01-01T02:30:00Z): + // Must resolve provider_mapping on ET date 2024-12-31 -> listing 200 (NOT listing 300), + // while partitioning into Parquet year=2025! + filing( + "SWITCH", + "2024-12-31T21:30:00 EST", + "8-K", + Some("DEC31-ROLLOVER"), + None, + ), + // On 2025-01-01 -> listing 300 + filing( + "SWITCH", + "2025-01-01T08:00:00 EST", + "10-K", + Some("NEW-YEAR-2025"), + None, + ), + ]; + + let earnings = vec![ + // (d) Linked to the late-evening 2024-06-14T23:30:00 EST 8-K (UTC date = 2024-06-15 = D). + // Must map on report_date = 2024-06-14 -> OLD listing 100! + earning( + "SWITCH", + d_before, + "AMC", + Some(day(2024, 3, 31)), + Some(0.75), + Some(10_000_000.0), + ), + ]; + + let curated = curate_events(filings.clone(), earnings.clone(), "qm", &mapping).unwrap(); + assert_conservation_and_order(&curated); + assert_eq!(curated.stats.rows_out, 8); + assert_eq!(curated.stats.listings_out, 4); + assert_eq!(curated.stats.dropped_unmapped, 0); + + let listing_of = |needle: &str| -> i32 { + curated + .rows + .iter() + .find(|r| r.payload_json.contains(needle)) + .unwrap_or_else(|| panic!("missing row containing {needle}")) + .listing_id + }; + + assert_eq!(listing_of("PRE-2008"), 90); + assert_eq!(listing_of("PRE-2008-LATE-EVE"), 90); + assert_eq!(listing_of("BEFORE-D"), 100); + assert_eq!(listing_of("LATE-EVE-D-MINUS-1"), 100); + assert_eq!(listing_of("ON-D"), 200); + assert_eq!(listing_of("DEC31-ROLLOVER"), 200); + assert_eq!(listing_of("NEW-YEAR-2025"), 300); + + // Check the linked earnings row specifically. + let earn_row = curated + .rows + .iter() + .find(|r| r.kind.as_ref() == EVENT_KIND_EARNINGS) + .expect("earnings row present"); + assert_eq!(earn_row.listing_id, 100); + assert_eq!(earn_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(earn_row.payload_json.contains("LATE-EVE-D-MINUS-1")); + + // Verify Dec 31 21:30 EST row lands in year=2025/part.parquet with listing_id=200. + let tmp = TempDirGuard::new("year-end-rollover"); + let report = curate_and_write_events( + tmp.path(), + filings, + earnings, + "qm", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(report.write_stats.rows_written, 8); + + let (by_year, _) = read_all_events_partitions(tmp.path()); + assert_eq!(by_year.keys().copied().collect::>(), vec![2003, 2024, 2025]); + let y2025 = &by_year[&2025]; + assert_eq!(y2025.len(), 2); + let dec31_row = y2025 + .iter() + .find(|r| r.payload_json.contains("DEC31-ROLLOVER")) + .expect("DEC31-ROLLOVER in year=2025"); + assert_eq!(dec31_row.listing_id, 200); +} + +#[test] +fn drops_unmapped_keys_wrong_source_and_out_of_range_dates() { + // Ticker "GAPPED": + // listing 10: 2020-01-01 ..= 2021-12-31 + // gap: 2022-01-01 ..= 2022-12-31 + // listing 20: 2023-01-01 ..= 2024-12-31 + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "GAPPED", day(2020, 1, 1), Some(day(2021, 12, 31)), 10), + map_row("qm", "GAPPED", day(2023, 1, 1), Some(day(2024, 12, 31)), 20), + map_row("eod", "WRONGSRC", day(2015, 1, 1), None, 30), + ]) + .unwrap(); + + let filings = vec![ + filing("GAPPED", "2019-12-31T16:00:00 EST", "10-K", Some("PRE"), None), // pre-range + filing("GAPPED", "2020-01-01T09:00:00 EST", "10-K", Some("IN1"), None), // -> 10 + filing("GAPPED", "2022-06-15T12:00:00 EDT", "10-Q", Some("GAP"), None), // interior gap + filing("GAPPED", "2023-06-15T12:00:00 EDT", "10-Q", Some("IN2"), None), // -> 20 + filing("GAPPED", "2025-01-01T09:00:00 EST", "10-K", Some("POST"), None), // post-range + filing("UNKNOWN", "2023-06-15T12:00:00 EDT", "8-K", Some("UNK"), None), // unknown key + filing("WRONGSRC", "2023-06-15T12:00:00 EDT", "8-K", Some("WS"), None), // wrong source + ]; + + let earnings = vec![ + earning("GAPPED", day(2022, 5, 1), "AMC", None, Some(1.0), None), // interior gap + earning("GAPPED", day(2024, 5, 1), "AMC", None, Some(2.0), None), // -> 20 + ]; + + let curated = curate_events(filings, earnings, "qm", &mapping).unwrap(); + assert_conservation_and_order(&curated); + assert_eq!(curated.stats.rows_in, 9); + assert_eq!(curated.stats.rows_out, 3); + assert_eq!(curated.stats.listings_out, 2); + assert_eq!(curated.stats.filings_out, 2); + assert_eq!(curated.stats.earnings_out, 1); + assert_eq!(curated.stats.dropped_unmapped, 6); + assert_eq!(curated.stats.listing_duplicate_collapsed, 0); +} + +#[test] +fn cross_key_identical_seven_field_rows_collapse_while_any_single_field_difference_is_kept() { + // Keys "ALIAS_1" and "ALIAS_2" both map to listing_id 50. + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "ALIAS_1", day(2020, 1, 1), None, 50), + map_row("qm", "ALIAS_2", day(2020, 1, 1), None, 50), + ]) + .unwrap(); + + let d_earn = day(2024, 4, 15); + + let filings = vec![ + // 1. Exact 7-field duplicate across ALIAS_1 and ALIAS_2 -> collapses to 1 (+1 collapsed) + filing( + "ALIAS_1", + "2024-03-01T10:00:00 EST", + "10-K", + Some("DUP-ID"), + Some("https://sec.example/dup"), + ), + filing( + "ALIAS_2", + "2024-03-01T10:00:00 EST", + "10-K", + Some("DUP-ID"), + Some("https://sec.example/dup"), + ), + // 2. Differing only in ts_micros (and known_at_micros) -> both kept + filing( + "ALIAS_2", + "2024-03-01T10:00:01 EST", + "10-K", + Some("DUP-ID"), + Some("https://sec.example/dup"), + ), + // 3. Differing in subtype (10-Q vs 10-K) at exact same timestamp -> kept + filing( + "ALIAS_2", + "2024-03-01T10:00:00 EST", + "10-Q", + Some("DUP-ID"), + Some("https://sec.example/dup"), + ), + // 4. Differing only in payload_json (different filing_id) at same timestamp + subtype -> kept + filing( + "ALIAS_2", + "2024-03-01T10:00:00 EST", + "10-K", + Some("DIFF-ID"), + Some("https://sec.example/dup"), + ), + // 5. Same timestamp as an earnings row, differing in kind ("filing" vs "earnings"), + // AND also creates a linked earnings row on ALIAS_1 at 16:05:00 EDT with + // filing_id = None, so ALIAS_1's earnings has known_at_source = "filing_timestamp" + // while ALIAS_2's unlinked earnings on the same report_date has the EXACT same + // ts_micros, known_at_micros, kind, subtype, payload_json, differing ONLY in + // known_at_source ("statutory_lag_estimate")! + filing("ALIAS_1", "2024-04-15T16:05:00 EDT", "8-K", None, None), + ]; + + let earnings = vec![ + // Linked on ALIAS_1 (16:05:00 EDT, filing_timestamp, linked_filing_id = null) + earning("ALIAS_1", d_earn, "AMC", Some(day(2024, 3, 31)), Some(1.0), Some(100.0)), + // Unlinked on ALIAS_2 (16:05:00 EDT, statutory_lag_estimate, linked_filing_id = null) + earning("ALIAS_2", d_earn, "AMC", Some(day(2024, 3, 31)), Some(1.0), Some(100.0)), + // Exact 7-field duplicate earnings across ALIAS_1 and ALIAS_2 on a different unlinked date -> collapses (+1) + earning("ALIAS_1", day(2024, 7, 15), "BTO", None, Some(2.0), None), + earning("ALIAS_2", day(2024, 7, 15), "BTO", None, Some(2.0), None), + ]; + + let curated = curate_events(filings, earnings, "qm", &mapping).unwrap(); + assert_conservation_and_order(&curated); + + // 6 filings in -> 6 out of builder; 4 earnings in -> 4 out of builder; total rows_in = 10. + // 2 exact 7-field duplicates collapse (1 filing + 1 earnings) -> 8 rows out. + assert_eq!(curated.stats.rows_in, 10); + assert_eq!(curated.stats.listing_duplicate_collapsed, 2); + assert_eq!(curated.stats.rows_out, 8); + assert_eq!(curated.stats.filings_out, 5); + assert_eq!(curated.stats.earnings_out, 3); + assert_eq!(curated.stats.listings_out, 1); + + // Confirm the two d_earn earnings rows differ ONLY in known_at_source and both survived. + let d_earn_rows: Vec<&EventsParquetRow> = curated + .rows + .iter() + .filter(|r| r.kind.as_ref() == EVENT_KIND_EARNINGS && r.payload_json.contains("2024-04-15")) + .collect(); + assert_eq!(d_earn_rows.len(), 2); + assert_eq!(d_earn_rows[0].listing_id, d_earn_rows[1].listing_id); + assert_eq!(d_earn_rows[0].ts_micros, d_earn_rows[1].ts_micros); + assert_eq!(d_earn_rows[0].known_at_micros, d_earn_rows[1].known_at_micros); + assert_eq!(d_earn_rows[0].kind, d_earn_rows[1].kind); + assert_eq!(d_earn_rows[0].subtype, d_earn_rows[1].subtype); + assert_eq!(d_earn_rows[0].payload_json, d_earn_rows[1].payload_json); + assert_eq!(d_earn_rows[0].known_at_source.as_ref(), KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(d_earn_rows[1].known_at_source.as_ref(), KNOWN_AT_SOURCE_STATUTORY_LAG); + + // Must be accepted cleanly by write_events_dataset without UnsortedInput or DuplicateRow. + let tmp = TempDirGuard::new("collapse-write"); + let write_stats = + write_events_dataset(tmp.path(), &curated.rows, EventsWriteOptions::default()).unwrap(); + assert_eq!(write_stats.rows_written, 8); +} + +#[test] +fn failure_modes_empty_inputs_and_out_dir_protection() { + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "QM_A", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + + // 1. Blank and whitespace-only mapping_source return EmptyMappingSource. + for blank in ["", " ", "\t\n"] { + let err = curate_events( + [filing("QM_A", "2024-05-01T10:00:00 EDT", "10-Q", None, None)], + std::iter::empty::>(), + blank, + &mapping, + ) + .unwrap_err(); + assert_eq!(err, CurateEventsError::EmptyMappingSource); + assert!(err.source().is_none()); + assert!(err.to_string().contains("mapping_source")); + } + + // 2. Empty inputs return empty rows, zero stats, and create no events/ directory. + let empty = curate_events( + std::iter::empty::>(), + std::iter::empty::>(), + "qm", + &mapping, + ) + .unwrap(); + assert_conservation_and_order(&empty); + assert!(empty.rows.is_empty()); + assert_eq!(empty.stats, CurateEventsStats::default()); + + let fresh_tmp = TempDirGuard::new("empty-and-err"); + let empty_report = curate_and_write_events( + fresh_tmp.path(), + std::iter::empty::>(), + std::iter::empty::>(), + "qm", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_report.curate_stats, CurateEventsStats::default()); + assert_eq!(empty_report.write_stats, EventsWriteStats::default()); + assert!(!fresh_tmp.path().join("events").exists()); + + // 3. Curate error on fresh dir creates no events/ directory. + let err = curate_and_write_events( + fresh_tmp.path(), + [filing("QM_A", "2024-05-01T10:00:00 EDT", "10-Q", None, None)], + std::iter::empty::>(), + " ", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err, + CurateEventsWriteError::Curate(CurateEventsError::EmptyMappingSource) + )); + assert!(err.source().is_some()); + assert!(err.to_string().contains("curation failed")); + assert!(!fresh_tmp.path().join("events").exists()); + + // 4. Curate error on pre-existing out_dir leaves live part.parquet byte-identical. + let existing_tmp = TempDirGuard::new("preexisting-protect"); + curate_and_write_events( + existing_tmp.path(), + [filing("QM_A", "2024-05-01T10:00:00 EDT", "10-Q", Some("F1"), None)], + std::iter::empty::>(), + "qm", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap(); + let part_path = existing_tmp.path().join("events/year=2024/part.parquet"); + let before_bytes = fs::read(&part_path).expect("read live part.parquet"); + + let err_existing = curate_and_write_events( + existing_tmp.path(), + [filing("QM_A", "2024-05-02T10:00:00 EDT", "10-K", Some("F2"), None)], + std::iter::empty::>(), + "", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err_existing, + CurateEventsWriteError::Curate(CurateEventsError::EmptyMappingSource) + )); + assert_eq!(fs::read(&part_path).unwrap(), before_bytes); + + // 5. Invalid EventsWriteOptions surfaces as CurateEventsWriteError::Parquet. + let pq_err = curate_and_write_events( + fresh_tmp.path(), + std::iter::empty::>(), + std::iter::empty::>(), + "qm", + &mapping, + EventsWriteOptions { + row_group_rows: 0, + ..EventsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!( + pq_err, + CurateEventsWriteError::Parquet(ParquetEventsError::InvalidRowGroupRows) + )); + assert!(pq_err.source().is_some()); + assert!(pq_err.to_string().contains("Parquet write failed")); +} + +#[test] +fn permutation_invariance_including_contrived_mismatched_zone_duplicates() { + struct SplitMix64(u64); + impl SplitMix64 { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + } + + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "K1", day(2000, 1, 1), Some(day(2024, 6, 1)), 10), + map_row("qm", "K1", day(2024, 6, 2), None, 20), + map_row("qm", "K2", day(2000, 1, 1), None, 10), + map_row("qm", "K3", day(2020, 1, 1), Some(day(2023, 12, 31)), 30), + ]) + .unwrap(); + + // Include contrived mismatched-zone duplicate filings on K1 that resolve to the exact same + // UTC instant (2024-06-02T04:30:00Z) but have different ET dates (2024-06-01 vs 2024-06-02), + // straddling K1's listing switch. `event_date_tiebreak()` ensures both permutations collapse + // deterministically to the same event_date (2024-06-01 -> listing 10). + let filings = vec![ + filing("K1", "2024-06-02T00:30:00 EDT", "8-K", Some("MISMATCH"), None), + filing("K1", "2024-06-01T23:30:00 EST", "8-K", Some("MISMATCH"), None), + filing("K1", "2003-04-10T11:00:00 EDT", "10-K", Some("OLD-K1"), None), + filing("K2", "2024-06-01T23:30:00 EST", "8-K", Some("MISMATCH"), None), + filing("K2", "2024-07-01T16:00:00 EDT", "10-Q", Some("K2-Q2"), None), + filing("K3", "2023-12-31T22:00:00 EST", "News release", Some("K3-NR"), None), + filing("K3", "2024-01-02T09:00:00 EST", "10-K", Some("K3-POST"), None), // unmapped + filing("GHOST", "2024-05-01T12:00:00 EDT", "8-K", Some("G1"), None), // unmapped + filing("K1", "bad-ts", "8-K", None, None), // builder skip + ]; + + let earnings = vec![ + earning("K1", day(2024, 6, 1), "AMC", Some(day(2024, 3, 31)), Some(1.1), Some(50.0)), + earning("K2", day(2024, 6, 1), "AMC", Some(day(2024, 3, 31)), Some(1.1), Some(50.0)), + earning("K3", day(2023, 12, 31), "N/A", None, Some(0.5), None), + earning("K3", day(2024, 5, 1), "BTO", None, Some(0.6), None), // unmapped + ]; + + let baseline = curate_events(filings.clone(), earnings.clone(), "qm", &mapping).unwrap(); + assert_conservation_and_order(&baseline); + assert!(baseline.stats.dropped_unmapped > 0); + assert!(baseline.stats.listing_duplicate_collapsed > 0); + assert!(baseline.stats.builder.filings_duplicate_collapsed > 0); + + // Reversed order + let mut rev_f = filings.clone(); + let mut rev_e = earnings.clone(); + rev_f.reverse(); + rev_e.reverse(); + let rev_out = curate_events(rev_f, rev_e, "qm", &mapping).unwrap(); + assert_eq!(rev_out, baseline); + + // Multiple fixed-seed Fisher-Yates shuffles + for seed in [0x1111_2222_3333_4444u64, 0xAAAA_BBBB_CCCC_DDDDu64, 0x570C_4B07_E7E4_7511u64] { + let mut shuf_f = filings.clone(); + let mut shuf_e = earnings.clone(); + let mut rng = SplitMix64(seed); + for i in (1..shuf_f.len()).rev() { + let j = (rng.next_u64() as usize) % (i + 1); + shuf_f.swap(i, j); + } + for i in (1..shuf_e.len()).rev() { + let j = (rng.next_u64() as usize) % (i + 1); + shuf_e.swap(i, j); + } + let shuf_out = curate_events(shuf_f, shuf_e, "qm", &mapping).unwrap(); + assert_eq!(shuf_out, baseline); + } +} diff --git a/tools/curate-etl/src/curate_fx.rs b/tools/curate-etl/src/curate_fx.rs new file mode 100644 index 00000000..eb51852a --- /dev/null +++ b/tools/curate-etl/src/curate_fx.rs @@ -0,0 +1,195 @@ +//! Pure, in-memory `fx_1d` curation stage joining [`crate::fx::build_fx_1d`] and +//! [`crate::parquet_fx::write_fx_1d_dataset`] into contract [`Fx1dParquetRow`]s. +//! +//! # Contract & Point-in-Time Rules +//! - Calls [`build_fx_1d`] unchanged: EODHD `CAD.FOREX` takes precedence on overlapping dates, +//! TradingEconomics `teMarketData.USDCAD` fills interior gaps and the post-EOD tail, the +//! read-only 1% overlap cross-check runs untouched, and all [`Fx1dStats`] counters are carried +//! through unchanged. +//! - Maps every [`crate::fx::Fx1dRow`] to [`Fx1dParquetRow`] via [`Fx1dParquetRow::from_fx_row`] +//! with zero per-row heap allocation (`pair` and `source` stay `Cow::Borrowed`), preserving the +//! strictly ascending, unique `session_date` order emitted by [`build_fx_1d`]. +//! - **Conservative no-look-ahead timestamp rule:** stamps every row with +//! `ts_micros = known_at_micros = (session_date + 1) * FX_1D_MICROS_PER_DAY - 1` +//! (i.e. `23:59:59.999999 UTC` of `session_date`, offset +//! [`FX_1D_TS_OFFSET_MICROS_FROM_DAY_START`] from UTC midnight). Neither `CAD.FOREX` nor +//! `teMarketData.USDCAD` documents its daily FX cutoff, so the last microsecond of the UTC day +//! is the conservative no-look-ahead boundary: +//! - Same-day `16:00 ET` equity close signals resolve to the prior UTC day's FX bar rather than +//! peeking at an undocumented same-day cutoff. +//! - Every timestamp lies strictly inside the UTC day `[day_start, day_end)` and has +//! `known_at >= ts`, satisfying `parquet_fx`'s `TsOutsideSessionDate` and `KnownAtBeforeTs` +//! invariants. +//! - Requires no DST table for `1971–1975` (which lies outside `session_close.rs`'s +//! `1976–2030` range). +//! - Uses checked `i64` arithmetic via [`fx_1d_utc_day_end_micros`]; any `session_date` whose +//! UTC day-end microsecond timestamp overflows `i64` returns +//! [`CurateFxError::SessionDateOutOfRange`] without panicking or wrapping. +//! - Accounting invariant on [`CurateFx1dStats`]: `rows_in == builder.rows_out == rows_out`. + +use std::error::Error; +use std::fmt; +use std::path::Path; + +use crate::fx::{build_fx_1d, Fx1dStats, FxDailyBar}; +use crate::parquet_fx::{ + write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, ParquetFxError, +}; + +/// Number of microseconds in one UTC calendar day (`86_400 * 1_000_000`). +pub const FX_1D_MICROS_PER_DAY: i64 = 86_400_000_000; + +/// Offset in microseconds from `00:00:00.000000 UTC` to `23:59:59.999999 UTC` +/// (`FX_1D_MICROS_PER_DAY - 1`), used as both `ts` and `known_at` for curated `fx_1d` rows. +pub const FX_1D_TS_OFFSET_MICROS_FROM_DAY_START: i64 = FX_1D_MICROS_PER_DAY - 1; + +/// Accounting summary produced alongside [`CurateFx1dOutput::rows`]. +/// +/// Conservation invariant: +/// - `rows_in == builder.rows_out == rows_out` +/// - `builder` independently satisfies all [`Fx1dStats`] conservation invariants. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct CurateFx1dStats { + pub builder: Fx1dStats, + pub rows_in: usize, + pub rows_out: usize, +} + +/// Output of [`curate_fx_1d`]: contract Parquet rows sorted and unique by `session_date` +/// and full stage + builder stats. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateFx1dOutput { + pub rows: Vec, + pub stats: CurateFx1dStats, +} + +/// Typed errors returned by [`curate_fx_1d`] and [`fx_1d_utc_day_end_micros`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CurateFxError { + /// `session_date` cannot be represented as a UTC day-end `i64` microsecond timestamp + /// (`(session_date + 1) * 86_400_000_000 - 1` overflows `i64`). + SessionDateOutOfRange { session_date: i32 }, +} + +impl fmt::Display for CurateFxError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::SessionDateOutOfRange { session_date } => write!( + f, + "fx_1d session_date {session_date} overflows i64 UTC microsecond timestamp" + ), + } + } +} + +impl Error for CurateFxError {} + +/// Combined stats returned by [`curate_and_write_fx_1d`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateFx1dWriteReport { + pub curate_stats: CurateFx1dStats, + pub write_stats: Fx1dWriteStats, +} + +/// Typed error returned by [`curate_and_write_fx_1d`]. +#[derive(Debug)] +pub enum CurateFxWriteError { + Curate(CurateFxError), + Parquet(ParquetFxError), +} + +impl fmt::Display for CurateFxWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => write!(f, "fx_1d curation failed: {err}"), + Self::Parquet(err) => write!(f, "fx_1d Parquet write failed: {err}"), + } + } +} + +impl Error for CurateFxWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CurateFxWriteError { + fn from(err: CurateFxError) -> Self { + Self::Curate(err) + } +} + +impl From for CurateFxWriteError { + fn from(err: ParquetFxError) -> Self { + Self::Parquet(err) + } +} + +/// Computes `23:59:59.999999 UTC` of `session_date` (days since `1970-01-01`) in UTC microseconds +/// using checked `i64` arithmetic. +/// +/// Formula: `(session_date + 1) * FX_1D_MICROS_PER_DAY - (FX_1D_MICROS_PER_DAY - FX_1D_TS_OFFSET_MICROS_FROM_DAY_START)`. +#[inline] +pub fn fx_1d_utc_day_end_micros(session_date: i32) -> Result { + let sub_from_next_day = FX_1D_MICROS_PER_DAY - FX_1D_TS_OFFSET_MICROS_FROM_DAY_START; + i64::from(session_date) + .checked_add(1) + .and_then(|next_day| next_day.checked_mul(FX_1D_MICROS_PER_DAY)) + .and_then(|next_day_start| next_day_start.checked_sub(sub_from_next_day)) + .ok_or(CurateFxError::SessionDateOutOfRange { session_date }) +} + +/// Pure `fx_1d` curation stage: merges `CAD.FOREX` (`eod`) and `teMarketData.USDCAD` (`te`) via +/// [`build_fx_1d`] and stamps each row with conservative `23:59:59.999999 UTC` `ts`/`known_at` +/// timestamps via [`fx_1d_utc_day_end_micros`] into contract [`Fx1dParquetRow`]s. +/// +/// Output rows preserve the strictly ascending, unique `session_date` order emitted by +/// [`build_fx_1d`], with `pair` and `source` kept as `Cow::Borrowed` (zero per-row heap +/// allocation). +pub fn curate_fx_1d( + eod: &[FxDailyBar], + te: &[FxDailyBar], +) -> Result { + let built = build_fx_1d(eod, te); + let rows_in = built.rows.len(); + let mut rows = Vec::with_capacity(rows_in); + + for row in &built.rows { + let ts_micros = fx_1d_utc_day_end_micros(row.session_date)?; + rows.push(Fx1dParquetRow::from_fx_row(row, ts_micros, ts_micros)); + } + + let stats = CurateFx1dStats { + builder: built.stats, + rows_in, + rows_out: rows.len(), + }; + + Ok(CurateFx1dOutput { rows, stats }) +} + +/// Thin end-to-end wrapper running [`curate_fx_1d`] and publishing the resulting contract rows +/// via [`write_fx_1d_dataset`] to `/fx_1d/part.parquet`. +/// +/// Any [`CurateFxError`] returns before [`write_fx_1d_dataset`] is invoked, leaving `out_dir` +/// untouched. +pub fn curate_and_write_fx_1d>( + out_dir: P, + eod: &[FxDailyBar], + te: &[FxDailyBar], + options: Fx1dWriteOptions, +) -> Result { + let curated = curate_fx_1d(eod, te)?; + let write_stats = write_fx_1d_dataset(out_dir, &curated.rows, options)?; + Ok(CurateFx1dWriteReport { + curate_stats: curated.stats, + write_stats, + }) +} + +#[cfg(test)] +#[path = "curate_fx_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_fx_tests.rs b/tools/curate-etl/src/curate_fx_tests.rs new file mode 100644 index 00000000..f42e24f8 --- /dev/null +++ b/tools/curate-etl/src/curate_fx_tests.rs @@ -0,0 +1,699 @@ +use std::borrow::Cow; +use std::error::Error; +use std::fs::{self, File}; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::fx::{build_fx_1d, FxSource, FX_PAIR_USDCAD}; +use crate::parquet_fx::fx_1d_parquet_schema; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!("curate-etl-curate-fx-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn bar(session_date: i32, open: f64, high: f64, low: f64, close: f64) -> FxDailyBar { + FxDailyBar { + session_date, + open, + high, + low, + close, + } +} + +fn flat(session_date: i32, rate: f64) -> FxDailyBar { + bar(session_date, rate, rate, rate, rate) +} + +fn assert_utc_day_end_invariants(row: &Fx1dParquetRow) { + let expected_ts = + (i128::from(row.session_date) + 1) * i128::from(FX_1D_MICROS_PER_DAY) - 1; + let day_start = i128::from(row.session_date) * i128::from(FX_1D_MICROS_PER_DAY); + let day_end = day_start + i128::from(FX_1D_MICROS_PER_DAY); + let ts = i128::from(row.ts_micros); + + assert_eq!(ts, expected_ts, "ts must equal UTC day-end microsecond"); + assert_eq!(row.known_at_micros, row.ts_micros, "known_at must equal ts"); + assert!( + ts >= day_start && ts < day_end, + "ts {ts} must lie inside UTC day [{day_start}, {day_end}) for session_date {}", + row.session_date + ); +} + +fn assert_stage_invariants(out: &CurateFx1dOutput) { + let s = &out.stats; + assert_eq!(s.rows_in, s.builder.rows_out); + assert_eq!(s.rows_out, s.rows_in); + assert_eq!(s.rows_out, out.rows.len()); + + for row in &out.rows { + assert_eq!(row.pair.as_ref(), FX_PAIR_USDCAD); + assert!(matches!(row.pair, Cow::Borrowed(_)), "pair must stay borrowed"); + assert!( + matches!(row.source, Cow::Borrowed(_)), + "source must stay borrowed" + ); + assert!( + row.source.as_ref() == FxSource::EodCadForex.as_str() + || row.source.as_ref() == FxSource::TeUsdCad.as_str() + ); + assert_utc_day_end_invariants(row); + } + + for pair in out.rows.windows(2) { + assert!( + pair[0].session_date < pair[1].session_date, + "rows must be strictly ascending and unique by session_date: {} >= {}", + pair[0].session_date, + pair[1].session_date + ); + } +} + +fn assert_row_bitwise_eq(actual: &Fx1dParquetRow, expected: &Fx1dParquetRow) { + assert_eq!(actual.pair.as_ref(), expected.pair.as_ref()); + assert_eq!(actual.session_date, expected.session_date); + assert_eq!(actual.ts_micros, expected.ts_micros); + assert_eq!(actual.open.to_bits(), expected.open.to_bits()); + assert_eq!(actual.high.to_bits(), expected.high.to_bits()); + assert_eq!(actual.low.to_bits(), expected.low.to_bits()); + assert_eq!(actual.close.to_bits(), expected.close.to_bits()); + assert_eq!(actual.source.as_ref(), expected.source.as_ref()); + assert_eq!(actual.known_at_micros, expected.known_at_micros); +} + +fn read_parquet_fx(path: &Path) -> (usize, Vec) { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let expected_schema = fx_1d_parquet_schema().expect("contract schema"); + assert_eq!( + metadata.file_metadata().schema_descr().root_schema_ptr(), + expected_schema, + "written Parquet schema must equal fx_1d_parquet_schema()" + ); + assert_eq!(metadata.file_metadata().schema_descr().num_columns(), 9); + + let footer_rows = metadata.file_metadata().num_rows() as usize; + let mut out = Vec::with_capacity(footer_rows); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let pair = read_str_col(rg_reader.get_column_reader(0).unwrap(), num_rows); + let session_date = read_i32_col(rg_reader.get_column_reader(1).unwrap(), num_rows); + let ts_micros = read_i64_col(rg_reader.get_column_reader(2).unwrap(), num_rows); + let open = read_f64_col(rg_reader.get_column_reader(3).unwrap(), num_rows); + let high = read_f64_col(rg_reader.get_column_reader(4).unwrap(), num_rows); + let low = read_f64_col(rg_reader.get_column_reader(5).unwrap(), num_rows); + let close = read_f64_col(rg_reader.get_column_reader(6).unwrap(), num_rows); + let source = read_str_col(rg_reader.get_column_reader(7).unwrap(), num_rows); + let known_at_micros = read_i64_col(rg_reader.get_column_reader(8).unwrap(), num_rows); + + for i in 0..num_rows { + out.push(Fx1dParquetRow { + pair: Cow::Owned(pair[i].clone()), + session_date: session_date[i], + ts_micros: ts_micros[i], + open: open[i], + high: high[i], + low: low[i], + close: close[i], + source: Cow::Owned(source[i].clone()), + known_at_micros: known_at_micros[i], + }); + } + } + + (footer_rows, out) +} + +fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int32ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int32ColumnReader"), + } + values +} + +fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int64ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int64ColumnReader"), + } + values +} + +fn read_f64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + values +} + +fn read_str_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected ByteArrayColumnReader"), + } + values + .into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8")) + .collect() +} + +#[test] +fn happy_path_eod_only_te_only_and_merged_overlap_gap_and_tail() { + let d1 = day(2025, 1, 2); + let d2 = day(2025, 1, 3); + let d3 = day(2025, 1, 6); + let d4 = day(2026, 4, 30); + + let eod = [ + bar(d1, 1.4301, 1.4402, 1.4253, 1.4354), + // d2 missing in EOD (interior gap) + bar(d3, 1.4365, 1.4436, 1.4307, 1.4388), + ]; + let te = [ + bar(d1, 1.4311, 1.4412, 1.4263, 1.4364), // overlaps d1 -> EOD wins + bar(d2, 1.4341, 1.4392, 1.4313, 1.4374), // fills interior gap + bar(d4, 1.3801, 1.3902, 1.3753, 1.3854), // fills post-EOD tail + ]; + + // EOD-only + let eod_only = curate_fx_1d(&eod, &[]).unwrap(); + assert_stage_invariants(&eod_only); + assert_eq!(eod_only.rows.len(), 2); + assert!(eod_only.rows.iter().all(|r| r.source.as_ref() == "eod_cad_forex")); + + // TE-only + let te_only = curate_fx_1d(&[], &te).unwrap(); + assert_stage_invariants(&te_only); + assert_eq!(te_only.rows.len(), 3); + assert!(te_only.rows.iter().all(|r| r.source.as_ref() == "te_usdcad")); + + // Merged: EOD wins overlap, TE fills interior gap + tail + let merged = curate_fx_1d(&eod, &te).unwrap(); + assert_stage_invariants(&merged); + assert_eq!(merged.rows.len(), 4); + assert_eq!(merged.stats.builder.eod_rows_out, 2); + assert_eq!(merged.stats.builder.te_rows_out, 2); + assert_eq!(merged.stats.builder.te_superseded_by_eod, 1); + + // d1: EOD wins with bit-exact OHLC + assert_eq!(merged.rows[0].session_date, d1); + assert_eq!(merged.rows[0].source.as_ref(), "eod_cad_forex"); + assert_eq!(merged.rows[0].open.to_bits(), eod[0].open.to_bits()); + assert_eq!(merged.rows[0].high.to_bits(), eod[0].high.to_bits()); + assert_eq!(merged.rows[0].low.to_bits(), eod[0].low.to_bits()); + assert_eq!(merged.rows[0].close.to_bits(), eod[0].close.to_bits()); + + // d2: TE interior gap fill + assert_eq!(merged.rows[1].session_date, d2); + assert_eq!(merged.rows[1].source.as_ref(), "te_usdcad"); + assert_eq!(merged.rows[1].open.to_bits(), te[1].open.to_bits()); + assert_eq!(merged.rows[1].high.to_bits(), te[1].high.to_bits()); + assert_eq!(merged.rows[1].low.to_bits(), te[1].low.to_bits()); + assert_eq!(merged.rows[1].close.to_bits(), te[1].close.to_bits()); + + // d3: EOD only + assert_eq!(merged.rows[2].session_date, d3); + assert_eq!(merged.rows[2].source.as_ref(), "eod_cad_forex"); + assert_eq!(merged.rows[2].close.to_bits(), eod[1].close.to_bits()); + + // d4: TE tail fill + assert_eq!(merged.rows[3].session_date, d4); + assert_eq!(merged.rows[3].source.as_ref(), "te_usdcad"); + assert_eq!(merged.rows[3].close.to_bits(), te[2].close.to_bits()); +} + +#[test] +fn timestamps_match_exact_utc_day_end_for_epoch_1971_pre1970_and_2026() { + let d_1969_01_01 = day(1969, 1, 1); + let d_1969_12_31 = day(1969, 12, 31); + let d_1970_01_01 = day(1970, 1, 1); + let d_1971_01_04 = day(1971, 1, 4); + let d_2026_04_30 = day(2026, 4, 30); + + assert_eq!(d_1969_01_01, -365); + assert_eq!(d_1969_12_31, -1); + assert_eq!(d_1970_01_01, 0); + assert_eq!(d_1971_01_04, 368); + assert_eq!(d_2026_04_30, 20_573); + + let expected = [ + (d_1969_01_01, -31_449_600_000_001_i64), + (d_1969_12_31, -1_i64), + (d_1970_01_01, 86_399_999_999_i64), + (d_1971_01_04, 31_881_599_999_999_i64), + (d_2026_04_30, 1_777_593_599_999_999_i64), + ]; + + let eod: Vec = expected.iter().map(|&(d, _)| flat(d, 1.35)).collect(); + let curated = curate_fx_1d(&eod, &[]).unwrap(); + assert_stage_invariants(&curated); + assert_eq!(curated.rows.len(), expected.len()); + + for (row, &(date, expected_ts)) in curated.rows.iter().zip(expected.iter()) { + assert_eq!(row.session_date, date); + assert_eq!(row.ts_micros, expected_ts); + assert_eq!(row.known_at_micros, expected_ts); + assert_eq!(fx_1d_utc_day_end_micros(date).unwrap(), expected_ts); + } +} + +#[test] +fn stats_invariant_and_builder_stats_match_direct_build_fx_1d_bit_for_bit() { + let base = day(2024, 6, 3); + let eod = [ + // Invalid OHLC + bar(base, f64::NAN, 1.37, 1.35, 1.36), + bar(base + 1, 1.36, 1.37, 0.0, 1.36), + // Inconsistent OHLC + bar(base + 2, 1.36, 1.34, 1.35, 1.36), + // Identical duplicate (collapses) + flat(base + 3, 1.365), + flat(base + 3, 1.365), + // Conflicting duplicate (drops group; TE fills) + flat(base + 4, 1.370), + flat(base + 4, 1.371), + // Clean overlap within 1% + bar(base + 5, 1.360, 1.370, 1.355, 1.362), + // Clean overlap > 1% mismatch (read-only audit) + bar(base + 6, 1.360, 1.370, 1.355, 1.360), + ]; + let te = [ + // Invalid + inconsistent in TE + bar(base, -1.0, 1.37, 1.35, 1.36), + bar(base + 1, 1.36, 1.37, 1.35, 1.38), + // Fills base + 4 where EOD had conflict + flat(base + 4, 1.3705), + // Overlap within tolerance + bar(base + 5, 1.361, 1.371, 1.356, 1.363), + // Overlap mismatched (>1%) + bar(base + 6, 1.390, 1.400, 1.385, 1.395), + // Duplicate collapsed in TE tail + flat(base + 7, 1.380), + flat(base + 7, 1.380), + // Conflicting duplicate in TE tail + flat(base + 8, 1.385), + flat(base + 8, 1.386), + ]; + + let direct = build_fx_1d(&eod, &te); + let curated = curate_fx_1d(&eod, &te).unwrap(); + assert_stage_invariants(&curated); + + assert_eq!(curated.stats.rows_in, curated.stats.builder.rows_out); + assert_eq!(curated.stats.rows_out, curated.stats.builder.rows_out); + assert_eq!(curated.stats.builder, direct.stats); + assert_eq!( + curated.stats.builder.max_overlap_rel.to_bits(), + direct.stats.max_overlap_rel.to_bits() + ); + assert!(curated.stats.builder.eod.dropped_invalid_ohlc > 0); + assert!(curated.stats.builder.eod.dropped_inconsistent_ohlc > 0); + assert!(curated.stats.builder.eod.duplicate_collapsed > 0); + assert!(curated.stats.builder.eod.duplicate_conflict_dropped > 0); + assert!(curated.stats.builder.te.dropped_invalid_ohlc > 0); + assert!(curated.stats.builder.te.dropped_inconsistent_ohlc > 0); + assert!(curated.stats.builder.te.duplicate_collapsed > 0); + assert!(curated.stats.builder.te.duplicate_conflict_dropped > 0); + assert_eq!(curated.stats.builder.overlap_within_tolerance, 1); + assert_eq!(curated.stats.builder.overlap_mismatched, 1); +} + +#[test] +fn permutation_invariance_and_temporal_prefix_stability() { + let base = day(2025, 3, 3); + let eod = vec![ + bar(base, 1.441, 1.448, 1.439, 1.445), + bar(base + 2, 1.446, 1.451, 1.442, 1.449), + bar(base + 3, 1.449, 1.455, 1.444, 1.450), + ]; + let te = vec![ + bar(base, 1.442, 1.449, 1.440, 1.446), + bar(base + 1, 1.444, 1.450, 1.441, 1.447), + bar(base + 4, 1.450, 1.458, 1.447, 1.453), + ]; + + let baseline = curate_fx_1d(&eod, &te).unwrap(); + assert_stage_invariants(&baseline); + + let mut eod_rev = eod.clone(); + let mut te_rev = te.clone(); + eod_rev.reverse(); + te_rev.reverse(); + let permuted = curate_fx_1d(&eod_rev, &te_rev).unwrap(); + assert_eq!(permuted.stats, baseline.stats); + assert_eq!(permuted.rows.len(), baseline.rows.len()); + for (a, b) in permuted.rows.iter().zip(baseline.rows.iter()) { + assert_row_bitwise_eq(a, b); + } + + // Temporal prefix stability: appending future TE tail rows leaves earlier rows bit-identical. + let mut te_extended = te; + te_extended.push(bar(base + 10, 1.420, 1.430, 1.415, 1.425)); + te_extended.push(bar(base + 11, 1.425, 1.432, 1.420, 1.428)); + let extended = curate_fx_1d(&eod, &te_extended).unwrap(); + assert_stage_invariants(&extended); + assert_eq!(extended.rows.len(), baseline.rows.len() + 2); + for (a, b) in extended.rows[..baseline.rows.len()] + .iter() + .zip(baseline.rows.iter()) + { + assert_row_bitwise_eq(a, b); + } +} + +#[test] +fn empty_inputs_return_zero_rows_and_create_no_output_dir() { + let curated = curate_fx_1d(&[], &[]).unwrap(); + assert_stage_invariants(&curated); + assert!(curated.rows.is_empty()); + assert_eq!(curated.stats, CurateFx1dStats::default()); + + let tmp = TempDirGuard::new("empty"); + let report = curate_and_write_fx_1d(tmp.path(), &[], &[], Fx1dWriteOptions::default()).unwrap(); + assert_eq!(report.curate_stats, CurateFx1dStats::default()); + assert_eq!(report.write_stats, Fx1dWriteStats::default()); + assert!( + !tmp.path().join("fx_1d").exists(), + "empty input must not create fx_1d directory" + ); +} + +#[test] +fn session_date_overflow_boundaries_return_typed_error_and_leave_disk_untouched() { + // Tight valid boundaries succeed and satisfy UTC-day containment. + for valid_date in [106_751_990_i32, -106_751_992_i32] { + let curated = curate_fx_1d(&[flat(valid_date, 1.35)], &[]).unwrap(); + assert_stage_invariants(&curated); + assert_eq!(curated.rows.len(), 1); + } + + // Extreme and tight overflow boundaries fail cleanly without panicking. + for bad_date in [i32::MAX, i32::MIN, 106_751_991_i32, -106_751_993_i32] { + let err = curate_fx_1d(&[flat(bad_date, 1.35)], &[]).unwrap_err(); + assert_eq!( + err, + CurateFxError::SessionDateOutOfRange { + session_date: bad_date + } + ); + assert!(err.source().is_none()); + assert!(err.to_string().contains(&bad_date.to_string())); + + // Fresh directory: neither fx_1d/part.parquet nor staging files created. + let fresh = TempDirGuard::new("overflow-fresh"); + let write_err = curate_and_write_fx_1d( + fresh.path(), + &[flat(bad_date, 1.35)], + &[], + Fx1dWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + write_err, + CurateFxWriteError::Curate(CurateFxError::SessionDateOutOfRange { session_date }) + if session_date == bad_date + )); + assert!(write_err.source().is_some()); + assert!(write_err.to_string().contains("fx_1d curation failed")); + assert!(!fresh.path().join("fx_1d").exists()); + } + + // Pre-existing fx_1d/part.parquet remains byte-identical on curate error. + let tmp = TempDirGuard::new("overflow-preserve"); + let valid = [bar(day(2025, 1, 2), 1.430, 1.440, 1.425, 1.435)]; + curate_and_write_fx_1d(tmp.path(), &valid, &[], Fx1dWriteOptions::default()).unwrap(); + let part_path = tmp.path().join("fx_1d/part.parquet"); + let original_bytes = fs::read(&part_path).expect("read original part.parquet"); + + let write_err = curate_and_write_fx_1d( + tmp.path(), + &[flat(i32::MAX, 1.35)], + &[], + Fx1dWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + write_err, + CurateFxWriteError::Curate(CurateFxError::SessionDateOutOfRange { + session_date: i32::MAX + }) + )); + assert_eq!(fs::read(&part_path).unwrap(), original_bytes); +} + +#[test] +fn curate_and_write_fx_1d_round_trips_schema_bits_and_atomic_rerun() { + let tmp = TempDirGuard::new("round-trip"); + let eod = [ + bar(day(1971, 1, 4), 1.0101, 1.0152, 1.0083, 1.0124), + bar(day(2025, 1, 2), 1.4301, 1.4402, 1.4253, 1.4354), + bar(day(2025, 1, 6), 1.4365, 1.4436, 1.4307, 1.4388), + ]; + let te = [ + bar(day(2025, 1, 2), 1.4311, 1.4412, 1.4263, 1.4364), + bar(day(2025, 1, 3), 1.4341, 1.4392, 1.4313, 1.4374), + bar(day(2026, 4, 30), 1.3801, 1.3902, 1.3753, 1.3854), + ]; + + let curated = curate_fx_1d(&eod, &te).unwrap(); + let report1 = + curate_and_write_fx_1d(tmp.path(), &eod, &te, Fx1dWriteOptions::default()).unwrap(); + + assert_eq!(report1.curate_stats, curated.stats); + assert_eq!(report1.write_stats.rows_written, report1.curate_stats.rows_out); + assert_eq!(report1.write_stats.files_written, 1); + assert!(report1.write_stats.bytes_written > 0); + + let fx_dir = tmp.path().join("fx_1d"); + let part_path = fx_dir.join("part.parquet"); + assert!(part_path.exists()); + + // No transient .tmp, .bak, or .write.lock files remain. + for entry in fs::read_dir(&fx_dir).expect("read fx_1d dir") { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!(name, "part.parquet", "unexpected transient file '{name}'"); + } + + let (footer_rows, read_back) = read_parquet_fx(&part_path); + assert_eq!(footer_rows, curated.rows.len()); + assert_eq!(read_back.len(), curated.rows.len()); + for (actual, expected) in read_back.iter().zip(curated.rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + + // Second identical run atomically replaces and yields byte-identical output. + let bytes1 = fs::read(&part_path).expect("read first part.parquet"); + let report2 = + curate_and_write_fx_1d(tmp.path(), &eod, &te, Fx1dWriteOptions::default()).unwrap(); + assert_eq!(report2, report1); + let bytes2 = fs::read(&part_path).expect("read second part.parquet"); + assert_eq!(bytes2, bytes1, "rerun must produce byte-identical part.parquet"); + + for entry in fs::read_dir(&fx_dir).expect("read fx_1d dir after rerun") { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!(name, "part.parquet", "unexpected transient file '{name}'"); + } +} + +#[test] +fn writer_error_when_out_dir_is_regular_file_surfaces_as_parquet_error_with_source() { + let tmp = TempDirGuard::new("writer-err"); + let regular_file = tmp.path().join("not_a_dir"); + fs::write(®ular_file, b"occupying path").expect("write regular file"); + + let eod = [bar(day(2025, 1, 2), 1.430, 1.440, 1.425, 1.435)]; + let err = + curate_and_write_fx_1d(®ular_file, &eod, &[], Fx1dWriteOptions::default()).unwrap_err(); + assert!( + matches!(err, CurateFxWriteError::Parquet(ParquetFxError::Io { .. })), + "expected Parquet(Io) error, got {err:?}" + ); + assert!(err.source().is_some(), "Parquet write error must expose source()"); + assert!( + err.to_string().contains("fx_1d Parquet write failed"), + "unexpected Display: {err}" + ); +} + +#[test] +fn curate_and_write_fx_1d_atomic_replace_preserves_open_handle_on_changed_input() { + let tmp = TempDirGuard::new("atomic-replace"); + let eod_v1 = [ + bar(day(2025, 1, 2), 1.4301, 1.4402, 1.4253, 1.4354), + bar(day(2025, 1, 3), 1.4341, 1.4392, 1.4313, 1.4374), + ]; + let eod_v2 = [ + bar(day(2025, 1, 2), 1.4301, 1.4402, 1.4253, 1.4354), + bar(day(2025, 1, 3), 1.4341, 1.4392, 1.4313, 1.4374), + bar(day(2025, 1, 6), 1.4410, 1.4490, 1.4380, 1.4455), + ]; + + curate_and_write_fx_1d(tmp.path(), &eod_v1, &[], Fx1dWriteOptions::default()).unwrap(); + let fx_dir = tmp.path().join("fx_1d"); + let part_path = fx_dir.join("part.parquet"); + let original_bytes = fs::read(&part_path).expect("read v1 part.parquet"); + + // Hold an open handle to v1 while publishing changed input v2. + let mut old_handle = File::open(&part_path).expect("open handle to v1 part.parquet"); + + let expected_v2 = curate_fx_1d(&eod_v2, &[]).unwrap(); + let report_v2 = + curate_and_write_fx_1d(tmp.path(), &eod_v2, &[], Fx1dWriteOptions::default()).unwrap(); + assert_eq!(report_v2.write_stats.rows_written, expected_v2.rows.len()); + + // An atomic rename replaces the directory entry without mutating the unlinked v1 inode. + let mut old_handle_bytes = Vec::new(); + old_handle + .read_to_end(&mut old_handle_bytes) + .expect("read v1 bytes from open handle"); + assert_eq!( + old_handle_bytes, original_bytes, + "open handle to previous part.parquet must still read original bytes" + ); + + // Opening the path now resolves to the newly published v2 rows. + let (footer_rows, read_back_v2) = read_parquet_fx(&part_path); + assert_eq!(footer_rows, expected_v2.rows.len()); + assert_eq!(read_back_v2.len(), expected_v2.rows.len()); + for (actual, expected) in read_back_v2.iter().zip(expected_v2.rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + + for entry in fs::read_dir(&fx_dir).expect("read fx_1d dir after v2 publish") { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!(name, "part.parquet", "unexpected transient file '{name}'"); + } +} + +#[test] +fn overflowing_session_date_mixed_with_valid_rows_fails_whole_stage_without_writing() { + let tmp = TempDirGuard::new("mixed-overflow"); + let eod = [ + bar(day(2025, 1, 2), 1.430, 1.440, 1.425, 1.435), + flat(106_751_991, 1.35), + ]; + let te = [bar(day(2025, 1, 3), 1.434, 1.439, 1.431, 1.437)]; + + let err = + curate_and_write_fx_1d(tmp.path(), &eod, &te, Fx1dWriteOptions::default()).unwrap_err(); + assert!(matches!( + err, + CurateFxWriteError::Curate(CurateFxError::SessionDateOutOfRange { + session_date: 106_751_991 + }) + )); + assert!(!tmp.path().join("fx_1d").exists()); +} + +#[test] +fn invalid_bar_with_overflowing_session_date_is_dropped_by_builder_before_timestamping() { + let eod = [ + bar(day(2025, 1, 2), 1.430, 1.440, 1.425, 1.435), + bar(i32::MAX, 1.35, 1.36, 1.34, 0.0), + ]; + let out = curate_fx_1d(&eod, &[]).expect("invalid overflowing bar should be dropped"); + assert_stage_invariants(&out); + assert_eq!(out.stats.builder.eod.dropped_invalid_ohlc, 1); + assert_eq!(out.rows.len(), 1); + assert_eq!(out.rows[0].session_date, day(2025, 1, 2)); +} + +#[test] +fn fx_1d_utc_day_end_micros_matches_i128_reference_across_seeded_sweep() { + let mut state: u64 = 0x517c_c1b7_2722_0a95; + let mut next_u64 = || -> u64 { + state = state.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) + }; + + let boundaries = [ + i32::MIN, + -106_751_994, + -106_751_993, + -106_751_992, + -1, + 0, + 1, + 106_751_990, + 106_751_991, + 106_751_992, + i32::MAX, + ]; + + let mut dates = Vec::with_capacity(boundaries.len() + 10_000); + dates.extend_from_slice(&boundaries); + for _ in 0..10_000 { + dates.push(next_u64() as i32); + } + + for session_date in dates { + let wide = (i128::from(session_date) + 1) * i128::from(FX_1D_MICROS_PER_DAY) - 1; + let expected = i64::try_from(wide) + .map_err(|_| CurateFxError::SessionDateOutOfRange { session_date }); + assert_eq!( + fx_1d_utc_day_end_micros(session_date), + expected, + "mismatch for session_date={session_date}" + ); + } +} diff --git a/tools/curate-etl/src/curate_shorts.rs b/tools/curate-etl/src/curate_shorts.rs new file mode 100644 index 00000000..d34e858f --- /dev/null +++ b/tools/curate-etl/src/curate_shorts.rs @@ -0,0 +1,315 @@ +//! Pure, in-memory `shorts` curation stage joining [`crate::shorts::build_shorts`], +//! [`crate::provider_mapping::ProviderMappingTable`], and +//! [`crate::parquet_shorts::write_shorts_dataset`] into contract [`ShortsParquetRow`]s. +//! +//! # Contract & Point-in-Time Rules +//! - Calls [`build_shorts`] unchanged to validate `shares_short`, sanitize non-finite optional +//! fields, deduplicate same-`(key, report_date)` reports, apply the locked `+4` Canadian TSX +//! business-day CIRO lag, and stamp `known_at_utc_micros = 17:00:00 America/Toronto` plus +//! `source = SHORTS_SOURCE_CEO` (`"ceo_shorts"`). +//! - Resolves each output row's `(mapping_source, key, report_date)` to a permanent +//! `listing_id: i32` via [`ProviderMappingTable::cursor_for`] / [`ProviderMappingCursor::resolve`] +//! (one cursor per contiguous `key` run, since `build_shorts` emits rows sorted by +//! `(key, report_date)`). +//! - **Point-in-time mapping boundary (`report_date`, not `known_at_date`):** `provider_mapping` +//! is resolved strictly on `report_date` (the reporting period the short position describes), +//! not on `known_at_date` (when CIRO disseminates the report `+4` business days later). A ticker +//! that changes listing or delists between `report_date` and `known_at_date` still belongs to +//! the listing that was active on `report_date`. +//! - Carries `source` through unchanged from `build_shorts` (`SHORTS_SOURCE_CEO` = `"ceo_shorts"`) +//! as `Cow::Borrowed`. +//! - Re-sorts mapped rows in place by `(listing_id, report_date)` and compacts cross-`key` +//! collisions on the same `(listing_id, report_date)`: bitwise-identical +//! `(known_at_micros, shares_short, net_change, pct_float)` collapses to one row +//! (`listing_collision_collapsed`), while any conflict drops the entire group +//! (`listing_collision_dropped`), mirroring `build_shorts`'s duplicate policy. + +use std::borrow::Cow; +use std::error::Error; +use std::fmt; +use std::path::Path; + +use crate::parquet_shorts::{ + write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, + ShortsWriteStats, +}; +use crate::provider_mapping::ProviderMappingTable; +use crate::shorts::{build_shorts, CeoShortReport, ShortsError, ShortsStats}; + +/// Accounting summary produced alongside [`CurateShortsOutput::rows`]. +/// +/// Conservation invariants: +/// - `rows_in == builder.rows_out` +/// - `rows_in == rows_out + dropped_unmapped + listing_collision_collapsed + listing_collision_dropped` +/// - `builder` independently satisfies all [`ShortsStats`] conservation invariants. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateShortsStats { + pub builder: ShortsStats, + pub rows_in: usize, + pub rows_out: usize, + pub listings_out: usize, + pub dropped_unmapped: usize, + pub listing_collision_collapsed: usize, + pub listing_collision_dropped: usize, +} + +/// Output of [`curate_shorts`]: contract Parquet rows sorted and unique by +/// `(listing_id, report_date)` and full stage + builder stats. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateShortsOutput { + pub rows: Vec, + pub stats: CurateShortsStats, +} + +/// Typed caller errors returned by [`curate_shorts`]. +/// +/// Bad single rows (unmapped dates and cross-`key` collisions) are dropped and counted in +/// [`CurateShortsStats`] rather than aborting the stage. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CurateShortsError { + /// Error propagated from [`build_shorts`] (e.g., `report_date` outside `2008..=2030`). + Shorts(ShortsError), + /// Caller-supplied `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, +} + +impl fmt::Display for CurateShortsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::Shorts(err) => write!(f, "{err}"), + Self::EmptyMappingSource => { + write!(f, "mapping_source must not be empty or blank") + } + } + } +} + +impl Error for CurateShortsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Shorts(err) => Some(err), + Self::EmptyMappingSource => None, + } + } +} + +impl From for CurateShortsError { + fn from(err: ShortsError) -> Self { + Self::Shorts(err) + } +} + +/// Combined stats returned by [`curate_and_write_shorts`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CurateShortsWriteReport { + pub curate_stats: CurateShortsStats, + pub write_stats: ShortsWriteStats, +} + +/// Typed error returned by [`curate_and_write_shorts`]. +#[derive(Debug)] +pub enum CurateShortsWriteError { + Curate(CurateShortsError), + Parquet(ParquetShortsError), +} + +impl fmt::Display for CurateShortsWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => write!(f, "shorts curation failed: {err}"), + Self::Parquet(err) => write!(f, "shorts Parquet write failed: {err}"), + } + } +} + +impl Error for CurateShortsWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CurateShortsWriteError { + fn from(err: CurateShortsError) -> Self { + Self::Curate(err) + } +} + +impl From for CurateShortsWriteError { + fn from(err: ParquetShortsError) -> Self { + Self::Parquet(err) + } +} + +#[inline] +fn parquet_row_values_bit_eq(a: &ShortsParquetRow, b: &ShortsParquetRow) -> bool { + a.known_at_micros == b.known_at_micros + && a.shares_short.to_bits() == b.shares_short.to_bits() + && a.net_change.map(f64::to_bits) == b.net_change.map(f64::to_bits) + && a.pct_float.map(f64::to_bits) == b.pct_float.map(f64::to_bits) +} + +/// Pure `shorts` curation stage: validates, deduplicates, and point-in-time lags source-keyed +/// `ceoShorts` reports via [`build_shorts`], resolves `(mapping_source, key, report_date) -> +/// listing_id` through `provider_mapping`, and emits contract [`ShortsParquetRow`]s sorted and +/// unique by `(listing_id, report_date)`. +/// +/// Mapping lookup uses `report_date` (the reporting period the short position describes), not +/// `known_at_date`. Rows with no covering mapping range are dropped into `dropped_unmapped`. +/// +/// After re-sorting in place by `(listing_id, report_date)`, cross-`key` collisions on the same +/// `(listing_id, report_date)` collapse to one row when `known_at_micros`, `shares_short`, +/// `net_change`, and `pct_float` are bitwise identical (`listing_collision_collapsed += g - 1`) +/// and drop the entire group when any of those fields differ (`listing_collision_dropped += g`). +pub fn curate_shorts( + reports: I, + mapping_source: &str, + mapping: &ProviderMappingTable, +) -> Result +where + K: Ord + Clone + AsRef, + I: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CurateShortsError::EmptyMappingSource); + } + + let built = build_shorts(reports)?; + + let mut stats = CurateShortsStats { + builder: built.stats, + rows_in: built.rows.len(), + ..CurateShortsStats::default() + }; + + let mut rows: Vec = Vec::with_capacity(built.rows.len()); + let total_built = built.rows.len(); + let mut idx = 0usize; + + while idx < total_built { + let run_start = idx; + let run_key = &built.rows[run_start].key; + idx += 1; + while idx < total_built && built.rows[idx].key == *run_key { + idx += 1; + } + let run_end = idx; + + let mut cursor = mapping.cursor_for(mapping_source, run_key.as_ref()); + if cursor.ranges().is_empty() { + stats.dropped_unmapped += run_end - run_start; + continue; + } + + for row in &built.rows[run_start..run_end] { + let Some(listing_id) = cursor.resolve(row.report_date) else { + stats.dropped_unmapped += 1; + continue; + }; + + rows.push(ShortsParquetRow { + listing_id, + report_date: row.report_date, + known_at_micros: row.known_at_utc_micros, + shares_short: row.shares_short, + net_change: row.net_change, + pct_float: row.pct_float, + source: Cow::Borrowed(row.source), + }); + } + } + + // Free builder rows before sorting/compacting mapped contract rows to cut peak RAM. + drop(built.rows); + + rows.sort_unstable_by(|a, b| { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.report_date.cmp(&b.report_date)) + }); + + let mut write_idx = 0usize; + let mut read_idx = 0usize; + let total_mapped = rows.len(); + let mut last_listing_id: Option = None; + + while read_idx < total_mapped { + let listing_id = rows[read_idx].listing_id; + let report_date = rows[read_idx].report_date; + let mut group_end = read_idx + 1; + while group_end < total_mapped + && rows[group_end].listing_id == listing_id + && rows[group_end].report_date == report_date + { + group_end += 1; + } + let group_len = group_end - read_idx; + + if group_len == 1 { + if write_idx != read_idx { + rows.swap(write_idx, read_idx); + } + if last_listing_id != Some(listing_id) { + stats.listings_out += 1; + last_listing_id = Some(listing_id); + } + write_idx += 1; + } else { + let first = &rows[read_idx]; + let all_identical = rows[read_idx + 1..group_end] + .iter() + .all(|other| parquet_row_values_bit_eq(first, other)); + + if all_identical { + stats.listing_collision_collapsed += group_len - 1; + if write_idx != read_idx { + rows.swap(write_idx, read_idx); + } + if last_listing_id != Some(listing_id) { + stats.listings_out += 1; + last_listing_id = Some(listing_id); + } + write_idx += 1; + } else { + stats.listing_collision_dropped += group_len; + } + } + + read_idx = group_end; + } + rows.truncate(write_idx); + stats.rows_out = rows.len(); + + Ok(CurateShortsOutput { rows, stats }) +} + +/// Thin end-to-end wrapper running [`curate_shorts`] and publishing the resulting contract rows +/// via [`write_shorts_dataset`] to `/shorts/part.parquet`. +/// +/// Any [`CurateShortsError`] returns before [`write_shorts_dataset`] is invoked, leaving +/// `out_dir` untouched. +pub fn curate_and_write_shorts( + out_dir: P, + reports: I, + mapping_source: &str, + mapping: &ProviderMappingTable, + options: ShortsWriteOptions, +) -> Result +where + P: AsRef, + K: Ord + Clone + AsRef, + I: IntoIterator>, +{ + let curated = curate_shorts(reports, mapping_source, mapping)?; + let write_stats = write_shorts_dataset(out_dir, &curated.rows, options)?; + Ok(CurateShortsWriteReport { + curate_stats: curated.stats, + write_stats, + }) +} + +#[cfg(test)] +#[path = "curate_shorts_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_shorts_tests.rs b/tools/curate-etl/src/curate_shorts_tests.rs new file mode 100644 index 00000000..8fe5a599 --- /dev/null +++ b/tools/curate-etl/src/curate_shorts_tests.rs @@ -0,0 +1,1065 @@ +use std::borrow::Cow; +use std::error::Error; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::provider_mapping::ProviderMappingRow; +use crate::shorts::{build_shorts, SHORTS_SOURCE_CEO}; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-curate-shorts-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn report( + key: &str, + report_date: i32, + shares_short: f64, + net_change: Option, + pct_float: Option, +) -> CeoShortReport { + CeoShortReport { + key: key.to_string(), + report_date, + shares_short, + net_change, + pct_float, + } +} + +fn map_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +fn assert_conservation_and_order(out: &CurateShortsOutput) { + let s = &out.stats; + assert_eq!( + s.rows_in, s.builder.rows_out, + "rows_in != builder.rows_out: {s:?}" + ); + assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); + assert_eq!( + s.rows_in, + s.rows_out + + s.dropped_unmapped + + s.listing_collision_collapsed + + s.listing_collision_dropped, + "curate accounting conservation mismatch: {s:?}" + ); + assert_eq!( + s.builder.rows_in, + s.builder.rows_out + + s.builder.dropped_invalid_shares_short + + s.builder.duplicate_collapsed + + s.builder.duplicate_conflict_dropped, + "builder accounting conservation mismatch: {s:?}" + ); + + let mut distinct_listings = 0usize; + let mut prev_listing: Option = None; + for row in &out.rows { + assert_eq!(row.source.as_ref(), SHORTS_SOURCE_CEO); + if prev_listing != Some(row.listing_id) { + distinct_listings += 1; + prev_listing = Some(row.listing_id); + } + } + assert_eq!(s.listings_out, distinct_listings); + + for pair in out.rows.windows(2) { + assert!( + (pair[0].listing_id, pair[0].report_date) < (pair[1].listing_id, pair[1].report_date), + "output rows must be strictly sorted and unique by (listing_id, report_date): {:?} vs {:?}", + (pair[0].listing_id, pair[0].report_date), + (pair[1].listing_id, pair[1].report_date), + ); + } +} + +fn read_parquet_rows(path: &Path) -> (usize, Vec) { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let footer_rows = metadata.file_metadata().num_rows() as usize; + let mut out = Vec::with_capacity(footer_rows); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let listing_id = read_i32_col(rg_reader.get_column_reader(0).unwrap(), num_rows); + let report_date = read_i32_col(rg_reader.get_column_reader(1).unwrap(), num_rows); + let known_at_micros = read_i64_col(rg_reader.get_column_reader(2).unwrap(), num_rows); + let shares_short = read_req_f64_col(rg_reader.get_column_reader(3).unwrap(), num_rows); + let net_change = read_opt_f64_col(rg_reader.get_column_reader(4).unwrap(), num_rows); + let pct_float = read_opt_f64_col(rg_reader.get_column_reader(5).unwrap(), num_rows); + let source = read_str_col(rg_reader.get_column_reader(6).unwrap(), num_rows); + + for i in 0..num_rows { + out.push(ShortsParquetRow { + listing_id: listing_id[i], + report_date: report_date[i], + known_at_micros: known_at_micros[i], + shares_short: shares_short[i], + net_change: net_change[i], + pct_float: pct_float[i], + source: Cow::Owned(source[i].clone()), + }); + } + } + (footer_rows, out) +} + +fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int32ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int32ColumnReader"), + } + values +} + +fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int64ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int64ColumnReader"), + } + values +} + +fn read_req_f64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + values +} + +fn read_opt_f64_col(reader: ColumnReader, expected: usize) -> Vec> { + let mut raw_values = Vec::with_capacity(expected); + let mut def_levels = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, levels) = r + .read_records(expected, Some(&mut def_levels), None, &mut raw_values) + .unwrap(); + assert_eq!(records, expected); + assert_eq!(levels, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + let mut out = Vec::with_capacity(expected); + let mut val_idx = 0usize; + for lvl in def_levels { + if lvl == 1 { + out.push(Some(raw_values[val_idx])); + val_idx += 1; + } else { + out.push(None); + } + } + assert_eq!(val_idx, raw_values.len()); + out +} + +fn read_str_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected ByteArrayColumnReader"), + } + values + .into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8")) + .collect() +} + +fn assert_row_bitwise_eq(actual: &ShortsParquetRow, expected: &ShortsParquetRow) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.report_date, expected.report_date); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits()); + assert_eq!( + actual.net_change.map(f64::to_bits), + expected.net_change.map(f64::to_bits) + ); + assert_eq!( + actual.pct_float.map(f64::to_bits), + expected.pct_float.map(f64::to_bits) + ); + assert_eq!(actual.source, expected.source); +} + +#[test] +fn happy_path_two_ceo_symbols_resort_by_listing_id_and_preserve_builder_known_at_and_source() { + // Assign RY (lexicographically after ABX) a smaller listing_id (10 vs 20) to prove + // post-mapping re-sorting by (listing_id, report_date). + let d_est = day(2024, 1, 15); // Winter (EST) + let d_edt = day(2024, 7, 15); // Summer (EDT) + + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "ABX", day(2015, 1, 1), None, 20), + map_row("ceo", "RY", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + + let input = vec![ + report("ABX", d_est, 12_500_000.0, Some(-250_000.0), Some(0.75)), + report("ABX", d_edt, 13_100_000.0, Some(600_000.0), None), + report("RY", d_est, 8_200_000.0, None, Some(0.60)), + report("RY", d_edt, 8_050_000.0, Some(-150_000.0), Some(0.58)), + ]; + + let built = build_shorts(input.clone()).unwrap(); + let out = curate_shorts(input, "ceo", &mapping).unwrap(); + + assert_conservation_and_order(&out); + assert_eq!(out.stats.builder, built.stats); + assert_eq!(out.stats.rows_in, 4); + assert_eq!(out.stats.rows_out, 4); + assert_eq!(out.stats.listings_out, 2); + assert_eq!(out.stats.dropped_unmapped, 0); + assert_eq!(out.stats.listing_collision_collapsed, 0); + assert_eq!(out.stats.listing_collision_dropped, 0); + + // Listing 10 (RY) comes first despite "RY" > "ABX". + let ry_built: Vec<_> = built.rows.iter().filter(|r| r.key == "RY").collect(); + let abx_built: Vec<_> = built.rows.iter().filter(|r| r.key == "ABX").collect(); + assert_eq!(ry_built.len(), 2); + assert_eq!(abx_built.len(), 2); + + for (actual, expected) in out.rows[0..2].iter().zip(ry_built.iter()) { + assert_eq!(actual.listing_id, 10); + assert_eq!(actual.report_date, expected.report_date); + assert_eq!(actual.known_at_micros, expected.known_at_utc_micros); + assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits()); + assert_eq!( + actual.net_change.map(f64::to_bits), + expected.net_change.map(f64::to_bits) + ); + assert_eq!( + actual.pct_float.map(f64::to_bits), + expected.pct_float.map(f64::to_bits) + ); + assert_eq!(actual.source.as_ref(), SHORTS_SOURCE_CEO); + assert_eq!(actual.source.as_ref(), "ceo_shorts"); + } + + for (actual, expected) in out.rows[2..4].iter().zip(abx_built.iter()) { + assert_eq!(actual.listing_id, 20); + assert_eq!(actual.report_date, expected.report_date); + assert_eq!(actual.known_at_micros, expected.known_at_utc_micros); + assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits()); + assert_eq!( + actual.net_change.map(f64::to_bits), + expected.net_change.map(f64::to_bits) + ); + assert_eq!( + actual.pct_float.map(f64::to_bits), + expected.pct_float.map(f64::to_bits) + ); + assert_eq!(actual.source.as_ref(), SHORTS_SOURCE_CEO); + } +} + +#[test] +fn date_ranged_ticker_reuse_resolves_on_report_date_and_counts_unmapped_drops() { + // Ticker "REUSE": + // listing 100: 2020-01-01 ..= 2022-06-15 + // interior gap: 2022-06-16 ..= 2022-07-04 + // listing 200: 2022-07-05 ..= 2024-12-31 + // + // Boundary proofs (report_date vs known_at_date): + // - 2022-06-15 (report_date == valid_to): known_at_date is +4 TSX bdays later (2022-06-21), + // which falls in the gap -> MUST still resolve to listing 100 on report_date. + // - 2022-06-30 (report_date in gap): known_at_date is +4 TSX bdays later (2022-07-07, skipping + // Canada Day Jul 1), which falls inside listing 200's range -> MUST drop as unmapped. + let d_pre = day(2019, 12, 31); + let d_r1_start = day(2020, 1, 15); + let d_r1_end = day(2022, 6, 15); + let d_gap_straddling_r2 = day(2022, 6, 30); + let d_r2_start = day(2022, 7, 15); + let d_r2_end = day(2024, 12, 31); + let d_post = day(2025, 1, 15); + + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "REUSE", day(2020, 1, 1), Some(d_r1_end), 100), + map_row("ceo", "REUSE", day(2022, 7, 5), Some(d_r2_end), 200), + // Different mapping_source must not match "ceo" + map_row("eod", "WRONGSRC", day(2015, 1, 1), None, 300), + ]) + .unwrap(); + + let input = vec![ + report("REUSE", d_pre, 1_000.0, None, None), // unmapped (before first range) + report("REUSE", d_r1_start, 2_000.0, Some(100.0), None), // -> 100 + report("REUSE", d_r1_end, 3_000.0, Some(1_000.0), None), // -> 100 (report_date == valid_to) + report("REUSE", d_gap_straddling_r2, 4_000.0, None, None), // unmapped (report_date in gap) + report("REUSE", d_r2_start, 5_000.0, Some(-200.0), None), // -> 200 + report("REUSE", d_r2_end, 6_000.0, Some(1_000.0), None), // -> 200 (report_date == valid_to) + report("REUSE", d_post, 7_000.0, None, None), // unmapped (after last range) + report("UNKNOWN", d_r2_start, 8_000.0, None, None), // unmapped (unknown key) + report("WRONGSRC", d_r2_start, 9_000.0, None, None), // unmapped (wrong mapping_source) + ]; + + let out = curate_shorts(input, "ceo", &mapping).unwrap(); + assert_conservation_and_order(&out); + assert_eq!(out.stats.rows_in, 9); + assert_eq!(out.stats.rows_out, 4); + assert_eq!(out.stats.listings_out, 2); + assert_eq!(out.stats.dropped_unmapped, 5); + + let keys: Vec<(i32, i32)> = out.rows.iter().map(|r| (r.listing_id, r.report_date)).collect(); + assert_eq!( + keys, + vec![ + (100, d_r1_start), + (100, d_r1_end), + (200, d_r2_start), + (200, d_r2_end), + ] + ); +} + +#[test] +fn cross_key_collisions_collapse_bitwise_identical_and_drop_conflicting_groups() { + let d1 = day(2024, 3, 15); + let d2 = day(2024, 3, 31); + let d3 = day(2024, 4, 15); + let d4 = day(2024, 4, 30); + let d5 = day(2024, 5, 15); + let d6 = day(2024, 5, 31); + let d7 = day(2024, 6, 15); + + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "A", day(2020, 1, 1), None, 10), + map_row("ceo", "B", day(2020, 1, 1), None, 10), + map_row("ceo", "C", day(2020, 1, 1), None, 10), + map_row("ceo", "X", day(2020, 1, 1), None, 20), + map_row("ceo", "Y", day(2020, 1, 1), None, 20), + ]) + .unwrap(); + + let input = vec![ + // d1 on listing 10: 3-way identical (with Some optionals and -0.0 normalized to 0.0) -> collapse (+2) + report("A", d1, 0.0, Some(-0.0), Some(1.25)), + report("B", d1, -0.0, Some(0.0), Some(1.25)), + report("C", d1, 0.0, Some(0.0), Some(1.25)), + // d2 on listing 10: 2-way identical with None optionals -> collapse (+1) + report("A", d2, 50_000.0, None, None), + report("B", d2, 50_000.0, None, None), + // d3 on listing 10: differing shares_short -> drop entire group of 3 + report("A", d3, 10_000.0, Some(100.0), Some(0.5)), + report("B", d3, 10_000.0, Some(100.0), Some(0.5)), + report("C", d3, 10_001.0, Some(100.0), Some(0.5)), + // d4 on listing 10: differing net_change (Some vs Some) -> drop group of 2 + report("A", d4, 10_000.0, Some(100.0), Some(0.5)), + report("B", d4, 10_000.0, Some(101.0), Some(0.5)), + // d5 on listing 10: differing net_change (Some vs None) -> drop group of 2 + report("A", d5, 10_000.0, Some(100.0), Some(0.5)), + report("B", d5, 10_000.0, None, Some(0.5)), + // d6 on listing 10: differing pct_float (Some vs Some) -> drop group of 2 + report("A", d6, 10_000.0, Some(100.0), Some(0.5)), + report("B", d6, 10_000.0, Some(100.0), Some(0.6)), + // d7 on listing 10: differing pct_float (Some vs None) -> drop group of 2 + report("A", d7, 10_000.0, Some(100.0), Some(0.5)), + report("B", d7, 10_000.0, Some(100.0), None), + // d1 on listing 20: conflicting shares_short -> listing 20 loses all rows + report("X", d1, 5_000.0, None, None), + report("Y", d1, 5_001.0, None, None), + ]; + + let out = curate_shorts(input, "ceo", &mapping).unwrap(); + assert_conservation_and_order(&out); + assert_eq!(out.stats.rows_in, 18); + assert_eq!(out.stats.rows_out, 2); + assert_eq!(out.stats.listings_out, 1); // listing 20 lost its only date + assert_eq!(out.stats.listing_collision_collapsed, 3); + assert_eq!(out.stats.listing_collision_dropped, 13); + + assert_eq!(out.rows[0].listing_id, 10); + assert_eq!(out.rows[0].report_date, d1); + assert_eq!(out.rows[0].shares_short.to_bits(), 0.0_f64.to_bits()); + assert_eq!(out.rows[0].net_change.map(f64::to_bits), Some(0.0_f64.to_bits())); + assert_eq!(out.rows[0].pct_float, Some(1.25)); + + assert_eq!(out.rows[1].listing_id, 10); + assert_eq!(out.rows[1].report_date, d2); + assert_eq!(out.rows[1].shares_short, 50_000.0); + assert_eq!(out.rows[1].net_change, None); + assert_eq!(out.rows[1].pct_float, None); +} + +#[test] +fn typed_caller_and_builder_errors_and_empty_input() { + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "RY", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + + // Blank/whitespace mapping_source returns EmptyMappingSource (even when input has bad dates). + for blank in ["", " ", "\t\n"] { + let err = curate_shorts( + [report("RY", day(2007, 12, 31), 100.0, None, None)], + blank, + &mapping, + ) + .unwrap_err(); + assert_eq!(err, CurateShortsError::EmptyMappingSource); + assert!(err.source().is_none()); + assert!(err.to_string().contains("mapping_source")); + } + + // Builder DateOutOfRange propagates for pre-2008 and post-2030 rollover dates. + for bad_date in [day(2007, 12, 31), day(2030, 12, 30)] { + let err = curate_shorts( + [report("RY", bad_date, 100.0, None, None)], + "ceo", + &mapping, + ) + .unwrap_err(); + assert!(matches!( + err, + CurateShortsError::Shorts(ShortsError::DateOutOfRange { .. }) + )); + assert!(err.source().is_some()); + assert!(err.to_string().contains("outside supported calendar range")); + } + + // Empty input returns empty rows and zeroed stats. + let empty = curate_shorts( + std::iter::empty::>(), + "ceo", + &mapping, + ) + .unwrap(); + assert_conservation_and_order(&empty); + assert_eq!(empty.stats, CurateShortsStats::default()); + assert!(empty.rows.is_empty()); +} + +#[test] +fn mixed_fixture_conservation_and_permutation_invariance() { + let d1 = day(2024, 2, 15); + let d2 = day(2024, 2, 29); + let d3 = day(2024, 3, 15); + + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "S1", day(2020, 1, 1), None, 5), + map_row("ceo", "S1_ALIAS", day(2020, 1, 1), None, 5), + ]) + .unwrap(); + + let reports = vec![ + // Builder identical duplicate on S1 d1 (collapses in builder) + identical cross-key alias (collapses in curate) + report("S1", d1, 100_000.0, Some(5_000.0), Some(1.5)), + report("S1", d1, 100_000.0, Some(5_000.0), Some(1.5)), + report("S1_ALIAS", d1, 100_000.0, Some(5_000.0), Some(1.5)), + // Cross-key conflicting collision on (5, d2) + report("S1", d2, 200_000.0, Some(10_000.0), None), + report("S1_ALIAS", d2, 200_000.0, Some(10_001.0), None), + // Builder invalid shares_short (dropped in builder before curate) + report("S1", d3, -10.0, None, None), + // Builder non-finite optional fields (sanitized to None in builder) + report("S1", d3, 50_000.0, Some(f64::NAN), Some(f64::INFINITY)), + // Unmapped key + report("GHOST", d3, 25_000.0, None, None), + ]; + + let raw_built = build_shorts(reports.clone()).unwrap(); + let curated = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + + assert_conservation_and_order(&curated); + assert_eq!(curated.stats.builder, raw_built.stats); + assert_eq!(curated.stats.builder.dropped_invalid_shares_short, 1); + assert_eq!(curated.stats.builder.nulled_invalid_net_change, 1); + assert_eq!(curated.stats.builder.nulled_invalid_pct_float, 1); + assert_eq!(curated.stats.builder.duplicate_collapsed, 1); + assert_eq!(curated.stats.rows_in, 6); + assert_eq!(curated.stats.dropped_unmapped, 1); + assert_eq!(curated.stats.listing_collision_collapsed, 1); + assert_eq!(curated.stats.listing_collision_dropped, 2); + assert_eq!(curated.stats.rows_out, 2); + assert_eq!(curated.stats.listings_out, 1); + + // Reversed input yields bitwise-identical rows and stats. + let mut reversed = reports; + reversed.reverse(); + let curated_rev = curate_shorts(reversed, "ceo", &mapping).unwrap(); + assert_eq!(curated_rev.stats, curated.stats); + assert_eq!(curated_rev.rows.len(), curated.rows.len()); + for (a, b) in curated_rev.rows.iter().zip(curated.rows.iter()) { + assert_row_bitwise_eq(a, b); + } +} + +#[test] +fn fixed_seed_randomized_fixture_satisfies_conservation_and_parquet_writer_contract() { + struct SplitMix64(u64); + impl SplitMix64 { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + } + + let dates: Vec = (2018..=2025) + .flat_map(|y| { + (1..=12).flat_map(move |m| { + let mid = day(y, m, 15); + let end = if m == 12 { + day(y + 1, 1, 1) - 1 + } else { + day(y, m + 1, 1) - 1 + }; + [mid, end] + }) + }) + .collect(); + + let mut mapping_rows = Vec::new(); + // 0..20: single range -> listing (i + 1) + for i in 0..20 { + mapping_rows.push(map_row("ceo", &format!("K{i:02}"), day(2018, 1, 1), None, i + 1)); + } + // 20..25: ticker reuse with interior gap -> listings 101..105 / 201..205 + for i in 0..5 { + let key = format!("K{:02}", 20 + i); + mapping_rows.push(map_row( + "ceo", + &key, + day(2018, 1, 1), + Some(day(2021, 6, 30)), + 101 + i, + )); + mapping_rows.push(map_row( + "ceo", + &key, + day(2022, 1, 1), + None, + 201 + i, + )); + } + // 25..30: aliases of listings 1..=5 + for i in 0..5 { + mapping_rows.push(map_row( + "ceo", + &format!("K{:02}", 25 + i), + day(2018, 1, 1), + None, + i + 1, + )); + } + // 30..35: unmapped keys + let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); + + let mut rng = SplitMix64(0x570C_4B07_5407_7E57); + let mut reports = Vec::with_capacity(2_500); + for _ in 0..2_500 { + let key_idx = (rng.next_u64() % 35) as usize; + let report_date = dates[(rng.next_u64() as usize) % dates.len()]; + let roll = rng.next_u64() % 100; + let shares_short = if roll == 0 { + -1.0 + } else if roll == 1 { + f64::NAN + } else { + // Small quantized values so collisions have both identical and conflicting cases + ((rng.next_u64() % 4) * 1_000) as f64 + }; + let net_change = match rng.next_u64() % 5 { + 0 => None, + 1 => Some(f64::NAN), + v => Some((v as f64 - 3.0) * 500.0), + }; + let pct_float = match rng.next_u64() % 5 { + 0 => None, + 1 => Some(f64::INFINITY), + v => Some(v as f64 * 0.25), + }; + reports.push(CeoShortReport { + key: format!("K{key_idx:02}"), + report_date, + shares_short, + net_change, + pct_float, + }); + } + + let out = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + assert_conservation_and_order(&out); + assert!(out.stats.rows_out > 0); + assert!(out.stats.dropped_unmapped > 0); + assert!(out.stats.listing_collision_collapsed > 0); + assert!(out.stats.listing_collision_dropped > 0); + + // Permutation invariance on the larger randomized fixture (reversed + deterministic shuffles). + let mut reversed = reports.clone(); + reversed.reverse(); + let out_rev = curate_shorts(reversed, "ceo", &mapping).unwrap(); + assert_eq!(out_rev.stats, out.stats); + assert_eq!(out_rev.rows.len(), out.rows.len()); + for (a, b) in out_rev.rows.iter().zip(out.rows.iter()) { + assert_row_bitwise_eq(a, b); + } + + for shuffle_seed in [0xA11C_E5ED_0000_0001u64, 0xB0B0_C0DE_0000_0002u64] { + let mut shuffled = reports.clone(); + let mut shuffle_rng = SplitMix64(shuffle_seed); + for i in (1..shuffled.len()).rev() { + let j = (shuffle_rng.next_u64() as usize) % (i + 1); + shuffled.swap(i, j); + } + let out_shuf = curate_shorts(shuffled, "ceo", &mapping).unwrap(); + assert_eq!(out_shuf.stats, out.stats); + assert_eq!(out_shuf.rows.len(), out.rows.len()); + for (a, b) in out_shuf.rows.iter().zip(out.rows.iter()) { + assert_row_bitwise_eq(a, b); + } + } + + // Stage output must always satisfy write_shorts_dataset's strict contract. + let tmp = TempDirGuard::new("rand-parquet"); + let write_stats = + write_shorts_dataset(tmp.path(), &out.rows, ShortsWriteOptions::default()).unwrap(); + assert_eq!(write_stats.rows_written, out.rows.len()); + assert_eq!(write_stats.files_written, 1); +} + +#[test] +fn curate_and_write_shorts_round_trips_parquet_and_protects_out_dir_on_error() { + let tmp = TempDirGuard::new("round-trip"); + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "ABX", day(2015, 1, 1), None, 20), + map_row("ceo", "RY", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + + let reports = vec![ + report("ABX", day(2024, 1, 15), 12_500_000.0, Some(-250_000.0), Some(0.75)), + report("ABX", day(2024, 7, 15), 13_100_000.0, Some(600_000.0), None), + report("RY", day(2024, 1, 15), 8_200_000.0, None, Some(0.60)), + report("RY", day(2024, 7, 15), 8_050_000.0, Some(-150_000.0), Some(0.58)), + ]; + + let stage = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + let report_res = curate_and_write_shorts( + tmp.path(), + reports.clone(), + "ceo", + &mapping, + ShortsWriteOptions::default(), + ) + .unwrap(); + + assert_eq!(report_res.curate_stats, stage.stats); + assert_eq!(report_res.write_stats.rows_written, stage.rows.len()); + assert_eq!(report_res.write_stats.files_written, 1); + + let shorts_dir = tmp.path().join("shorts"); + let part_path = shorts_dir.join("part.parquet"); + assert!(part_path.exists(), "expected {}", part_path.display()); + + // No transient .write.lock, .tmp, or .bak files remain. + for entry in fs::read_dir(&shorts_dir).expect("read shorts dir") { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!( + name, "part.parquet", + "unexpected transient file '{name}' in {}", + shorts_dir.display() + ); + } + + let (footer_rows, read_back) = read_parquet_rows(&part_path); + assert_eq!(footer_rows, stage.stats.rows_out); + assert_eq!(read_back.len(), stage.rows.len()); + for (actual, expected) in read_back.iter().zip(stage.rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + + // Curate error with pre-existing part.parquet leaves the live file byte-for-byte intact. + let original_bytes = fs::read(&part_path).expect("read original part.parquet"); + let curate_err = curate_and_write_shorts( + tmp.path(), + reports, + " ", + &mapping, + ShortsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + curate_err, + CurateShortsWriteError::Curate(CurateShortsError::EmptyMappingSource) + )); + assert!(curate_err.source().is_some()); + assert!(curate_err.to_string().contains("curation failed")); + assert_eq!(fs::read(&part_path).unwrap(), original_bytes); + + // Curate error on a fresh directory creates no shorts/ directory at all. + let fresh_tmp = TempDirGuard::new("curate-err-fresh"); + let date_err = curate_and_write_shorts( + fresh_tmp.path(), + [report("RY", day(2007, 12, 31), 100.0, None, None)], + "ceo", + &mapping, + ShortsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + date_err, + CurateShortsWriteError::Curate(CurateShortsError::Shorts(ShortsError::DateOutOfRange { .. })) + )); + assert!(!fresh_tmp.path().join("shorts").exists()); + + // ParquetShortsError propagates cleanly. + let pq_err = curate_and_write_shorts( + fresh_tmp.path(), + std::iter::empty::>(), + "ceo", + &mapping, + ShortsWriteOptions { + row_group_rows: 0, + ..ShortsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!( + pq_err, + CurateShortsWriteError::Parquet(ParquetShortsError::InvalidRowGroupRows) + )); + assert!(pq_err.source().is_some()); + assert!(pq_err.to_string().contains("Parquet write failed")); + + // Empty input is a clean no-op without creating shorts/. + let empty_report = curate_and_write_shorts( + fresh_tmp.path(), + std::iter::empty::>(), + "ceo", + &mapping, + ShortsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_report.curate_stats, CurateShortsStats::default()); + assert_eq!(empty_report.write_stats, ShortsWriteStats::default()); + assert!(!fresh_tmp.path().join("shorts").exists()); +} + +#[test] +fn curate_shorts_matches_reference_oracle_across_fixed_seeds() { + use std::collections::BTreeMap; + + struct SplitMix64(u64); + impl SplitMix64 { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + } + + let dates: Vec = (2018..=2025) + .flat_map(|y| { + (1..=12).flat_map(move |m| { + let mid = day(y, m, 15); + let end = if m == 12 { + day(y + 1, 1, 1) - 1 + } else { + day(y, m + 1, 1) - 1 + }; + [mid, end] + }) + }) + .collect(); + + let mut mapping_rows = Vec::new(); + for i in 0..15 { + mapping_rows.push(map_row("ceo", &format!("K{i:02}"), day(2018, 1, 1), None, i + 1)); + } + for i in 0..5 { + let key = format!("K{:02}", 15 + i); + mapping_rows.push(map_row( + "ceo", + &key, + day(2018, 1, 1), + Some(day(2021, 6, 30)), + 101 + i, + )); + mapping_rows.push(map_row( + "ceo", + &key, + day(2022, 1, 1), + None, + 201 + i, + )); + } + for i in 0..5 { + mapping_rows.push(map_row( + "ceo", + &format!("K{:02}", 20 + i), + day(2018, 1, 1), + None, + i + 1, + )); + } + let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); + + for seed in [ + 0x1111_2222_3333_4444u64, + 0x5555_6666_7777_8888u64, + 0x9999_AAAA_BBBB_CCCCu64, + ] { + let mut rng = SplitMix64(seed); + let mut reports = Vec::with_capacity(3_000); + for _ in 0..3_000 { + let key_idx = (rng.next_u64() % 30) as usize; + let report_date = dates[(rng.next_u64() as usize) % dates.len()]; + let shares_short = ((rng.next_u64() % 4) * 500) as f64; + let net_change = match rng.next_u64() % 4 { + 0 => None, + v => Some((v as f64 - 2.0) * 100.0), + }; + let pct_float = match rng.next_u64() % 4 { + 0 => None, + v => Some(v as f64 * 0.25), + }; + reports.push(CeoShortReport { + key: format!("K{key_idx:02}"), + report_date, + shares_short, + net_change, + pct_float, + }); + } + + let actual = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + assert_conservation_and_order(&actual); + + // Simple reference oracle using BTreeMap over build_shorts output. + let built = build_shorts(reports).unwrap(); + let mut groups: BTreeMap<(i32, i32), Vec> = BTreeMap::new(); + let mut expected_unmapped = 0usize; + for row in built.rows { + if let Some(listing_id) = mapping.resolve("ceo", &row.key, row.report_date) { + groups + .entry((listing_id, row.report_date)) + .or_default() + .push(ShortsParquetRow { + listing_id, + report_date: row.report_date, + known_at_micros: row.known_at_utc_micros, + shares_short: row.shares_short, + net_change: row.net_change, + pct_float: row.pct_float, + source: Cow::Borrowed(row.source), + }); + } else { + expected_unmapped += 1; + } + } + + let mut expected_rows = Vec::new(); + let mut expected_collapsed = 0usize; + let mut expected_dropped = 0usize; + for group in groups.into_values() { + if group.len() == 1 { + expected_rows.push(group.into_iter().next().unwrap()); + } else { + let first = &group[0]; + let all_same = group[1..].iter().all(|r| { + r.known_at_micros == first.known_at_micros + && r.shares_short.to_bits() == first.shares_short.to_bits() + && r.net_change.map(f64::to_bits) == first.net_change.map(f64::to_bits) + && r.pct_float.map(f64::to_bits) == first.pct_float.map(f64::to_bits) + }); + if all_same { + expected_collapsed += group.len() - 1; + expected_rows.push(group.into_iter().next().unwrap()); + } else { + expected_dropped += group.len(); + } + } + } + + assert_eq!(actual.stats.dropped_unmapped, expected_unmapped); + assert_eq!(actual.stats.listing_collision_collapsed, expected_collapsed); + assert_eq!(actual.stats.listing_collision_dropped, expected_dropped); + assert_eq!(actual.rows.len(), expected_rows.len()); + for (a, e) in actual.rows.iter().zip(expected_rows.iter()) { + assert_row_bitwise_eq(a, e); + } + } +} + +#[test] +fn curate_shorts_enforces_look_ahead_lag_and_temporal_stability() { + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "RY", day(2018, 1, 1), None, 10), + map_row("ceo", "RY_ALIAS", day(2018, 1, 1), None, 10), + map_row("ceo", "TD", day(2018, 1, 1), None, 20), + ]) + .unwrap(); + + let pre_2022 = vec![ + report("RY", day(2020, 1, 15), 5_000.0, Some(100.0), Some(0.5)), + report("RY", day(2021, 6, 30), 6_000.0, Some(200.0), Some(0.6)), + report("TD", day(2021, 12, 15), 7_000.0, None, Some(0.7)), + ]; + let baseline = curate_shorts(pre_2022.clone(), "ceo", &mapping).unwrap(); + assert_conservation_and_order(&baseline); + + // Every emitted row must have known_at at least 4 calendar days after report_date. + const FOUR_DAYS_MICROS: i64 = 4 * 86_400 * 1_000_000; + for row in &baseline.rows { + let report_midnight_micros = i64::from(row.report_date) * 86_400 * 1_000_000; + assert!( + row.known_at_micros >= report_midnight_micros + FOUR_DAYS_MICROS, + "known_at_micros {} is not >= 4 days after report_date {}", + row.known_at_micros, + row.report_date + ); + } + + // Appending future 2026 reports (including conflicting cross-key collisions) must not + // alter any pre-2022 output row. + let mut with_future = pre_2022; + with_future.push(report("RY", day(2026, 1, 15), 99_999.0, Some(500.0), Some(9.9))); + with_future.push(report( + "RY_ALIAS", + day(2026, 1, 15), + 11_111.0, + Some(-500.0), + Some(1.1), + )); + with_future.push(report("TD", day(2026, 2, 15), 88_888.0, None, None)); + + let full = curate_shorts(with_future, "ceo", &mapping).unwrap(); + assert_conservation_and_order(&full); + + let cutoff = day(2022, 1, 1); + let prefix: Vec<&ShortsParquetRow> = full + .rows + .iter() + .filter(|r| r.report_date < cutoff) + .collect(); + assert_eq!(prefix.len(), baseline.rows.len()); + for (a, b) in prefix.iter().zip(baseline.rows.iter()) { + assert_row_bitwise_eq(a, b); + } +} + +#[test] +fn curate_shorts_handles_borrowed_str_keys_unknown_source_and_builder_conflict_isolation() { + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "SYM_A", day(2020, 1, 1), None, 10), + map_row("ceo", "SYM_B", day(2020, 1, 1), None, 10), + map_row("other", "SYM_A", day(2020, 1, 1), None, 99), + ]) + .unwrap(); + + // Borrowed &str keys work directly; SYM_A has a builder-level duplicate conflict (dropped by + // build_shorts), so SYM_B's lone valid copy for (listing_id=10, 2024-03-15) survives intact. + let d = day(2024, 3, 15); + let reports: Vec> = vec![ + CeoShortReport { + key: "SYM_A", + report_date: d, + shares_short: 1_000.0, + net_change: None, + pct_float: None, + }, + CeoShortReport { + key: "SYM_A", + report_date: d, + shares_short: 2_000.0, + net_change: None, + pct_float: None, + }, + CeoShortReport { + key: "SYM_B", + report_date: d, + shares_short: 3_000.0, + net_change: Some(50.0), + pct_float: Some(0.4), + }, + ]; + + let out = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + assert_conservation_and_order(&out); + assert_eq!(out.stats.builder.duplicate_conflict_dropped, 2); + assert_eq!(out.stats.rows_in, 1); + assert_eq!(out.stats.rows_out, 1); + assert_eq!(out.stats.listing_collision_dropped, 0); + assert_eq!(out.rows[0].listing_id, 10); + assert_eq!(out.rows[0].shares_short, 3_000.0); + + // Unknown mapping_source drops every builder-surviving row without error. + let unknown = curate_shorts(reports, "nonexistent_source", &mapping).unwrap(); + assert_conservation_and_order(&unknown); + assert_eq!(unknown.stats.rows_in, 1); + assert_eq!(unknown.stats.rows_out, 0); + assert_eq!(unknown.stats.dropped_unmapped, 1); +} diff --git a/tools/curate-etl/src/events.rs b/tools/curate-etl/src/events.rs index 9c9ef553..e1f6b52b 100644 --- a/tools/curate-etl/src/events.rs +++ b/tools/curate-etl/src/events.rs @@ -654,22 +654,66 @@ impl NormalizedEarning { } } -/// Builds deterministically sorted point-in-time `events` rows from raw `qmFilings` and -/// `qmEarnings` streams. -/// -/// Infallible: malformed timestamps, unknown zones, invalid dates/times, and out-of-range -/// unlinked earnings dates are counted in [`EventsStats`] and skipped without panicking. -/// Any permutation of `filings` and `earnings` produces identical `rows` and `stats`. -pub fn build_events(filings: IF, earnings: IE) -> EventsBuild +/// Crate-internal [`EventRow`] paired with its exact Eastern local calendar date (`et_date` for +/// filings, `report_date` for earnings) for point-in-time `provider_mapping` resolution across all +/// supported years (including pre-2008 filings and late-evening ET rollovers). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct EventRowWithDate { + pub(crate) row: EventRow, + pub(crate) event_date: i32, +} + +trait EventRecord: Sized { + fn from_parts(row: EventRow, event_date: i32) -> Self; + fn event_row(&self) -> &EventRow; + fn event_date_tiebreak(&self) -> i32; +} + +impl EventRecord for EventRow { + #[inline] + fn from_parts(row: EventRow, _event_date: i32) -> Self { + row + } + + #[inline] + fn event_row(&self) -> &EventRow { + self + } + + #[inline] + fn event_date_tiebreak(&self) -> i32 { + 0 + } +} + +impl EventRecord for EventRowWithDate { + #[inline] + fn from_parts(row: EventRow, event_date: i32) -> Self { + Self { row, event_date } + } + + #[inline] + fn event_row(&self) -> &EventRow { + &self.row + } + + #[inline] + fn event_date_tiebreak(&self) -> i32 { + self.event_date + } +} + +fn build_events_impl(filings: IF, earnings: IE) -> (Vec, EventsStats) where K: Ord + Clone, + R: EventRecord, IF: IntoIterator>, IE: IntoIterator>, { let filings_iter = filings.into_iter(); let (filings_lower, _) = filings_iter.size_hint(); let mut stats = EventsStats::default(); - let mut rows: Vec> = Vec::with_capacity(filings_lower); + let mut rows: Vec = Vec::with_capacity(filings_lower); let mut links: Vec> = Vec::new(); for filing in filings_iter { @@ -710,15 +754,18 @@ where }); } - rows.push(EventRow { - key: filing.key, - ts_micros: parsed.utc_micros, - known_at_micros: parsed.utc_micros, - known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, - kind: EVENT_KIND_FILING, - subtype: group.as_str().to_string(), - payload_json, - }); + rows.push(R::from_parts( + EventRow { + key: filing.key, + ts_micros: parsed.utc_micros, + known_at_micros: parsed.utc_micros, + known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, + kind: EVENT_KIND_FILING, + subtype: group.as_str().to_string(), + payload_json, + }, + parsed.et_date, + )); } // Retain the strictly earliest deterministic qualifying filing per (key, et_date). @@ -735,18 +782,23 @@ where // Collapse exact duplicate filing rows. rows.sort_unstable_by(|a, b| { - a.key - .cmp(&b.key) - .then_with(|| a.ts_micros.cmp(&b.ts_micros)) - .then_with(|| a.subtype.cmp(&b.subtype)) - .then_with(|| a.payload_json.cmp(&b.payload_json)) + let ra = a.event_row(); + let rb = b.event_row(); + ra.key + .cmp(&rb.key) + .then_with(|| ra.ts_micros.cmp(&rb.ts_micros)) + .then_with(|| ra.subtype.cmp(&rb.subtype)) + .then_with(|| ra.payload_json.cmp(&rb.payload_json)) + .then_with(|| a.event_date_tiebreak().cmp(&b.event_date_tiebreak())) }); let filings_before_dedup = rows.len(); rows.dedup_by(|b, a| { - a.key == b.key - && a.ts_micros == b.ts_micros - && a.subtype == b.subtype - && a.payload_json == b.payload_json + let ra = a.event_row(); + let rb = b.event_row(); + ra.key == rb.key + && ra.ts_micros == rb.ts_micros + && ra.subtype == rb.subtype + && ra.payload_json == rb.payload_json }); stats.filings_duplicate_collapsed = filings_before_dedup - rows.len(); stats.filings_out = rows.len(); @@ -845,15 +897,18 @@ where first.report_date, first.revenue, ); - rows.push(EventRow { - key: first.key.clone(), - ts_micros: first.ts_micros, - known_at_micros: first.ts_micros, - known_at_source: first.known_at_source, - kind: EVENT_KIND_EARNINGS, - subtype: first.subtype.to_string(), - payload_json, - }); + rows.push(R::from_parts( + EventRow { + key: first.key.clone(), + ts_micros: first.ts_micros, + known_at_micros: first.ts_micros, + known_at_source: first.known_at_source, + kind: EVENT_KIND_EARNINGS, + subtype: first.subtype.to_string(), + payload_json, + }, + first.report_date, + )); } else { stats.earnings_duplicate_conflict_dropped += group_len; } @@ -864,20 +919,24 @@ where stats.earnings_out = stats.earnings_linked_to_filing + stats.earnings_lagged_1605; rows.sort_unstable_by(|a, b| { - a.key - .cmp(&b.key) - .then_with(|| a.ts_micros.cmp(&b.ts_micros)) - .then_with(|| a.kind.cmp(b.kind)) - .then_with(|| a.subtype.cmp(&b.subtype)) - .then_with(|| a.payload_json.cmp(&b.payload_json)) - .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) - .then_with(|| a.known_at_source.cmp(b.known_at_source)) + let ra = a.event_row(); + let rb = b.event_row(); + ra.key + .cmp(&rb.key) + .then_with(|| ra.ts_micros.cmp(&rb.ts_micros)) + .then_with(|| ra.kind.cmp(rb.kind)) + .then_with(|| ra.subtype.cmp(&rb.subtype)) + .then_with(|| ra.payload_json.cmp(&rb.payload_json)) + .then_with(|| ra.known_at_micros.cmp(&rb.known_at_micros)) + .then_with(|| ra.known_at_source.cmp(rb.known_at_source)) + .then_with(|| a.event_date_tiebreak().cmp(&b.event_date_tiebreak())) }); stats.rows_out = rows.len(); let mut keys_out = 0usize; let mut prev_key: Option<&K> = None; - for row in &rows { + for item in &rows { + let row = item.event_row(); if prev_key != Some(&row.key) { keys_out += 1; prev_key = Some(&row.key); @@ -885,6 +944,36 @@ where } stats.keys_out = keys_out; + (rows, stats) +} + +/// Crate-internal entry point returning each [`EventRow`] alongside its exact Eastern local +/// calendar date (`ParsedFilingTime::et_date` for filings, `QmEarning::report_date` for earnings). +pub(crate) fn build_events_with_dates( + filings: IF, + earnings: IE, +) -> (Vec>, EventsStats) +where + K: Ord + Clone, + IF: IntoIterator>, + IE: IntoIterator>, +{ + build_events_impl(filings, earnings) +} + +/// Builds deterministically sorted point-in-time `events` rows from raw `qmFilings` and +/// `qmEarnings` streams. +/// +/// Infallible: malformed timestamps, unknown zones, invalid dates/times, and out-of-range +/// unlinked earnings dates are counted in [`EventsStats`] and skipped without panicking. +/// Any permutation of `filings` and `earnings` produces identical `rows` and `stats`. +pub fn build_events(filings: IF, earnings: IE) -> EventsBuild +where + K: Ord + Clone, + IF: IntoIterator>, + IE: IntoIterator>, +{ + let (rows, stats) = build_events_impl(filings, earnings); EventsBuild { rows, stats } } diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 6efd8878..0fffc229 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -3,12 +3,20 @@ pub mod adj; pub mod bars; pub mod bench; +pub mod bson_eod_prices; pub mod cli; pub mod corporate_actions; pub mod events; pub mod fx; +pub mod parquet_adj; pub mod parquet_bars; +pub mod parquet_corporate_actions; +pub mod parquet_events; +pub mod parquet_fx; +mod parquet_publish; +pub mod parquet_shorts; pub mod provider_mapping; +pub mod session_close; pub mod shorts; pub mod split; @@ -20,6 +28,10 @@ pub use bars::{ build_bars_1d, Bar1dRow, Bars1dBuild, Bars1dStats, BarsError, EodDailyBar, QmRawVolume, VolumeMismatchSample, MAX_MISMATCH_SAMPLES, }; +pub use bson_eod_prices::{ + decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs, + BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar, +}; pub use corporate_actions::{ build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionRow, CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, @@ -37,15 +49,41 @@ pub use fx::{ build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource, FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD, }; +pub use parquet_adj::{ + adj_factors_parquet_schema, write_adj_factors_dataset, AdjFactorsParquetRow, + AdjFactorsWriteOptions, AdjFactorsWriteStats, ParquetAdjError, +}; pub use parquet_bars::{ bars_1d_parquet_schema, write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, }; +pub use parquet_corporate_actions::{ + corporate_actions_parquet_schema, write_corporate_actions_dataset, CorporateActionsParquetRow, + CorporateActionsWriteOptions, CorporateActionsWriteStats, ForbiddenFieldValue, + ParquetCorporateActionsError, +}; +pub use parquet_events::{ + events_parquet_schema, write_events_dataset, EventsParquetRow, EventsWriteOptions, + EventsWriteStats, ParquetEventsError, +}; +pub use parquet_fx::{ + fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, + ParquetFxError, +}; +pub use parquet_shorts::{ + shorts_parquet_schema, write_shorts_dataset, ParquetShortsError, ShortsParquetRow, + ShortsWriteOptions, ShortsWriteStats, +}; pub use provider_mapping::{ MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow, ProviderMappingTable, }; +pub use session_close::{ + et_session_close_utc_micros, SessionCloseError, SESSION_CLOSE_MAX_SUPPORTED_DATE, + SESSION_CLOSE_MAX_SUPPORTED_YEAR, SESSION_CLOSE_MIN_SUPPORTED_DATE, + SESSION_CLOSE_MIN_SUPPORTED_YEAR, +}; pub use shorts::{ add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, is_canadian_business_day, CeoShortReport, ShortRow, ShortsBuild, ShortsError, ShortsStats, @@ -57,3 +95,29 @@ pub use split::{ unadjust_ohlcv, unadjust_price, unadjust_volume, ymd_to_epoch_days, OhlcvBar, SplitEntry, SplitError, SplitEvent, SplitTable, }; + +pub mod curate_bars; +pub use curate_bars::{ + curate_and_write_bars_1d, curate_bars_1d, CurateBars1dOutput, CurateBars1dStats, + CurateBars1dWriteReport, CurateBarsError, CurateBarsWriteError, BARS_1D_SESSION_CLOSE_HOUR_ET, + BARS_1D_SESSION_CLOSE_MINUTE_ET, BARS_1D_SESSION_CLOSE_SECOND_ET, BARS_1D_SOURCE_EOD, +}; + +pub mod curate_shorts; +pub use curate_shorts::{ + curate_and_write_shorts, curate_shorts, CurateShortsError, CurateShortsOutput, + CurateShortsStats, CurateShortsWriteError, CurateShortsWriteReport, +}; + +pub mod curate_events; +pub use curate_events::{ + curate_and_write_events, curate_events, CurateEventsError, CurateEventsOutput, + CurateEventsStats, CurateEventsWriteError, CurateEventsWriteReport, +}; + +pub mod curate_fx; +pub use curate_fx::{ + curate_and_write_fx_1d, curate_fx_1d, fx_1d_utc_day_end_micros, CurateFx1dOutput, + CurateFx1dStats, CurateFx1dWriteReport, CurateFxError, CurateFxWriteError, + FX_1D_MICROS_PER_DAY, FX_1D_TS_OFFSET_MICROS_FROM_DAY_START, +}; diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 3441e023..fc5eca9e 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -4,9 +4,12 @@ use std::env; use std::process::ExitCode; use curate_etl::bench::{ - run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_events_benchmark, - run_fx_benchmark, run_parquet_bars_benchmark, run_provider_mapping_benchmark, - run_shorts_benchmark, run_split_benchmark, + run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark, + run_corporate_actions_benchmark, run_curate_bars_benchmark, run_curate_events_benchmark, + run_curate_fx_benchmark, run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark, + run_parquet_adj_benchmark, run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, + run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, + run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark, }; use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction}; @@ -325,6 +328,436 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchParquetShorts(rows)) => { + let report = match run_parquet_shorts_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: parquet shorts benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-parquet-shorts"); + println!( + " input: rows={} listings={} raw_row_bytes={}", + report.rows, report.listing_count, report.raw_row_bytes + ); + println!( + " output: files={} row_groups={} bytes={} read_back_rows={}", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s size={:.2} bytes/row compression={:.2}x", + report.elapsed_ms, + report.rows_per_sec, + report.mb_per_sec, + report.bytes_per_row, + report.compression_ratio + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchParquetEvents(rows)) => { + let report = match run_parquet_events_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: parquet events benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-parquet-events"); + println!( + " input: rows={} listings={} avg_raw_row_bytes={:.1}", + report.rows, report.listing_count, report.avg_raw_row_bytes + ); + println!( + " output: files={} row_groups={} bytes={} read_back_rows={}", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s size={:.2} bytes/row compression={:.2}x", + report.elapsed_ms, + report.rows_per_sec, + report.mb_per_sec, + report.bytes_per_row, + report.compression_ratio + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchParquetFx(rows)) => { + let report = match run_parquet_fx_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: parquet fx benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-parquet-fx"); + println!( + " input: rows={} pairs={} raw_row_bytes={}", + report.rows, report.pair_count, report.raw_row_bytes + ); + println!( + " output: files={} row_groups={} bytes={} read_back_rows={}", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s size={:.2} bytes/row compression={:.2}x", + report.elapsed_ms, + report.rows_per_sec, + report.mb_per_sec, + report.bytes_per_row, + report.compression_ratio + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchParquetAdj(rows)) => { + let report = match run_parquet_adj_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: parquet adj benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-parquet-adj"); + println!( + " input: rows={} listings={} raw_row_bytes={}", + report.rows, report.listing_count, report.raw_row_bytes + ); + println!( + " output: files={} row_groups={} bytes={} read_back_rows={}", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s size={:.2} bytes/row compression={:.2}x", + report.elapsed_ms, + report.rows_per_sec, + report.mb_per_sec, + report.bytes_per_row, + report.compression_ratio + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchParquetCorporateActions(rows)) => { + let report = match run_parquet_corporate_actions_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: parquet corporate_actions benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-parquet-corporate-actions"); + println!( + " input: rows={} listings={} raw_row_bytes={}", + report.rows, report.listing_count, report.raw_row_bytes + ); + println!( + " output: files={} row_groups={} bytes={} read_back_rows={}", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s size={:.2} bytes/row compression={:.2}x", + report.elapsed_ms, + report.rows_per_sec, + report.mb_per_sec, + report.bytes_per_row, + report.compression_ratio + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchBsonEodPrices(rows)) => { + let report = run_bson_eod_prices_benchmark(rows); + println!("curate-etl bench-bson-eod-prices"); + println!(" input: rows={} bytes={}", report.rows, report.bytes); + println!( + " decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})", + report.stats.decoded, + report.stats.rejected_total(), + report.stats.rejected_missing_field, + report.stats.rejected_empty_field, + report.stats.rejected_wrong_type, + report.stats.rejected_malformed_date, + report.stats.rejected_invalid_number, + report.stats.rejected_corrupt_document + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s latency={:.2} ns/row checksum=0x{:016x}", + report.elapsed_ms, + report.rows_per_sec, + report.mb_per_sec, + report.ns_per_row, + report.checksum + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchCurateBars(rows)) => { + let report = match run_curate_bars_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: curate-bars benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + let retention_pct = if report.rows > 0 { + (report.rows_out as f64 / report.rows as f64) * 100.0 + } else { + 0.0 + }; + println!("curate-etl bench-curate-bars"); + println!( + " input: rows={} qm_rows={} splits={} keys={}", + report.rows, report.qm_rows_in, report.split_event_count, report.key_count + ); + println!( + " builder: rows_out={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} dup_collapsed={} dup_conflict_dropped={}", + report.stats.builder.rows_out, + report.stats.builder.dropped_invalid_ohlc, + report.stats.builder.dropped_inconsistent_ohlc, + report.stats.builder.dropped_invalid_volume, + report.stats.builder.duplicate_collapsed, + report.stats.builder.duplicate_conflict_dropped + ); + println!( + " stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row proj_846M={:.1}s ({:.2}m) checksum=0x{:016x}", + report.rows_out, + retention_pct, + report.listings_out, + report.stage_elapsed_ms, + report.stage_rows_per_sec, + report.stage_ns_per_row, + report.stage_extrap_846m_secs, + report.stage_extrap_846m_secs / 60.0, + report.checksum + ); + println!( + " parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows, + report.parquet_elapsed_ms, + report.parquet_rows_per_sec + ); + println!( + " total: elapsed={:.2} ms throughput={:.0} rows/s proj_846M={:.1}s ({:.2}m, projected at batch={} and {:.2}% retention)", + report.total_elapsed_ms, + report.total_rows_per_sec, + report.total_extrap_846m_secs, + report.total_extrap_846m_secs / 60.0, + report.rows, + retention_pct + ); + println!( + " curate: unmapped={} missing_curr={} ts_oor={} pre_2008_rows={} coll_collapsed={} coll_dropped={} mismatch_samples={}", + report.stats.dropped_unmapped, + report.stats.dropped_missing_currency, + report.stats.dropped_ts_out_of_range, + report.pre_2008_rows_out, + report.stats.listing_collision_collapsed, + report.stats.listing_collision_dropped, + report.mismatch_samples_out + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchCurateShorts(rows)) => { + let report = match run_curate_shorts_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: curate-shorts benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + let retention_pct = if report.rows > 0 { + (report.rows_out as f64 / report.rows as f64) * 100.0 + } else { + 0.0 + }; + println!("curate-etl bench-curate-shorts"); + println!( + " input: rows={} keys={}", + report.rows, report.key_count + ); + println!( + " builder: rows_out={} invalid_shares={} nulled_net_change={} nulled_pct_float={} dup_collapsed={} dup_conflict_dropped={}", + report.stats.builder.rows_out, + report.stats.builder.dropped_invalid_shares_short, + report.stats.builder.nulled_invalid_net_change, + report.stats.builder.nulled_invalid_pct_float, + report.stats.builder.duplicate_collapsed, + report.stats.builder.duplicate_conflict_dropped + ); + println!( + " stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + retention_pct, + report.listings_out, + report.stage_elapsed_ms, + report.stage_rows_per_sec, + report.stage_ns_per_row, + report.checksum + ); + println!( + " parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows, + report.parquet_elapsed_ms, + report.parquet_rows_per_sec + ); + println!( + " total: elapsed={:.2} ms throughput={:.0} rows/s", + report.total_elapsed_ms, report.total_rows_per_sec + ); + println!( + " curate: unmapped={} coll_collapsed={} coll_dropped={}", + report.stats.dropped_unmapped, + report.stats.listing_collision_collapsed, + report.stats.listing_collision_dropped + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchCurateEvents(rows)) => { + let report = match run_curate_events_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: curate-events benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + let retention_pct = if report.rows > 0 { + (report.rows_out as f64 / report.rows as f64) * 100.0 + } else { + 0.0 + }; + println!("curate-etl bench-curate-events"); + println!( + " input: rows={} filings={} earnings={} keys={}", + report.rows, report.filings_in, report.earnings_in, report.key_count + ); + println!( + " builder: rows_out={} filings_out={} earnings_out={} malformed_ts={} unknown_zone={} invalid_dt={} filing_dup={} linked={} lagged_1605={} earnings_oor={} earnings_dup={} earnings_conflict={}", + report.stats.builder.rows_out, + report.stats.builder.filings_out, + report.stats.builder.earnings_out, + report.stats.builder.filings_skipped_malformed_timestamp, + report.stats.builder.filings_skipped_unknown_zone, + report.stats.builder.filings_skipped_invalid_date_time, + report.stats.builder.filings_duplicate_collapsed, + report.stats.builder.earnings_linked_to_filing, + report.stats.builder.earnings_lagged_1605, + report.stats.builder.earnings_skipped_out_of_range, + report.stats.builder.earnings_duplicate_collapsed, + report.stats.builder.earnings_duplicate_conflict_dropped + ); + println!( + " stage: rows_out={} ({:.2}% retained) filings_out={} earnings_out={} listings_out={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + retention_pct, + report.stats.filings_out, + report.stats.earnings_out, + report.listings_out, + report.stage_elapsed_ms, + report.stage_rows_per_sec, + report.stage_ns_per_row, + report.checksum + ); + println!( + " parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows, + report.parquet_elapsed_ms, + report.parquet_rows_per_sec + ); + println!( + " total: elapsed={:.2} ms throughput={:.0} rows/s", + report.total_elapsed_ms, report.total_rows_per_sec + ); + println!( + " curate: unmapped={} dup_collapsed={}", + report.stats.dropped_unmapped, report.stats.listing_duplicate_collapsed + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchCurateFx(rows)) => { + let report = match run_curate_fx_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: curate-fx benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + let retention_pct = if report.rows > 0 { + (report.rows_out as f64 / report.rows as f64) * 100.0 + } else { + 0.0 + }; + println!("curate-etl bench-curate-fx"); + println!( + " input: rows={} eod_rows={} te_rows={}", + report.rows, report.eod_rows_in, report.te_rows_in + ); + println!( + " builder: rows_out={} eod_out={} te_out={} eod_invalid={} eod_inconsistent={} eod_dup_collapsed={} eod_dup_conflict={} te_invalid={} te_inconsistent={} te_dup_collapsed={} te_dup_conflict={}", + report.stats.builder.rows_out, + report.stats.builder.eod_rows_out, + report.stats.builder.te_rows_out, + report.stats.builder.eod.dropped_invalid_ohlc, + report.stats.builder.eod.dropped_inconsistent_ohlc, + report.stats.builder.eod.duplicate_collapsed, + report.stats.builder.eod.duplicate_conflict_dropped, + report.stats.builder.te.dropped_invalid_ohlc, + report.stats.builder.te.dropped_inconsistent_ohlc, + report.stats.builder.te.duplicate_collapsed, + report.stats.builder.te.duplicate_conflict_dropped + ); + println!( + " stage: rows_out={} ({:.2}% retained) elapsed={:.3} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + retention_pct, + report.stage_elapsed_ms, + report.stage_rows_per_sec, + report.stage_ns_per_row, + report.checksum + ); + println!( + " parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.3} ms throughput={:.0} rows/s", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows, + report.parquet_elapsed_ms, + report.parquet_rows_per_sec + ); + println!( + " total: elapsed={:.3} ms throughput={:.0} rows/s", + report.total_elapsed_ms, report.total_rows_per_sec + ); + println!( + " overlap: te_superseded={} checked={} within_tol={} mismatched={} max_overlap_rel={:.6}", + report.stats.builder.te_superseded_by_eod, + report.stats.builder.overlap_checked, + report.stats.builder.overlap_within_tolerance, + report.stats.builder.overlap_mismatched, + report.stats.builder.max_overlap_rel + ); + ExitCode::SUCCESS + } Err(msg) => { eprintln!("error: {msg}"); eprintln!("{}", format_usage_stderr(NAME)); diff --git a/tools/curate-etl/src/parquet_adj.rs b/tools/curate-etl/src/parquet_adj.rs new file mode 100644 index 00000000..139522bf --- /dev/null +++ b/tools/curate-etl/src/parquet_adj.rs @@ -0,0 +1,1315 @@ +//! Streaming, atomic Zstd Parquet writer for `adj_factors`. +//! +//! Writes `/adj_factors/part.parquet` matching the 8-column contract schema in +//! `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `ex_date` (`INT32`, `REQUIRED`, `DATE`) +//! 3. `split_factor` (`DOUBLE`, `REQUIRED`) +//! 4. `div_cash` (`DOUBLE`, `REQUIRED`) +//! 5. `div_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) +//! 6. `cum_split_factor` (`DOUBLE`, `REQUIRED`) +//! 7. `cum_total_factor` (`DOUBLE`, `REQUIRED`) +//! 8. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::adj::AdjFactorRow; +use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; +use crate::parquet_publish::{ + create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, + write_f64_col, write_i32_col, write_i64_col, write_optional_interned_str_col, DatasetFileLock, + PublishIoError, StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, + FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, +}; +pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; +use crate::shorts::epoch_days_to_ymd; + +/// Single `adj_factors` row matching the `design/DATA-CONTRACTS.md` Parquet schema. +#[derive(Debug, Clone, PartialEq)] +pub struct AdjFactorsParquetRow { + pub listing_id: i32, + pub ex_date: i32, + pub split_factor: f64, + pub div_cash: f64, + pub div_currency: Option>, + pub cum_split_factor: f64, + pub cum_total_factor: f64, + pub known_at_micros: i64, +} + +impl AdjFactorsParquetRow { + /// Builds an [`AdjFactorsParquetRow`] from a curated [`AdjFactorRow`] and a + /// caller-supplied UTC microsecond `known_at` timestamp. + #[inline] + pub fn from_adj_row(row: &AdjFactorRow, known_at_micros: i64) -> Self { + Self { + listing_id: row.key, + ex_date: row.ex_date, + split_factor: row.split_factor, + div_cash: row.div_cash, + div_currency: row.div_currency.clone().map(Cow::Owned), + cum_split_factor: row.cum_split_factor, + cum_total_factor: row.cum_total_factor, + known_at_micros, + } + } +} + +/// Configuration for [`write_adj_factors_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AdjFactorsWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for AdjFactorsWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_adj_factors_dataset`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AdjFactorsWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, +} + +/// Typed error returned by [`write_adj_factors_dataset`]. +#[derive(Debug)] +pub enum ParquetAdjError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + UnsortedInput { + prev_listing_id: i32, + prev_ex_date: i32, + listing_id: i32, + ex_date: i32, + }, + DuplicateKey { + listing_id: i32, + ex_date: i32, + }, + ExDateOutOfRange { + listing_id: i32, + ex_date: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + InvalidSplitFactor { + listing_id: i32, + ex_date: i32, + value: f64, + }, + InvalidDivCash { + listing_id: i32, + ex_date: i32, + value: f64, + }, + InvalidDivCurrency { + listing_id: i32, + ex_date: i32, + }, + InvalidCumSplitFactor { + listing_id: i32, + ex_date: i32, + value: f64, + }, + InvalidCumTotalFactor { + listing_id: i32, + ex_date: i32, + value: f64, + }, + LockTimeout { + path: PathBuf, + waited: Duration, + }, + RollbackFailed { + cause: Box, + failures: Vec, + }, + Io { + path: PathBuf, + source: io::Error, + }, + Parquet { + path: PathBuf, + source: ParquetError, + }, +} + +impl fmt::Display for ParquetAdjError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidRowGroupRows => { + write!(f, "invalid row_group_rows: must be greater than 0") + } + Self::InvalidZstdLevel { level } => { + write!(f, "invalid Zstd compression level: {level}") + } + Self::UnsortedInput { + prev_listing_id, + prev_ex_date, + listing_id, + ex_date, + } => write!( + f, + "unsorted input: ({listing_id}, {ex_date}) follows ({prev_listing_id}, {prev_ex_date})" + ), + Self::DuplicateKey { + listing_id, + ex_date, + } => write!( + f, + "duplicate (listing_id, ex_date) key: ({listing_id}, {ex_date})" + ), + Self::ExDateOutOfRange { + listing_id, + ex_date, + year, + min_year, + max_year, + } => write!( + f, + "ex_date {ex_date} (year {year}) for listing_id {listing_id} is outside supported range [{min_year}, {max_year}]" + ), + Self::InvalidSplitFactor { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid split_factor {value} for ({listing_id}, {ex_date}): must be finite and > 0" + ), + Self::InvalidDivCash { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid div_cash {value} for ({listing_id}, {ex_date}): must be finite and >= 0" + ), + Self::InvalidDivCurrency { + listing_id, + ex_date, + } => write!( + f, + "invalid div_currency for ({listing_id}, {ex_date}): must be non-empty when div_cash > 0 and never empty/whitespace when Some" + ), + Self::InvalidCumSplitFactor { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid cum_split_factor {value} for ({listing_id}, {ex_date}): must be finite and > 0" + ), + Self::InvalidCumTotalFactor { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid cum_total_factor {value} for ({listing_id}, {ex_date}): must be finite and > 0" + ), + Self::LockTimeout { path, waited } => write!( + f, + "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", + waited.as_millis(), + path.display() + ), + Self::RollbackFailed { cause, failures } => { + write!( + f, + "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", + failures.len() + )?; + for failure in failures { + write!(f, " [{failure}]")?; + } + Ok(()) + } + Self::Io { path, source } => { + write!(f, "I/O error at '{}': {source}", path.display()) + } + Self::Parquet { path, source } => { + write!(f, "Parquet error at '{}': {source}", path.display()) + } + } + } +} + +impl Error for ParquetAdjError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::Io { source, .. } => Some(source), + Self::Parquet { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for ParquetAdjError { + fn from(err: PublishIoError) -> Self { + match err { + PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, + PublishIoError::Io { path, source } => Self::Io { path, source }, + } + } +} + +/// Builds the exact 8-column Parquet schema for `adj_factors` per `design/DATA-CONTRACTS.md` (§3A). +pub fn adj_factors_parquet_schema() -> Result { + let fields: Vec = vec![ + Arc::new( + Type::primitive_type_builder("listing_id", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ex_date", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("split_factor", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("div_cash", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("div_currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("cum_split_factor", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("cum_total_factor", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("adj_factors") + .with_fields(fields) + .build()?, + )) +} + +fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { + Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(zstd_level)) + .set_column_dictionary_enabled(ColumnPath::from("div_currency"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn is_valid_positive_factor(value: f64) -> bool { + value.is_finite() && value > 0.0 +} + +#[inline] +fn validate_row(row: &AdjFactorsParquetRow) -> Result<(), ParquetAdjError> { + let (year, _, _) = epoch_days_to_ymd(row.ex_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { + return Err(ParquetAdjError::ExDateOutOfRange { + listing_id: row.listing_id, + ex_date: row.ex_date, + year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + if !is_valid_positive_factor(row.split_factor) { + return Err(ParquetAdjError::InvalidSplitFactor { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: row.split_factor, + }); + } + if !row.div_cash.is_finite() || row.div_cash < 0.0 { + return Err(ParquetAdjError::InvalidDivCash { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: row.div_cash, + }); + } + match row.div_currency.as_deref() { + Some(currency) if currency.trim().is_empty() => { + return Err(ParquetAdjError::InvalidDivCurrency { + listing_id: row.listing_id, + ex_date: row.ex_date, + }); + } + None if row.div_cash > 0.0 => { + return Err(ParquetAdjError::InvalidDivCurrency { + listing_id: row.listing_id, + ex_date: row.ex_date, + }); + } + _ => {} + } + if !is_valid_positive_factor(row.cum_split_factor) { + return Err(ParquetAdjError::InvalidCumSplitFactor { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: row.cum_split_factor, + }); + } + if !is_valid_positive_factor(row.cum_total_factor) { + return Err(ParquetAdjError::InvalidCumTotalFactor { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: row.cum_total_factor, + }); + } + Ok(()) +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + ex_date: Vec, + split_factor: Vec, + div_cash: Vec, + div_currency_ids: Vec, + div_currency_def_levels: Vec, + div_currency_interner: StringInterner, + cum_split_factor: Vec, + cum_total_factor: Vec, + known_at_micros: Vec, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &AdjFactorsParquetRow) { + self.listing_id.push(row.listing_id); + self.ex_date.push(row.ex_date); + self.split_factor.push(row.split_factor); + self.div_cash.push(row.div_cash); + match row.div_currency.as_deref() { + Some(currency) => { + let id = self.div_currency_interner.intern(currency); + self.div_currency_ids.push(id); + self.div_currency_def_levels.push(1); + } + None => { + self.div_currency_def_levels.push(0); + } + } + self.cum_split_factor.push(row.cum_split_factor); + self.cum_total_factor.push(row.cum_total_factor); + self.known_at_micros.push(row.known_at_micros); + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.ex_date.clear(); + self.split_factor.clear(); + self.div_cash.clear(); + self.div_currency_ids.clear(); + self.div_currency_def_levels.clear(); + self.div_currency_interner.clear(); + self.cum_split_factor.clear(); + self.cum_total_factor.clear(); + self.known_at_micros.clear(); + } +} + +struct AdjFactorsFileWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl AdjFactorsFileWriter { + fn from_file( + tmp_path: PathBuf, + final_path: PathBuf, + file: File, + schema: &TypePtr, + props: &WriterPropertiesPtr, + ) -> Result { + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetAdjError::Parquet { + path: tmp_path.clone(), + source, + }, + )?; + + Ok(Self { + tmp_path, + final_path, + writer, + buf: RowGroupBuffer::default(), + rows_written: 0, + row_groups_written: 0, + }) + } + + fn flush_row_group(&mut self, scratch: &mut Vec) -> Result<(), ParquetAdjError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetAdjError::Parquet { + path: self.tmp_path.clone(), + source, + }; + + let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; + + // 1. listing_id (INT32, REQUIRED) + write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; + // 2. ex_date (INT32, REQUIRED, DATE) + write_i32_col(&mut rg_writer, &self.buf.ex_date).map_err(map_pq)?; + // 3. split_factor (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.split_factor, None).map_err(map_pq)?; + // 4. div_cash (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.div_cash, None).map_err(map_pq)?; + // 5. div_currency (BYTE_ARRAY, OPTIONAL, STRING) + write_optional_interned_str_col( + &mut rg_writer, + &self.buf.div_currency_ids, + &self.buf.div_currency_def_levels, + &self.buf.div_currency_interner, + scratch, + ) + .map_err(map_pq)?; + // 6. cum_split_factor (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.cum_split_factor, None).map_err(map_pq)?; + // 7. cum_total_factor (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.cum_total_factor, None).map_err(map_pq)?; + // 8. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; + + rg_writer.close().map_err(map_pq)?; + + self.rows_written += row_count; + self.row_groups_written += 1; + self.buf.clear(); + Ok(()) + } + + fn finish_and_sync( + mut self, + scratch: &mut Vec, + ) -> Result { + self.flush_row_group(scratch)?; + + let mut buf_writer = + self.writer + .into_inner() + .map_err(|source| ParquetAdjError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer.flush().map_err(|source| ParquetAdjError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetAdjError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all().map_err(|source| ParquetAdjError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetAdjError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedAdjFactorsFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedAdjFactorsFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +/// Streams strictly ascending `(listing_id, ex_date)` rows into a single Zstd Parquet file +/// at `/adj_factors/part.parquet`. +/// +/// # Empty Input +/// Empty input returns `Ok(AdjFactorsWriteStats::default())` without creating `/adj_factors` +/// and without modifying or removing any pre-existing `part.parquet`. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/adj_factors` directory are serialized via an +/// in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. The file is +/// written to an exclusively created per-run staging file (`part.parquet..tmp`), flushed, +/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists, +/// a live-preserving backup (`part.parquet..bak`) is created via hard link (or exclusive +/// copy fallback) so readers never observe a missing `part.parquet` before replacement by a +/// single atomic `rename`. On any error, the writer is dropped, any backup created by this run +/// is cleaned up (reporting cleanup failures via [`ParquetAdjError::RollbackFailed`]), and +/// only staging files owned by this run are unlinked. +pub fn write_adj_factors_dataset( + out_dir: P, + rows: I, + options: AdjFactorsWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_adj_factors_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _| {}, + |path| fs::remove_file(path), + ) +} + +fn write_adj_factors_dataset_with_hooks( + out_dir: P, + rows: I, + options: AdjFactorsWriteOptions, + lock_timeout: Duration, + mut on_after_backup: F, + mut remove_backup: Rm, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(&Path, Option<&Path>), + Rm: FnMut(&Path) -> io::Result<()>, +{ + if options.row_group_rows == 0 { + return Err(ParquetAdjError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetAdjError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(AdjFactorsWriteStats::default()); + }; + validate_row(first_item.borrow())?; + + let out_dir = out_dir.as_ref(); + let adj_dir = out_dir.join("adj_factors"); + let schema = adj_factors_parquet_schema().map_err(|source| ParquetAdjError::Parquet { + path: adj_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&adj_dir).map_err(|source| ParquetAdjError::Io { + path: adj_dir.clone(), + source, + })?; + + // Serialize writers targeting the same dataset directory across threads and processes. + // Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held, + // and only after all staging/publication/rollback work has finished. + let dataset_mu = dataset_mutex(&adj_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire_with_timeout(&adj_dir, lock_timeout)?; + + let run_id = next_run_id(); + let (tmp_path, tmp_file) = create_exclusive_tmp_file(&adj_dir, &run_id)?; + // Declared before `file_writer` so Rust's reverse drop order closes the file handle + // before the guard unlinks the staging file on error or panic unwind, while `_file_lock` + // and `_in_process_guard` are still held. + let mut staging_guard = StagingFileGuard::new(tmp_path.clone()); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let mut file_writer = Some(AdjFactorsFileWriter::from_file( + tmp_path, + adj_dir.join("part.parquet"), + tmp_file, + &schema, + &props, + )?); + + let synced = { + let mut prev_key: Option<(i32, i32)> = None; + let writer = file_writer.as_mut().expect("writer initialized"); + + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + // Validate row fields before checking sort order so e.g. an out-of-range + // ex_date is reported as ExDateOutOfRange rather than UnsortedInput. + validate_row(row)?; + let key = (row.listing_id, row.ex_date); + if let Some((prev_listing_id, prev_ex_date)) = prev_key { + match key.cmp(&(prev_listing_id, prev_ex_date)) { + Ordering::Equal => { + return Err(ParquetAdjError::DuplicateKey { + listing_id: row.listing_id, + ex_date: row.ex_date, + }); + } + Ordering::Less => { + return Err(ParquetAdjError::UnsortedInput { + prev_listing_id, + prev_ex_date, + listing_id: row.listing_id, + ex_date: row.ex_date, + }); + } + Ordering::Greater => {} + } + } + prev_key = Some(key); + + writer.buf.push(row); + if writer.buf.len() == options.row_group_rows { + writer.flush_row_group(&mut scratch)?; + } + } + + let writer = file_writer.take().expect("writer still present"); + writer.finish_and_sync(&mut scratch)? + }; + + let backup_path = match fs::symlink_metadata(&synced.final_path) { + Ok(meta) if !meta.is_dir() => { + Some(create_backup_preserving_live(&synced.final_path, &run_id)?) + } + // Directory occupying final_path: leave it in place so the rename below fails cleanly. + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + return Err(ParquetAdjError::Io { + path: synced.final_path, + source, + }); + } + }; + + on_after_backup(&synced.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&synced.tmp_path, &synced.final_path) { + // `synced.final_path` was never moved during backup creation, so it remains intact; + // remove the backup created for this run. `staging_guard` unlinks our staging file on drop. + let backup_remove_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: synced.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let cause = ParquetAdjError::Io { + path: synced.final_path, + source, + }; + return match backup_remove_failure { + Some(failure) => Err(ParquetAdjError::RollbackFailed { + cause: Box::new(cause), + failures: vec![failure], + }), + None => Err(cause), + }; + } + + staging_guard.disarm(); + + if let Some(bak) = backup_path { + if let Err(remove_err) = remove_backup(&bak) { + let cause = ParquetAdjError::Io { + path: bak.clone(), + source: remove_err, + }; + return match fs::rename(&bak, &synced.final_path) { + Ok(()) => Err(cause), + Err(restore_err) => Err(ParquetAdjError::RollbackFailed { + cause: Box::new(cause), + failures: vec![RollbackFailure { + final_path: synced.final_path, + backup_path: Some(bak), + source: restore_err, + }], + }), + }; + } + } + + Ok(AdjFactorsWriteStats { + rows_written: synced.rows_written, + files_written: 1, + row_groups_written: synced.row_groups_written, + bytes_written: synced.bytes, + }) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + + use parquet::basic::ConvertedType; + use parquet::column::reader::ColumnReader; + use parquet::file::reader::{FileReader, SerializedFileReader}; + + use super::*; + use crate::adj::{build_adj_factors, DividendEvent}; + use crate::split::{ymd_to_epoch_days, SplitEvent}; + + static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + + pub(super) struct TempDirGuard { + path: PathBuf, + } + + impl TempDirGuard { + pub(super) fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-pq-adj-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + pub(super) fn path(&self) -> &Path { + &self.path + } + } + + impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + pub(super) fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") + } + + pub(super) fn declared_known_at_micros(ex_date: i32) -> i64 { + // Declared 14 days before ex_date at 13:30 UTC. + i64::from(ex_date - 14) * 86_400_000_000 + 13 * 3_600_000_000 + 30 * 60_000_000 + } + + pub(super) fn make_split_row( + listing_id: i32, + ex_date: i32, + split_factor: f64, + cum_split_factor: f64, + cum_total_factor: f64, + ) -> AdjFactorsParquetRow { + AdjFactorsParquetRow { + listing_id, + ex_date, + split_factor, + div_cash: 0.0, + div_currency: None, + cum_split_factor, + cum_total_factor, + known_at_micros: declared_known_at_micros(ex_date), + } + } + + pub(super) fn make_div_row( + listing_id: i32, + ex_date: i32, + div_cash: f64, + div_currency: &'static str, + cum_split_factor: f64, + cum_total_factor: f64, + ) -> AdjFactorsParquetRow { + AdjFactorsParquetRow { + listing_id, + ex_date, + split_factor: 1.0, + div_cash, + div_currency: Some(Cow::Borrowed(div_currency)), + cum_split_factor, + cum_total_factor, + known_at_micros: declared_known_at_micros(ex_date), + } + } + + pub(super) fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let read_i32 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i32"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + let read_i64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + let read_f64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read f64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + vals + }; + let read_opt_str = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(num_rows); + let mut def_levels = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, levels_read) = r + .read_records(num_rows, Some(&mut def_levels), None, &mut vals) + .expect("read optional utf8"); + assert_eq!(read, num_rows); + assert_eq!(levels_read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + let mut val_idx = 0usize; + let mut result = Vec::with_capacity(num_rows); + for def in def_levels { + match def { + 0 => result.push(None), + 1 => { + let text = std::str::from_utf8(vals[val_idx].data()) + .expect("valid utf8") + .to_owned(); + val_idx += 1; + result.push(Some(text)); + } + other => panic!("unexpected definition level {other}"), + } + } + assert_eq!(val_idx, vals.len()); + result + }; + + let listing_id = read_i32(0); + let ex_date = read_i32(1); + let split_factor = read_f64(2); + let div_cash = read_f64(3); + let div_currency = read_opt_str(4); + let cum_split_factor = read_f64(5); + let cum_total_factor = read_f64(6); + let known_at_micros = read_i64(7); + + for i in 0..num_rows { + out.push(AdjFactorsParquetRow { + listing_id: listing_id[i], + ex_date: ex_date[i], + split_factor: split_factor[i], + div_cash: div_cash[i], + div_currency: div_currency[i].clone().map(Cow::Owned), + cum_split_factor: cum_split_factor[i], + cum_total_factor: cum_total_factor[i], + known_at_micros: known_at_micros[i], + }); + } + } + out + } + + pub(super) fn assert_row_bitwise_eq( + actual: &AdjFactorsParquetRow, + expected: &AdjFactorsParquetRow, + ) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.ex_date, expected.ex_date); + assert_eq!( + actual.split_factor.to_bits(), + expected.split_factor.to_bits() + ); + assert_eq!(actual.div_cash.to_bits(), expected.div_cash.to_bits()); + assert_eq!(actual.div_currency, expected.div_currency); + assert_eq!( + actual.cum_split_factor.to_bits(), + expected.cum_split_factor.to_bits() + ); + assert_eq!( + actual.cum_total_factor.to_bits(), + expected.cum_total_factor.to_bits() + ); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + } + + pub(super) fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + for entry in fs::read_dir(dir).expect("read dir") { + let entry = entry.expect("dir entry"); + let name = entry.file_name().to_string_lossy().into_owned(); + assert!( + !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", + "unexpected transient file remaining: {}", + entry.path().display() + ); + } + } + + #[test] + fn schema_matches_contract_names_types_nullability_and_order() { + let schema = adj_factors_parquet_schema().expect("build schema"); + assert_eq!(schema.name(), "adj_factors"); + let fields = schema.get_fields(); + assert_eq!(fields.len(), 8); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 8] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "ex_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "split_factor", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "div_cash", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "div_currency", + PhysicalType::BYTE_ARRAY, + Repetition::OPTIONAL, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "cum_split_factor", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "cum_total_factor", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + let f = &fields[idx]; + assert_eq!(f.name(), name, "field {idx} name"); + assert_eq!(f.get_physical_type(), phys, "field {name} physical type"); + assert_eq!( + f.get_basic_info().repetition(), + rep, + "field {name} repetition" + ); + assert_eq!( + f.get_basic_info().logical_type_ref().cloned(), + logical, + "field {name} logical type" + ); + assert_eq!( + f.get_basic_info().converted_type(), + converted, + "field {name} converted type" + ); + } + } + + #[test] + fn build_adj_factors_round_trip_bitwise_and_zstd_on_every_column_chunk() { + let tmp = TempDirGuard::new("round-trip"); + let d0 = day(1969, 12, 31); // pre-1970 split-only + let d1 = day(2021, 7, 20); // split-only + let d2 = day(2024, 3, 6); // dividend-only USD + let d3 = day(2024, 6, 10); // combined split + dividend USD + let d4 = day(2025, 1, 15); // dividend-only CAD on listing 2 + + let splits = vec![ + ( + 101i32, + SplitEvent { + ex_date: d0, + ratio: 2.0, + }, + ), + ( + 101i32, + SplitEvent { + ex_date: d1, + ratio: 4.0, + }, + ), + ( + 101i32, + SplitEvent { + ex_date: d3, + ratio: 10.0, + }, + ), + ]; + let dividends = vec![ + ( + 101i32, + DividendEvent { + ex_date: d2, + cash: 0.04, + currency: "USD".to_string(), + prev_close: Some(850.0), + prev_close_currency: Some("USD".to_string()), + }, + ), + ( + 101i32, + DividendEvent { + ex_date: d3, + cash: 0.10, + currency: "USD".to_string(), + prev_close: Some(1200.0), + prev_close_currency: Some("USD".to_string()), + }, + ), + ( + 202i32, + DividendEvent { + ex_date: d4, + cash: 0.90, + currency: "CAD".to_string(), + prev_close: Some(100.0), + prev_close_currency: Some("CAD".to_string()), + }, + ), + ]; + + let built = build_adj_factors(splits, dividends).unwrap(); + let rows: Vec = built + .rows + .iter() + .map(|r| AdjFactorsParquetRow::from_adj_row(r, declared_known_at_micros(r.ex_date))) + .collect(); + assert_eq!(rows.len(), 5); + assert!(rows[0].div_currency.is_none()); + assert!(rows[1].div_currency.is_none()); + assert_eq!(rows[2].div_currency.as_deref(), Some("USD")); + assert_eq!(rows[3].div_currency.as_deref(), Some("USD")); + assert_eq!(rows[4].div_currency.as_deref(), Some("CAD")); + + let opts = AdjFactorsWriteOptions { + row_group_rows: 2, + ..AdjFactorsWriteOptions::default() + }; + let stats = write_adj_factors_dataset(tmp.path(), &rows, opts).unwrap(); + + assert_eq!(stats.rows_written, 5); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 3); + assert!(stats.bytes_written > 0); + + let path = tmp.path().join("adj_factors/part.parquet"); + assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written); + + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().num_rows(), 5); + assert_eq!(meta.num_row_groups(), 3); + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} expected ZSTD, got {:?}", + col.column_path(), + col.compression() + ); + } + } + + let actual = read_parquet_rows(&path); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } + assert_eq!(actual[0].ex_date, -1); + assert!(actual[0].div_currency.is_none()); + assert_no_transient_files(&tmp.path().join("adj_factors")); + } + + #[test] + fn empty_input_creates_nothing_and_preserves_existing_part_parquet() { + let tmp = TempDirGuard::new("empty"); + let fresh = tmp.path().join("fresh"); + let stats = write_adj_factors_dataset( + &fresh, + std::iter::empty::(), + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats, AdjFactorsWriteStats::default()); + assert!(!fresh.exists(), "empty input must not create out_dir"); + + let seeded = tmp.path().join("seeded"); + let seed_rows = vec![make_div_row(10, day(2024, 3, 15), 0.25, "USD", 1.0, 1.005)]; + write_adj_factors_dataset(&seeded, &seed_rows, AdjFactorsWriteOptions::default()).unwrap(); + let part = seeded.join("adj_factors/part.parquet"); + let before = fs::read(&part).unwrap(); + + let empty_stats = write_adj_factors_dataset( + &seeded, + std::iter::empty::(), + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_stats, AdjFactorsWriteStats::default()); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&seeded.join("adj_factors")); + } + + #[test] + fn determinism_identical_rows_produce_byte_identical_files() { + let tmp = TempDirGuard::new("determinism"); + let rows = vec![ + make_split_row(1, day(2021, 7, 20), 4.0, 40.0, 40.08), + make_div_row(1, day(2024, 3, 6), 0.04, "USD", 10.0, 10.02), + make_div_row(2, day(2025, 1, 15), 0.90, "CAD", 1.0, 1.009), + ]; + + let out_a = tmp.path().join("a"); + let out_b = tmp.path().join("b"); + let opts = AdjFactorsWriteOptions { + row_group_rows: 2, + ..AdjFactorsWriteOptions::default() + }; + write_adj_factors_dataset(&out_a, &rows, opts).unwrap(); + write_adj_factors_dataset(&out_b, &rows, opts).unwrap(); + + let bytes_a = fs::read(out_a.join("adj_factors/part.parquet")).unwrap(); + let bytes_b = fs::read(out_b.join("adj_factors/part.parquet")).unwrap(); + assert_eq!(bytes_a, bytes_b); + } +} + +#[cfg(test)] +#[path = "parquet_adj_tests.rs"] +mod edge_case_tests; diff --git a/tools/curate-etl/src/parquet_adj_tests.rs b/tools/curate-etl/src/parquet_adj_tests.rs new file mode 100644 index 00000000..4cc00792 --- /dev/null +++ b/tools/curate-etl/src/parquet_adj_tests.rs @@ -0,0 +1,817 @@ +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use parquet::basic::Encoding; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::tests::{ + assert_no_transient_files, assert_row_bitwise_eq, day, declared_known_at_micros, make_div_row, + make_split_row, read_parquet_rows, TempDirGuard, +}; +use super::{ + write_adj_factors_dataset, write_adj_factors_dataset_with_hooks, AdjFactorsParquetRow, + AdjFactorsWriteOptions, ParquetAdjError, +}; +use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; +use crate::parquet_publish::STRING_WRITE_BATCH_ROWS; + +fn seed_existing(out_dir: &Path) -> (PathBuf, Vec) { + let seed = vec![ + make_split_row(100, day(2024, 1, 15), 2.0, 2.0, 2.02), + make_div_row(100, day(2024, 6, 15), 0.50, "USD", 1.0, 1.01), + ]; + write_adj_factors_dataset(out_dir, &seed, AdjFactorsWriteOptions::default()).unwrap(); + let part = out_dir.join("adj_factors/part.parquet"); + let before = fs::read(&part).unwrap(); + (part, before) +} + +#[test] +fn single_row_and_row_group_boundary_counts_with_pre_1970_split_only() { + let tmp = TempDirGuard::new("rg-boundaries"); + + // 1 row: pre-1970 split-only (negative epoch day, None div_currency) + let out_1 = tmp.path().join("one"); + let single = vec![make_split_row(7, day(1969, 12, 31), 2.0, 2.0, 2.0)]; + let stats_1 = + write_adj_factors_dataset(&out_1, &single, AdjFactorsWriteOptions::default()).unwrap(); + assert_eq!(stats_1.rows_written, 1); + assert_eq!(stats_1.files_written, 1); + assert_eq!(stats_1.row_groups_written, 1); + let actual_1 = read_parquet_rows(&out_1.join("adj_factors/part.parquet")); + assert_eq!(actual_1.len(), 1); + assert_row_bitwise_eq(&actual_1[0], &single[0]); + assert_eq!(actual_1[0].ex_date, -1); + assert!(actual_1[0].div_currency.is_none()); + + // Exactly row_group_rows (4 rows, row_group_rows = 4 => 1 row group) + let base = day(2024, 1, 2); + let rows_exact: Vec = (0..4_i32) + .map(|i| { + if i % 2 == 0 { + make_split_row(10, base + i * 30, 2.0, 4.0, 4.1) + } else { + make_div_row(10, base + i * 30, 0.25, "USD", 1.0, 1.02) + } + }) + .collect(); + let out_exact = tmp.path().join("exact"); + let opts = AdjFactorsWriteOptions { + row_group_rows: 4, + ..AdjFactorsWriteOptions::default() + }; + let stats_exact = write_adj_factors_dataset(&out_exact, &rows_exact, opts).unwrap(); + assert_eq!(stats_exact.rows_written, 4); + assert_eq!(stats_exact.row_groups_written, 1); + let reader_exact = SerializedFileReader::new( + File::open(out_exact.join("adj_factors/part.parquet")).unwrap(), + ) + .unwrap(); + assert_eq!(reader_exact.metadata().num_row_groups(), 1); + assert_eq!(reader_exact.metadata().row_group(0).num_rows(), 4); + + // row_group_rows + 1 (5 rows, row_group_rows = 4 => 2 row groups: [4, 1]) + let rows_plus_one = vec![ + make_split_row(1, day(1969, 6, 15), 3.0, 3.0, 3.0), + make_div_row(1, base, 0.40, "USD", 1.0, 1.01), + make_split_row(2, base, 0.5, 0.5, 0.505), + make_div_row(3, day(1969, 12, 31), 0.15, "CAD", 1.0, 1.005), + make_div_row(3, base, 0.20, "CAD", 1.0, 1.002), + ]; + let out_plus = tmp.path().join("plus-one"); + let stats_plus = write_adj_factors_dataset(&out_plus, &rows_plus_one, opts).unwrap(); + assert_eq!(stats_plus.rows_written, 5); + assert_eq!(stats_plus.row_groups_written, 2); + let p_plus = out_plus.join("adj_factors/part.parquet"); + let reader_plus = SerializedFileReader::new(File::open(&p_plus).unwrap()).unwrap(); + let rg_sizes: Vec = (0..reader_plus.metadata().num_row_groups()) + .map(|i| reader_plus.metadata().row_group(i).num_rows()) + .collect(); + assert_eq!(rg_sizes, vec![4, 1]); + let actual_plus = read_parquet_rows(&p_plus); + assert_eq!(actual_plus.len(), rows_plus_one.len()); + for (a, e) in actual_plus.iter().zip(&rows_plus_one) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&out_plus.join("adj_factors")); +} + +#[test] +fn all_null_div_currency_row_group_and_multi_batch_mixed_nulls_round_trip() { + let tmp = TempDirGuard::new("opt-str-batches"); + let base = day(2000, 1, 3); + + // 100% split-only (all-None div_currency) spanning > STRING_WRITE_BATCH_ROWS (4096) in one row group. + let all_null_count = STRING_WRITE_BATCH_ROWS + 137; + let all_null_rows: Vec = (0..all_null_count) + .map(|i| { + let listing_id = (i / 100) as i32 + 1; + let ex_date = base + (i % 100) as i32; + make_split_row(listing_id, ex_date, 2.0, 2.0, 2.0) + }) + .collect(); + let out_null = tmp.path().join("all-null"); + let stats_null = + write_adj_factors_dataset(&out_null, &all_null_rows, AdjFactorsWriteOptions::default()) + .unwrap(); + assert_eq!(stats_null.rows_written, all_null_count); + assert_eq!(stats_null.row_groups_written, 1); + let actual_null = read_parquet_rows(&out_null.join("adj_factors/part.parquet")); + assert_eq!(actual_null.len(), all_null_rows.len()); + for (a, e) in actual_null.iter().zip(&all_null_rows) { + assert_row_bitwise_eq(a, e); + assert!(a.div_currency.is_none()); + } + + // > STRING_WRITE_BATCH_ROWS mixed Some/None values crossing multiple 4,096-row batches + // and row-group boundaries, including an all-null middle chunk inside the same row group. + let mixed_count = STRING_WRITE_BATCH_ROWS * 2 + 257; + let mixed_rows: Vec = (0..mixed_count) + .map(|i| { + let listing_id = (i / 500) as i32 + 1; + let ex_date = base + (i % 500) as i32; + // Make chunk 1 (rows 4096..8192) all-null while chunks 0 and 2 alternate USD/CAD/None. + if (STRING_WRITE_BATCH_ROWS..STRING_WRITE_BATCH_ROWS * 2).contains(&i) { + make_split_row(listing_id, ex_date, 1.5, 1.5, 1.5) + } else { + match i % 3 { + 0 => make_split_row(listing_id, ex_date, 2.0, 2.0, 2.0), + 1 => make_div_row(listing_id, ex_date, 0.25, "USD", 1.0, 1.01), + _ => make_div_row(listing_id, ex_date, 0.40, "CAD", 1.0, 1.02), + } + } + }) + .collect(); + + let out_mixed = tmp.path().join("mixed-multi-batch"); + let stats_mixed = write_adj_factors_dataset( + &out_mixed, + &mixed_rows, + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats_mixed.rows_written, mixed_count); + assert_eq!(stats_mixed.row_groups_written, 1); + let actual_mixed = read_parquet_rows(&out_mixed.join("adj_factors/part.parquet")); + assert_eq!(actual_mixed.len(), mixed_rows.len()); + for (a, e) in actual_mixed.iter().zip(&mixed_rows) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&out_mixed.join("adj_factors")); +} + +#[test] +fn div_currency_uses_dictionary_encoding_and_invalid_options_preserve_state() { + let tmp = TempDirGuard::new("dict-zstd"); + let base = day(2024, 1, 2); + let rows: Vec = (0..64_i32) + .map(|i| { + let listing_id = if i < 32 { 1 } else { 2 }; + let d = base + (i % 32); + match i % 4 { + 0 => make_split_row(listing_id, d, 2.0, 2.0, 2.0), + 1 | 2 => make_div_row(listing_id, d, 0.30, "USD", 1.0, 1.01), + _ => make_div_row(listing_id, d, 0.45, "CAD", 1.0, 1.02), + } + }) + .collect(); + + let out_ok = tmp.path().join("lvl-3"); + write_adj_factors_dataset(&out_ok, &rows, AdjFactorsWriteOptions::default()).unwrap(); + let p = out_ok.join("adj_factors/part.parquet"); + let reader = SerializedFileReader::new(File::open(&p).unwrap()).unwrap(); + let rg0 = reader.metadata().row_group(0); + + let col = rg0.column(4); // div_currency + assert!( + col.encodings() + .any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)), + "expected dictionary encoding on div_currency column, got {:?}", + col.encodings().collect::>() + ); + + // Invalid row_group_rows and zstd_level in fresh dir + let out_bad = tmp.path().join("bad-opts-fresh"); + assert!(matches!( + write_adj_factors_dataset( + &out_bad, + &rows, + AdjFactorsWriteOptions { + row_group_rows: 0, + ..AdjFactorsWriteOptions::default() + } + ), + Err(ParquetAdjError::InvalidRowGroupRows) + )); + assert!(matches!( + write_adj_factors_dataset( + &out_bad, + &rows, + AdjFactorsWriteOptions { + zstd_level: 23, + ..AdjFactorsWriteOptions::default() + } + ), + Err(ParquetAdjError::InvalidZstdLevel { level: 23 }) + )); + assert!(matches!( + write_adj_factors_dataset( + &out_bad, + &rows, + AdjFactorsWriteOptions { + zstd_level: 99, + ..AdjFactorsWriteOptions::default() + } + ), + Err(ParquetAdjError::InvalidZstdLevel { level: 99 }) + )); + assert!(!out_bad.exists(), "invalid options must not create out_dir"); + + // Invalid options in seeded dir leave existing part.parquet byte-identical + let out_seeded = tmp.path().join("bad-opts-seeded"); + let (part, before) = seed_existing(&out_seeded); + assert!(matches!( + write_adj_factors_dataset( + &out_seeded, + &rows, + AdjFactorsWriteOptions { + row_group_rows: 0, + ..AdjFactorsWriteOptions::default() + } + ), + Err(ParquetAdjError::InvalidRowGroupRows) + )); + assert!(matches!( + write_adj_factors_dataset( + &out_seeded, + &rows, + AdjFactorsWriteOptions { + zstd_level: 23, + ..AdjFactorsWriteOptions::default() + } + ), + Err(ParquetAdjError::InvalidZstdLevel { level: 23 }) + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&out_seeded.join("adj_factors")); +} + +#[test] +fn overwrite_replaces_existing_part_parquet_and_leaves_no_transients() { + let tmp = TempDirGuard::new("overwrite"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![ + make_div_row(500, day(2025, 4, 15), 0.75, "CAD", 1.0, 1.015), + make_split_row(500, day(2025, 6, 1), 5.0, 5.0, 5.0), + ]; + let stats = + write_adj_factors_dataset(tmp.path(), &replacement, AdjFactorsWriteOptions::default()) + .unwrap(); + assert_eq!(stats.rows_written, 2); + assert_eq!(stats.files_written, 1); + + let after = fs::read(&part).unwrap(); + assert_ne!(after, before); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), replacement.len()); + for (a, e) in actual.iter().zip(&replacement) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("adj_factors")); +} + +#[test] +fn validation_errors_return_typed_variants_and_preserve_existing_state() { + let tmp = TempDirGuard::new("validation"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 6, 15); + + type ErrorCheck = fn(&ParquetAdjError) -> bool; + let bad_cases: Vec<(&str, Vec, ErrorCheck)> = vec![ + ( + "unsorted-listing", + vec![ + make_div_row(2, d1, 0.25, "USD", 1.0, 1.01), + make_div_row(1, d1, 0.25, "USD", 1.0, 1.01), + ], + |e| { + matches!( + e, + ParquetAdjError::UnsortedInput { + prev_listing_id: 2, + listing_id: 1, + .. + } + ) + }, + ), + ( + "unsorted-ex-date", + vec![ + make_div_row(1, d2, 0.25, "USD", 1.0, 1.01), + make_div_row(1, d1, 0.25, "USD", 1.0, 1.01), + ], + |e| matches!(e, ParquetAdjError::UnsortedInput { listing_id: 1, .. }), + ), + ( + "duplicate-key", + vec![ + make_div_row(1, d1, 0.25, "USD", 1.0, 1.01), + make_div_row(1, d1, 0.50, "USD", 1.0, 1.02), + ], + |e| matches!(e, ParquetAdjError::DuplicateKey { listing_id: 1, .. }), + ), + ( + "ex-date-below-min-year", + vec![make_split_row(1, day(1899, 12, 31), 2.0, 2.0, 2.0)], + |e| { + matches!( + e, + ParquetAdjError::ExDateOutOfRange { + year: 1899, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + ( + "ex-date-above-max-year", + vec![make_split_row(1, day(2201, 1, 1), 2.0, 2.0, 2.0)], + |e| { + matches!( + e, + ParquetAdjError::ExDateOutOfRange { + year: 2201, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + ( + "split-factor-zero", + vec![make_split_row(1, d1, 0.0, 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidSplitFactor { .. }), + ), + ( + "split-factor-neg-zero", + vec![make_split_row(1, d1, -0.0, 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidSplitFactor { .. }), + ), + ( + "split-factor-negative", + vec![make_split_row(1, d1, -2.0, 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidSplitFactor { .. }), + ), + ( + "split-factor-nan", + vec![make_split_row(1, d1, f64::NAN, 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidSplitFactor { .. }), + ), + ( + "split-factor-inf", + vec![make_split_row(1, d1, f64::INFINITY, 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidSplitFactor { .. }), + ), + ( + "div-cash-negative", + vec![make_div_row(1, d1, -0.01, "USD", 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidDivCash { .. }), + ), + ( + "div-cash-nan", + vec![make_div_row(1, d1, f64::NAN, "USD", 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidDivCash { .. }), + ), + ( + "div-cash-inf", + vec![make_div_row(1, d1, f64::INFINITY, "USD", 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidDivCash { .. }), + ), + ( + "div-cash-pos-none-currency", + vec![AdjFactorsParquetRow { + div_cash: 0.25, + div_currency: None, + ..make_split_row(1, d1, 1.0, 1.0, 1.0) + }], + |e| matches!(e, ParquetAdjError::InvalidDivCurrency { .. }), + ), + ( + "div-cash-pos-empty-currency", + vec![make_div_row(1, d1, 0.25, "", 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidDivCurrency { .. }), + ), + ( + "div-cash-pos-whitespace-currency", + vec![make_div_row(1, d1, 0.25, " \t ", 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidDivCurrency { .. }), + ), + ( + "div-cash-zero-whitespace-currency", + vec![AdjFactorsParquetRow { + div_cash: 0.0, + div_currency: Some(Cow::Borrowed(" ")), + ..make_split_row(1, d1, 2.0, 2.0, 2.0) + }], + |e| matches!(e, ParquetAdjError::InvalidDivCurrency { .. }), + ), + ( + "cum-split-factor-zero", + vec![make_split_row(1, d1, 2.0, 0.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidCumSplitFactor { .. }), + ), + ( + "cum-split-factor-nan", + vec![make_split_row(1, d1, 2.0, f64::NAN, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidCumSplitFactor { .. }), + ), + ( + "cum-total-factor-negative", + vec![make_split_row(1, d1, 2.0, 2.0, -1.0)], + |e| matches!(e, ParquetAdjError::InvalidCumTotalFactor { .. }), + ), + ( + "cum-total-factor-inf", + vec![make_split_row(1, d1, 2.0, 2.0, f64::INFINITY)], + |e| matches!(e, ParquetAdjError::InvalidCumTotalFactor { .. }), + ), + ]; + + for (label, rows, check) in bad_cases { + let fresh = tmp.path().join(format!("fresh-{label}")); + let err = + write_adj_factors_dataset(&fresh, &rows, AdjFactorsWriteOptions::default()) + .unwrap_err(); + assert!(check(&err), "fresh case '{label}' got unexpected {err:?}"); + assert!( + !fresh.join("adj_factors/part.parquet").exists(), + "fresh case '{label}' must not publish part.parquet" + ); + assert_no_transient_files(&fresh.join("adj_factors")); + + let seeded = tmp.path().join(format!("seeded-{label}")); + let (part, before) = seed_existing(&seeded); + let err_s = + write_adj_factors_dataset(&seeded, &rows, AdjFactorsWriteOptions::default()) + .unwrap_err(); + assert!(check(&err_s), "seeded case '{label}' got unexpected {err_s:?}"); + assert_eq!( + fs::read(&part).unwrap(), + before, + "seeded case '{label}' must preserve existing part.parquet" + ); + assert_no_transient_files(&seeded.join("adj_factors")); + } +} + +#[test] +fn mid_stream_failure_after_flushed_row_groups_preserves_existing_file() { + let tmp = TempDirGuard::new("mid-stream-fail"); + let (part, before) = seed_existing(tmp.path()); + + let base = day(2024, 1, 2); + let mut rows: Vec = (0..5_i32) + .map(|i| make_div_row(1, base + i * 30, 0.25, "USD", 1.0, 1.01)) + .collect(); + rows.push(AdjFactorsParquetRow { + listing_id: 1, + ex_date: base + 6 * 30, + split_factor: f64::NAN, + div_cash: 0.0, + div_currency: None, + cum_split_factor: 1.0, + cum_total_factor: 1.0, + known_at_micros: declared_known_at_micros(base + 6 * 30), + }); + + let err = write_adj_factors_dataset( + tmp.path(), + &rows, + AdjFactorsWriteOptions { + row_group_rows: 2, + ..AdjFactorsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetAdjError::InvalidSplitFactor { .. })); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("adj_factors")); +} + +#[test] +fn out_dir_or_adj_factors_occupied_by_regular_file_returns_io_error() { + let tmp = TempDirGuard::new("io-blocker"); + let rows = vec![make_div_row(1, day(2024, 3, 15), 0.25, "USD", 1.0, 1.01)]; + + let file_as_out = tmp.path().join("not-a-dir"); + fs::write(&file_as_out, b"sentinel").unwrap(); + let err = + write_adj_factors_dataset(&file_as_out, &rows, AdjFactorsWriteOptions::default()) + .unwrap_err(); + assert!(matches!(err, ParquetAdjError::Io { .. })); + assert!(StdError::source(&err).is_some()); + assert_eq!(fs::read(&file_as_out).unwrap(), b"sentinel"); + + let out_with_file_adj = tmp.path().join("adj-is-file"); + fs::create_dir_all(&out_with_file_adj).unwrap(); + let adj_file = out_with_file_adj.join("adj_factors"); + fs::write(&adj_file, b"file-not-dir").unwrap(); + let err2 = write_adj_factors_dataset( + &out_with_file_adj, + &rows, + AdjFactorsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!(err2, ParquetAdjError::Io { .. })); + assert_eq!(fs::read(&adj_file).unwrap(), b"file-not-dir"); +} + +#[test] +fn stale_lock_times_out_leaving_lock_and_existing_part_intact() { + let tmp = TempDirGuard::new("stale-lock"); + let (part, before) = seed_existing(tmp.path()); + let lock_path = tmp.path().join("adj_factors/.write.lock"); + fs::write(&lock_path, b"999999\n").unwrap(); + + let rows = vec![make_div_row(1, day(2024, 6, 15), 0.50, "USD", 1.0, 1.01)]; + let err = write_adj_factors_dataset_with_hooks( + tmp.path(), + &rows, + AdjFactorsWriteOptions::default(), + Duration::from_millis(30), + |_, _| {}, + |path| fs::remove_file(path), + ) + .unwrap_err(); + + assert!( + matches!(err, ParquetAdjError::LockTimeout { ref path, .. } if path == &lock_path), + "expected LockTimeout, got {err:?}" + ); + assert!( + lock_path.exists(), + "stale lock must not be deleted by timed-out writer" + ); + assert_eq!(fs::read(&part).unwrap(), before); +} + +#[test] +fn live_part_parquet_stays_readable_between_backup_and_rename() { + let tmp = TempDirGuard::new("live-readable"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![make_div_row(200, day(2024, 9, 15), 0.60, "CAD", 1.0, 1.02)]; + let observed_live = Arc::new(Mutex::new(false)); + let observed_clone = Arc::clone(&observed_live); + + write_adj_factors_dataset_with_hooks( + tmp.path(), + &replacement, + AdjFactorsWriteOptions::default(), + Duration::from_secs(5), + move |final_path, backup_path| { + assert!( + backup_path.is_some(), + "expected backup path for existing file" + ); + assert_eq!(fs::read(final_path).unwrap(), before); + assert_eq!(fs::read(backup_path.unwrap()).unwrap(), before); + *observed_clone.lock().unwrap() = true; + }, + |path| fs::remove_file(path), + ) + .unwrap(); + + assert!(*observed_live.lock().unwrap()); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), 1); + assert_row_bitwise_eq(&actual[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("adj_factors")); +} + +#[test] +fn rename_failure_over_directory_blocker_cleans_up_staging_and_unowned_tmp_is_preserved() { + let tmp = TempDirGuard::new("rename-blocker"); + let adj_dir = tmp.path().join("adj_factors"); + let blocking_dir = adj_dir.join("part.parquet"); + fs::create_dir_all(&blocking_dir).unwrap(); + + let unowned_tmp = adj_dir.join("part.parquet.unowned-other-run.tmp"); + fs::write(&unowned_tmp, b"keep-me").unwrap(); + + let rows = vec![make_div_row(1, day(2024, 3, 15), 0.25, "USD", 1.0, 1.01)]; + let err = + write_adj_factors_dataset(tmp.path(), &rows, AdjFactorsWriteOptions::default()) + .unwrap_err(); + assert!(matches!(err, ParquetAdjError::Io { .. }), "got {err:?}"); + assert!(blocking_dir.is_dir(), "directory blocker must remain intact"); + assert_eq!( + fs::read(&unowned_tmp).unwrap(), + b"keep-me", + "unowned .tmp file must be preserved" + ); + + let mut entries: Vec = fs::read_dir(&adj_dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + entries.sort(); + assert_eq!( + entries, + vec![ + "part.parquet".to_string(), + "part.parquet.unowned-other-run.tmp".to_string(), + ] + ); +} + +#[test] +fn concurrent_in_process_writers_serialize_cleanly() { + let tmp = TempDirGuard::new("concurrent-unit"); + let out = Arc::new(tmp.path().to_path_buf()); + + let out_1 = Arc::clone(&out); + let handle_1 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + if i == 1 { + thread::sleep(Duration::from_millis(30)); + } + make_div_row(10, day(2024, 1, 15) + i * 30, 0.25, "USD", 1.0, 1.01) + }); + write_adj_factors_dataset(out_1.as_path(), iter, AdjFactorsWriteOptions::default()) + }); + + thread::sleep(Duration::from_millis(5)); + let out_2 = Arc::clone(&out); + let handle_2 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + make_split_row(20, day(2024, 2, 15) + i * 30, 2.0, 2.0, 2.0) + }); + write_adj_factors_dataset(out_2.as_path(), iter, AdjFactorsWriteOptions::default()) + }); + + let s1 = handle_1.join().unwrap().unwrap(); + let s2 = handle_2.join().unwrap().unwrap(); + assert_eq!(s1.rows_written, 2); + assert_eq!(s2.rows_written, 2); + + let got = read_parquet_rows(&tmp.path().join("adj_factors/part.parquet")); + assert_eq!(got.len(), 2); + assert!( + got.iter().all(|r| r.listing_id == 10) || got.iter().all(|r| r.listing_id == 20), + "output must come entirely from one writer generation" + ); + assert_no_transient_files(&tmp.path().join("adj_factors")); +} + +#[test] +fn panicking_iterator_cleans_up_staging_file_and_releases_lock() { + let tmp = TempDirGuard::new("panic-unwind"); + let (part, before) = seed_existing(tmp.path()); + + let out = tmp.path().to_path_buf(); + let opts = AdjFactorsWriteOptions { + row_group_rows: 2, + ..AdjFactorsWriteOptions::default() + }; + let result = std::panic::catch_unwind(move || { + let base = day(2024, 3, 15); + let iter = (0..5_i32).map(move |i| { + if i == 3 { + panic!("simulated iterator panic after row-group flush"); + } + make_div_row(1, base + i * 30, 0.25, "USD", 1.0, 1.01) + }); + let _ = write_adj_factors_dataset(&out, iter, opts); + }); + assert!(result.is_err(), "iterator must have panicked"); + + // Pre-existing live file stays byte-identical and both staging `.tmp` and `.write.lock` + // are removed during unwind. + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("adj_factors")); + + // Subsequent writer succeeds immediately without hanging on a stale lock. + let replacement = vec![make_div_row(99, day(2024, 6, 15), 0.75, "CAD", 1.0, 1.02)]; + let stats = + write_adj_factors_dataset(tmp.path(), &replacement, AdjFactorsWriteOptions::default()) + .unwrap(); + assert_eq!(stats.rows_written, 1); + let got = read_parquet_rows(&part); + assert_eq!(got.len(), 1); + assert_row_bitwise_eq(&got[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("adj_factors")); +} + +#[test] +fn backup_unlink_failure_after_rename_restores_live_file_and_returns_error() { + let tmp = TempDirGuard::new("backup-unlink-fail"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![make_div_row(300, day(2024, 9, 15), 0.60, "CAD", 1.0, 1.02)]; + let observed_bak: Arc>> = Arc::new(Mutex::new(None)); + let observed_bak_clone = Arc::clone(&observed_bak); + + let err = write_adj_factors_dataset_with_hooks( + tmp.path(), + &replacement, + AdjFactorsWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + move |bak_path| { + *observed_bak_clone.lock().unwrap() = Some(bak_path.to_path_buf()); + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "simulated backup unlink failure", + )) + }, + ) + .unwrap_err(); + + let expected_bak = observed_bak + .lock() + .unwrap() + .clone() + .expect("backup unlink hook must be called"); + assert!( + matches!( + err, + ParquetAdjError::Io { ref path, ref source } + if path == &expected_bak + && source.kind() == std::io::ErrorKind::PermissionDenied + ), + "expected Io error on backup path, got {err:?}" + ); + assert_eq!( + fs::read(&part).unwrap(), + before, + "live part.parquet must be atomically restored from backup" + ); + assert_no_transient_files(&tmp.path().join("adj_factors")); +} + +#[test] +fn backup_unlink_and_restore_failure_reports_rollback_failed() { + let tmp = TempDirGuard::new("backup-rollback-fail"); + let (part, _before) = seed_existing(tmp.path()); + + let replacement = vec![make_div_row(300, day(2024, 9, 15), 0.60, "CAD", 1.0, 1.02)]; + let observed_bak: Arc>> = Arc::new(Mutex::new(None)); + let observed_bak_clone = Arc::clone(&observed_bak); + + let err = write_adj_factors_dataset_with_hooks( + tmp.path(), + &replacement, + AdjFactorsWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + move |bak_path| { + *observed_bak_clone.lock().unwrap() = Some(bak_path.to_path_buf()); + // Remove the backup before returning an error so the restore rename also fails. + let _ = fs::remove_file(bak_path); + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "simulated backup unlink failure", + )) + }, + ) + .unwrap_err(); + + let expected_bak = observed_bak + .lock() + .unwrap() + .clone() + .expect("backup unlink hook must be called"); + match err { + ParquetAdjError::RollbackFailed { cause, failures } => { + assert!( + matches!( + *cause, + ParquetAdjError::Io { ref path, ref source } + if path == &expected_bak + && source.kind() == std::io::ErrorKind::PermissionDenied + ), + "unexpected cause: {cause:?}" + ); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].final_path, part); + assert_eq!( + failures[0].backup_path.as_deref(), + Some(expected_bak.as_path()) + ); + assert_eq!(failures[0].source.kind(), std::io::ErrorKind::NotFound); + } + other => panic!("expected RollbackFailed, got {other:?}"), + } + assert_no_transient_files(&tmp.path().join("adj_factors")); +} diff --git a/tools/curate-etl/src/parquet_bars.rs b/tools/curate-etl/src/parquet_bars.rs index 16c8833e..5367748e 100644 --- a/tools/curate-etl/src/parquet_bars.rs +++ b/tools/curate-etl/src/parquet_bars.rs @@ -18,44 +18,37 @@ use std::borrow::{Borrow, Cow}; use std::cmp::Ordering; -use std::collections::{BTreeMap, HashMap}; +use std::collections::BTreeMap; use std::error::Error; use std::fmt; -use std::fs::{self, File, OpenOptions}; +use std::fs::{self, File}; use std::io::{self, BufWriter, Write}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; -use std::sync::{Arc, Mutex, OnceLock}; -use std::thread; -use std::time::{Duration, Instant}; +use std::sync::Arc; +use std::time::Duration; use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; -use parquet::column::writer::ColumnWriter; use parquet::data_type::ByteArray; use parquet::errors::ParquetError; use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; use parquet::file::writer::SerializedFileWriter; use parquet::schema::types::{ColumnPath, Type, TypePtr}; +use crate::parquet_publish::{ + cleanup_owned_files, create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, + next_run_id, rollback_published, write_f64_col, write_i32_col, write_i64_col, + write_interned_str_col, DatasetFileLock, PublishIoError, PublishedPartition, StringInterner, + DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, +}; +pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; use crate::shorts::epoch_days_to_ymd; -/// Default maximum number of rows buffered per Parquet row group. -pub const DEFAULT_ROW_GROUP_ROWS: usize = 1_000_000; - -/// Default Zstd compression level for `bars_1d` Parquet files. -pub const DEFAULT_ZSTD_LEVEL: i32 = 3; - /// Minimum allowed calendar year for `session_date` partitioning. pub const MIN_PARQUET_YEAR: i32 = 1900; /// Maximum allowed calendar year for `session_date` partitioning. pub const MAX_PARQUET_YEAR: i32 = 2200; -const STRING_WRITE_BATCH_ROWS: usize = 4_096; -const FILE_BUF_CAPACITY_BYTES: usize = 64 * 1024; -const LINEAR_INTERN_LIMIT: usize = 8; -const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30); - /// Single `bars_1d` row matching the `design/DATA-CONTRACTS.md` Parquet schema. #[derive(Debug, Clone, PartialEq)] pub struct Bars1dParquetRow { @@ -99,34 +92,6 @@ pub struct Bars1dWriteStats { pub rows_by_year: BTreeMap, } -/// Single failure encountered while rolling back a partial publication. -#[derive(Debug)] -pub struct RollbackFailure { - pub final_path: PathBuf, - pub backup_path: Option, - pub source: io::Error, -} - -impl fmt::Display for RollbackFailure { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match &self.backup_path { - Some(bak) => write!( - f, - "partition '{}' (backup '{}'): {}", - self.final_path.display(), - bak.display(), - self.source - ), - None => write!( - f, - "partition '{}': {}", - self.final_path.display(), - self.source - ), - } - } -} - /// Typed error returned by [`write_bars_1d_dataset`]. #[derive(Debug)] pub enum ParquetBarsError { @@ -242,6 +207,15 @@ impl Error for ParquetBarsError { } } +impl From for ParquetBarsError { + fn from(err: PublishIoError) -> Self { + match err { + PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, + PublishIoError::Io { path, source } => Self::Io { path, source }, + } + } +} + /// Builds the exact 12-column Parquet schema for `bars_1d` per `design/DATA-CONTRACTS.md`. pub fn bars_1d_parquet_schema() -> Result { let fields: Vec = vec![ @@ -330,54 +304,6 @@ fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { ) } -#[derive(Default)] -struct StringInterner { - values: Vec, - index: HashMap, -} - -impl StringInterner { - fn intern(&mut self, s: &str) -> u32 { - if self.values.len() <= LINEAR_INTERN_LIMIT { - let bytes = s.as_bytes(); - for (idx, existing) in self.values.iter().enumerate() { - if existing.data() == bytes { - return idx as u32; - } - } - let id = self.values.len() as u32; - self.values.push(ByteArray::from(s)); - if self.values.len() > LINEAR_INTERN_LIMIT { - self.index.reserve(self.values.len()); - for (i, val) in self.values.iter().enumerate() { - if let Ok(text) = std::str::from_utf8(val.data()) { - self.index.insert(text.to_owned(), i as u32); - } - } - } - return id; - } - - if let Some(&id) = self.index.get(s) { - return id; - } - let id = self.values.len() as u32; - self.values.push(ByteArray::from(s)); - self.index.insert(s.to_owned(), id); - id - } - - #[inline] - fn get(&self, id: u32) -> &ByteArray { - &self.values[id as usize] - } - - fn clear(&mut self) { - self.values.clear(); - self.index.clear(); - } -} - #[derive(Default)] struct RowGroupBuffer { listing_id: Vec, @@ -447,177 +373,6 @@ impl RowGroupBuffer { } } -static DATASET_LOCKS: OnceLock>>>> = OnceLock::new(); -static WRITE_RUN_SEQ: AtomicU64 = AtomicU64::new(0); - -fn dataset_mutex(bars_dir: &Path) -> Arc> { - let key = fs::canonicalize(bars_dir).unwrap_or_else(|_| bars_dir.to_path_buf()); - let map_mutex = DATASET_LOCKS.get_or_init(|| Mutex::new(HashMap::new())); - let mut map = map_mutex.lock().unwrap_or_else(|err| err.into_inner()); - map.entry(key) - .or_insert_with(|| Arc::new(Mutex::new(()))) - .clone() -} - -struct DatasetFileLock { - path: PathBuf, -} - -impl DatasetFileLock { - fn acquire_with_timeout(bars_dir: &Path, timeout: Duration) -> Result { - let lock_path = bars_dir.join(".write.lock"); - let start = Instant::now(); - let mut backoff_ms = 2u64; - loop { - match OpenOptions::new() - .write(true) - .create_new(true) - .open(&lock_path) - { - Ok(mut file) => { - let _ = writeln!(file, "{}", std::process::id()); - let _ = file.sync_all(); - return Ok(Self { path: lock_path }); - } - Err(err) if err.kind() == io::ErrorKind::AlreadyExists => { - let elapsed = start.elapsed(); - if elapsed >= timeout { - return Err(ParquetBarsError::LockTimeout { - path: lock_path, - waited: elapsed, - }); - } - let remaining = timeout.saturating_sub(elapsed); - thread::sleep(Duration::from_millis(backoff_ms).min(remaining)); - backoff_ms = (backoff_ms * 2).min(25); - } - Err(source) => { - return Err(ParquetBarsError::Io { - path: lock_path, - source, - }); - } - } - } - } -} - -impl Drop for DatasetFileLock { - fn drop(&mut self) { - let _ = fs::remove_file(&self.path); - } -} - -fn next_run_id() -> String { - let seq = WRITE_RUN_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - format!("{}-{seq}", std::process::id()) -} - -fn create_exclusive_tmp_file( - year_dir: &Path, - run_id: &str, -) -> Result<(PathBuf, File), ParquetBarsError> { - for attempt in 0..1024u32 { - let file_name = if attempt == 0 { - format!("part.parquet.{run_id}.tmp") - } else { - format!("part.parquet.{run_id}.{attempt}.tmp") - }; - let tmp_path = year_dir.join(file_name); - match OpenOptions::new() - .write(true) - .create_new(true) - .open(&tmp_path) - { - Ok(file) => return Ok((tmp_path, file)), - Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, - Err(source) => { - return Err(ParquetBarsError::Io { - path: tmp_path, - source, - }); - } - } - } - Err(ParquetBarsError::Io { - path: year_dir.join(format!("part.parquet.{run_id}.tmp")), - source: io::Error::new( - io::ErrorKind::AlreadyExists, - "exhausted unique staging file names", - ), - }) -} - -fn is_hard_link_unsupported(err: &io::Error) -> bool { - matches!( - err.kind(), - io::ErrorKind::Unsupported | io::ErrorKind::PermissionDenied - ) -} - -fn copy_to_exclusive_backup(src: &Path, dst: &Path) -> io::Result<()> { - let mut dst_file = OpenOptions::new().write(true).create_new(true).open(dst)?; - let copy_res = (|| -> io::Result<()> { - let mut src_file = File::open(src)?; - io::copy(&mut src_file, &mut dst_file)?; - dst_file.sync_all()?; - Ok(()) - })(); - if let Err(err) = copy_res { - drop(dst_file); - let _ = fs::remove_file(dst); - return Err(err); - } - Ok(()) -} - -/// Creates a per-run rollback backup of `final_path` while keeping `final_path` intact on disk. -/// Uses an atomic hard link in the same directory when supported, falling back to an exclusive -/// file copy so readers never observe a missing `part.parquet` before replacement. -fn create_backup_preserving_live( - final_path: &Path, - run_id: &str, -) -> Result { - let parent = final_path.parent().unwrap_or_else(|| Path::new(".")); - for attempt in 0..1024u32 { - let file_name = if attempt == 0 { - format!("part.parquet.{run_id}.bak") - } else { - format!("part.parquet.{run_id}.{attempt}.bak") - }; - let bak_path = parent.join(file_name); - match fs::hard_link(final_path, &bak_path) { - Ok(()) => return Ok(bak_path), - Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, - Err(err) if is_hard_link_unsupported(&err) => { - match copy_to_exclusive_backup(final_path, &bak_path) { - Ok(()) => return Ok(bak_path), - Err(copy_err) if copy_err.kind() == io::ErrorKind::AlreadyExists => continue, - Err(source) => { - return Err(ParquetBarsError::Io { - path: bak_path, - source, - }); - } - } - } - Err(source) => { - return Err(ParquetBarsError::Io { - path: bak_path, - source, - }); - } - } - } - Err(ParquetBarsError::Io { - path: parent.join(format!("part.parquet.{run_id}.bak")), - source: io::Error::new( - io::ErrorKind::AlreadyExists, - "exhausted unique backup file names", - ), - }) -} - struct YearWriter { tmp_path: PathBuf, final_path: PathBuf, @@ -678,46 +433,46 @@ impl YearWriter { let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; // 1. listing_id (INT32, REQUIRED) - write_i32_col(&mut rg_writer, &self.buf.listing_id, &self.tmp_path)?; + write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; // 2. ts (INT64, REQUIRED) - write_i64_col(&mut rg_writer, &self.buf.ts_micros, &self.tmp_path)?; + write_i64_col(&mut rg_writer, &self.buf.ts_micros).map_err(map_pq)?; // 3. session_date (INT32, REQUIRED) - write_i32_col(&mut rg_writer, &self.buf.session_date, &self.tmp_path)?; + write_i32_col(&mut rg_writer, &self.buf.session_date).map_err(map_pq)?; // 4. open (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.open, None, &self.tmp_path)?; + write_f64_col(&mut rg_writer, &self.buf.open, None).map_err(map_pq)?; // 5. high (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.high, None, &self.tmp_path)?; + write_f64_col(&mut rg_writer, &self.buf.high, None).map_err(map_pq)?; // 6. low (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.low, None, &self.tmp_path)?; + write_f64_col(&mut rg_writer, &self.buf.low, None).map_err(map_pq)?; // 7. close (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.close, None, &self.tmp_path)?; + write_f64_col(&mut rg_writer, &self.buf.close, None).map_err(map_pq)?; // 8. volume (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.volume, None, &self.tmp_path)?; + write_f64_col(&mut rg_writer, &self.buf.volume, None).map_err(map_pq)?; // 9. vwap (DOUBLE, OPTIONAL) write_f64_col( &mut rg_writer, &self.buf.vwap_values, Some(&self.buf.vwap_def_levels), - &self.tmp_path, - )?; + ) + .map_err(map_pq)?; // 10. currency (BYTE_ARRAY, REQUIRED) write_interned_str_col( &mut rg_writer, &self.buf.currency_ids, &self.buf.currency_interner, scratch, - &self.tmp_path, - )?; + ) + .map_err(map_pq)?; // 11. source (BYTE_ARRAY, REQUIRED) write_interned_str_col( &mut rg_writer, &self.buf.source_ids, &self.buf.source_interner, scratch, - &self.tmp_path, - )?; + ) + .map_err(map_pq)?; // 12. known_at (INT64, REQUIRED) - write_i64_col(&mut rg_writer, &self.buf.known_at_micros, &self.tmp_path)?; + write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; rg_writer.close().map_err(map_pq)?; @@ -778,182 +533,6 @@ struct SyncedYearFile { bytes: u64, } -fn next_column<'a>( - rg_writer: &'a mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, - path: &Path, -) -> Result, ParquetBarsError> { - match rg_writer.next_column() { - Ok(Some(col)) => Ok(col), - Ok(None) => Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source: ParquetError::General("unexpected end of Parquet schema columns".to_string()), - }), - Err(source) => Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - }), - } -} - -fn write_i32_col( - rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, - values: &[i32], - path: &Path, -) -> Result<(), ParquetBarsError> { - let mut col = next_column(rg_writer, path)?; - match col.untyped() { - ColumnWriter::Int32ColumnWriter(typed) => { - typed - .write_batch(values, None, None) - .map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - })?; - } - _ => { - return Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source: ParquetError::General("expected INT32 column writer".to_string()), - }); - } - } - col.close().map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - }) -} - -fn write_i64_col( - rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, - values: &[i64], - path: &Path, -) -> Result<(), ParquetBarsError> { - let mut col = next_column(rg_writer, path)?; - match col.untyped() { - ColumnWriter::Int64ColumnWriter(typed) => { - typed - .write_batch(values, None, None) - .map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - })?; - } - _ => { - return Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source: ParquetError::General("expected INT64 column writer".to_string()), - }); - } - } - col.close().map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - }) -} - -fn write_f64_col( - rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, - values: &[f64], - def_levels: Option<&[i16]>, - path: &Path, -) -> Result<(), ParquetBarsError> { - let mut col = next_column(rg_writer, path)?; - match col.untyped() { - ColumnWriter::DoubleColumnWriter(typed) => { - typed - .write_batch(values, def_levels, None) - .map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - })?; - } - _ => { - return Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source: ParquetError::General("expected DOUBLE column writer".to_string()), - }); - } - } - col.close().map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - }) -} - -fn write_interned_str_col( - rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, - ids: &[u32], - interner: &StringInterner, - scratch: &mut Vec, - path: &Path, -) -> Result<(), ParquetBarsError> { - let mut col = next_column(rg_writer, path)?; - match col.untyped() { - ColumnWriter::ByteArrayColumnWriter(typed) => { - for chunk in ids.chunks(STRING_WRITE_BATCH_ROWS) { - scratch.clear(); - for &id in chunk { - scratch.push(interner.get(id).clone()); - } - typed - .write_batch(scratch, None, None) - .map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - })?; - } - } - _ => { - return Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source: ParquetError::General("expected BYTE_ARRAY column writer".to_string()), - }); - } - } - col.close().map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - }) -} - -fn cleanup_owned_files(owned_paths: &[PathBuf]) { - for path in owned_paths { - let _ = fs::remove_file(path); - } -} - -struct PublishedPartition { - final_path: PathBuf, - backup_path: Option, -} - -fn rollback_published(published: &[PublishedPartition]) -> Vec { - let mut failures = Vec::new(); - for part in published.iter().rev() { - match &part.backup_path { - Some(bak) => { - if let Err(source) = fs::rename(bak, &part.final_path) { - failures.push(RollbackFailure { - final_path: part.final_path.clone(), - backup_path: Some(bak.clone()), - source, - }); - } - } - None => { - if let Err(source) = fs::remove_file(&part.final_path) { - failures.push(RollbackFailure { - final_path: part.final_path.clone(), - backup_path: None, - source, - }); - } - } - } - } - failures -} - fn finish_with_rollback( cause: ParquetBarsError, published: &[PublishedPartition], @@ -1159,7 +738,12 @@ where match create_backup_preserving_live(&file.final_path, &run_id) { Ok(bak) => Some(bak), Err(err) => { - return Err(finish_with_rollback(err, &published, None, &owned_tmp_paths)); + return Err(finish_with_rollback( + err.into(), + &published, + None, + &owned_tmp_paths, + )); } } } @@ -1223,6 +807,8 @@ where #[cfg(test)] mod tests { use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + use std::sync::Mutex; + use std::thread; use parquet::basic::ConvertedType; use parquet::column::reader::ColumnReader; diff --git a/tools/curate-etl/src/parquet_corporate_actions.rs b/tools/curate-etl/src/parquet_corporate_actions.rs new file mode 100644 index 00000000..b5abbb7a --- /dev/null +++ b/tools/curate-etl/src/parquet_corporate_actions.rs @@ -0,0 +1,1879 @@ +//! Streaming, atomic Zstd Parquet writer for `corporate_actions`. +//! +//! Writes `/corporate_actions/part.parquet` matching the 11-column contract schema in +//! `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `ex_date` (`INT32`, `REQUIRED`, `DATE`) +//! 3. `declared_date` (`INT32`, `OPTIONAL`, `DATE`) +//! 4. `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 5. `ratio` (`DOUBLE`, `OPTIONAL`) +//! 6. `cash_amount` (`DOUBLE`, `OPTIONAL`) +//! 7. `currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) +//! 8. `successor_listing_id` (`INT32`, `OPTIONAL`) +//! 9. `terminal_return` (`DOUBLE`, `OPTIONAL`) +//! 10. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 11. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use parquet::basic::{ + Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel, +}; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::corporate_actions::{CorporateActionKind, CorporateActionRow, KnownAtSource}; +use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; +use crate::parquet_publish::{ + create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, + write_i32_col, write_i64_col, write_interned_str_col, write_optional_f64_col, + write_optional_i32_col, write_optional_interned_str_col, DatasetFileLock, PublishIoError, + StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, + STRING_WRITE_BATCH_ROWS, +}; +pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; +use crate::shorts::epoch_days_to_ymd; + +/// Single `corporate_actions` row matching the `design/DATA-CONTRACTS.md` Parquet schema. +#[derive(Debug, Clone, PartialEq)] +pub struct CorporateActionsParquetRow { + pub listing_id: i32, + pub ex_date: i32, + pub declared_date: Option, + pub kind: CorporateActionKind, + pub ratio: Option, + pub cash_amount: Option, + pub currency: Option>, + pub successor_listing_id: Option, + pub terminal_return: Option, + pub known_at_micros: i64, + pub known_at_source: KnownAtSource, +} + +impl CorporateActionsParquetRow { + /// Builds a [`CorporateActionsParquetRow`] from a curated [`CorporateActionRow`] and a + /// caller-supplied UTC microsecond `known_at` timestamp. + #[inline] + pub fn from_corporate_action_row(row: &CorporateActionRow, known_at_micros: i64) -> Self { + Self { + listing_id: row.key, + ex_date: row.ex_date, + declared_date: row.declared_date, + kind: row.kind, + ratio: row.ratio, + cash_amount: row.cash_amount, + currency: row.currency.clone().map(Cow::Owned), + successor_listing_id: row.successor_key, + terminal_return: row.terminal_return, + known_at_micros, + known_at_source: row.known_at_source, + } + } +} + +/// Configuration for [`write_corporate_actions_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CorporateActionsWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for CorporateActionsWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_corporate_actions_dataset`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CorporateActionsWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, +} + +/// Typed offending value carried by [`ParquetCorporateActionsError::ForbiddenFieldForKind`]. +#[derive(Debug, Clone, PartialEq)] +pub enum ForbiddenFieldValue { + Float(f64), + Int(i32), + String(String), +} + +impl fmt::Display for ForbiddenFieldValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Float(v) => write!(f, "{v}"), + Self::Int(v) => write!(f, "{v}"), + Self::String(v) => write!(f, "{v:?}"), + } + } +} + +/// Typed error returned by [`write_corporate_actions_dataset`]. +#[derive(Debug)] +pub enum ParquetCorporateActionsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + UnsortedInput { + prev_listing_id: i32, + prev_ex_date: i32, + prev_kind: CorporateActionKind, + listing_id: i32, + ex_date: i32, + kind: CorporateActionKind, + }, + ExDateOutOfRange { + listing_id: i32, + ex_date: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + DeclaredDateOutOfRange { + listing_id: i32, + ex_date: i32, + declared_date: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + InvalidRatio { + listing_id: i32, + ex_date: i32, + value: Option, + }, + InvalidCashAmount { + listing_id: i32, + ex_date: i32, + value: Option, + }, + InvalidCurrency { + listing_id: i32, + ex_date: i32, + value: Option, + }, + InvalidSuccessorListingId { + listing_id: i32, + ex_date: i32, + successor_listing_id: Option, + }, + InvalidTerminalReturn { + listing_id: i32, + ex_date: i32, + value: Option, + }, + ForbiddenFieldForKind { + listing_id: i32, + ex_date: i32, + kind: CorporateActionKind, + field: &'static str, + value: ForbiddenFieldValue, + }, + InconsistentKnownAtSource { + listing_id: i32, + ex_date: i32, + kind: CorporateActionKind, + known_at_source: KnownAtSource, + declared_date: Option, + }, + LockTimeout { + path: PathBuf, + waited: Duration, + }, + RollbackFailed { + cause: Box, + failures: Vec, + }, + Io { + path: PathBuf, + source: io::Error, + }, + Parquet { + path: PathBuf, + source: ParquetError, + }, +} + +impl fmt::Display for ParquetCorporateActionsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidRowGroupRows => { + write!(f, "invalid row_group_rows: must be greater than 0") + } + Self::InvalidZstdLevel { level } => { + write!(f, "invalid Zstd compression level: {level}") + } + Self::UnsortedInput { + prev_listing_id, + prev_ex_date, + prev_kind, + listing_id, + ex_date, + kind, + } => write!( + f, + "unsorted input: ({listing_id}, {ex_date}, {kind}) follows ({prev_listing_id}, {prev_ex_date}, {prev_kind})" + ), + Self::ExDateOutOfRange { + listing_id, + ex_date, + year, + min_year, + max_year, + } => write!( + f, + "ex_date {ex_date} (year {year}) for listing_id {listing_id} is outside supported range [{min_year}, {max_year}]" + ), + Self::DeclaredDateOutOfRange { + listing_id, + ex_date, + declared_date, + year, + min_year, + max_year, + } => write!( + f, + "declared_date {declared_date} (year {year}) for ({listing_id}, {ex_date}) is outside supported range [{min_year}, {max_year}]" + ), + Self::InvalidRatio { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid split ratio {value:?} for ({listing_id}, {ex_date}): must be Some(finite > 0)" + ), + Self::InvalidCashAmount { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid dividend cash_amount {value:?} for ({listing_id}, {ex_date}): must be Some(finite > 0)" + ), + Self::InvalidCurrency { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid dividend currency {value:?} for ({listing_id}, {ex_date}): must be Some(non-empty)" + ), + Self::InvalidSuccessorListingId { + listing_id, + ex_date, + successor_listing_id, + } => write!( + f, + "invalid successor_listing_id {successor_listing_id:?} for ({listing_id}, {ex_date}): must be Some(id != {listing_id})" + ), + Self::InvalidTerminalReturn { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid terminal_return {value:?} for ({listing_id}, {ex_date}): must be Some(finite in [-1.0, 0.0])" + ), + Self::ForbiddenFieldForKind { + listing_id, + ex_date, + kind, + field, + value, + } => write!( + f, + "field '{field}' (value {value}) must be None for kind '{kind}' on ({listing_id}, {ex_date})" + ), + Self::InconsistentKnownAtSource { + listing_id, + ex_date, + kind, + known_at_source, + declared_date, + } => write!( + f, + "inconsistent known_at_source '{known_at_source}' for kind '{kind}' (declared_date={declared_date:?}) on ({listing_id}, {ex_date})" + ), + Self::LockTimeout { path, waited } => write!( + f, + "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", + waited.as_millis(), + path.display() + ), + Self::RollbackFailed { cause, failures } => { + write!( + f, + "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", + failures.len() + )?; + for failure in failures { + write!(f, " [{failure}]")?; + } + Ok(()) + } + Self::Io { path, source } => { + write!(f, "I/O error at '{}': {source}", path.display()) + } + Self::Parquet { path, source } => { + write!(f, "Parquet error at '{}': {source}", path.display()) + } + } + } +} + +impl Error for ParquetCorporateActionsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::Io { source, .. } => Some(source), + Self::Parquet { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for ParquetCorporateActionsError { + fn from(err: PublishIoError) -> Self { + match err { + PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, + PublishIoError::Io { path, source } => Self::Io { path, source }, + } + } +} + +/// Builds the exact 11-column Parquet schema for `corporate_actions` per +/// `design/DATA-CONTRACTS.md` (§3A). +pub fn corporate_actions_parquet_schema() -> Result { + let fields: Vec = vec![ + Arc::new( + Type::primitive_type_builder("listing_id", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ex_date", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("declared_date", PhysicalType::INT32) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("kind", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ratio", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("cash_amount", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("successor_listing_id", PhysicalType::INT32) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("terminal_return", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("corporate_actions") + .with_fields(fields) + .build()?, + )) +} + +fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { + Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(zstd_level)) + .set_column_dictionary_enabled(ColumnPath::from("kind"), true) + .set_column_dictionary_enabled(ColumnPath::from("currency"), true) + .set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn check_forbidden_none( + row: &CorporateActionsParquetRow, + value: &Option, + field: &'static str, + to_value: impl FnOnce(&T) -> ForbiddenFieldValue, +) -> Result<(), ParquetCorporateActionsError> { + if let Some(v) = value { + return Err(ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: row.listing_id, + ex_date: row.ex_date, + kind: row.kind, + field, + value: to_value(v), + }); + } + Ok(()) +} + +#[inline] +fn validate_row(row: &CorporateActionsParquetRow) -> Result<(), ParquetCorporateActionsError> { + let (ex_year, _, _) = epoch_days_to_ymd(row.ex_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&ex_year) { + return Err(ParquetCorporateActionsError::ExDateOutOfRange { + listing_id: row.listing_id, + ex_date: row.ex_date, + year: ex_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + + if let Some(declared_date) = row.declared_date { + let (decl_year, _, _) = epoch_days_to_ymd(declared_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&decl_year) { + return Err(ParquetCorporateActionsError::DeclaredDateOutOfRange { + listing_id: row.listing_id, + ex_date: row.ex_date, + declared_date, + year: decl_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + } + + match row.kind { + CorporateActionKind::Split => { + match row.ratio { + Some(r) if r.is_finite() && r > 0.0 => {} + other => { + return Err(ParquetCorporateActionsError::InvalidRatio { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: other, + }); + } + } + check_forbidden_none(row, &row.cash_amount, "cash_amount", |&v| { + ForbiddenFieldValue::Float(v) + })?; + check_forbidden_none(row, &row.currency, "currency", |v| { + ForbiddenFieldValue::String(v.as_ref().to_owned()) + })?; + check_forbidden_none( + row, + &row.successor_listing_id, + "successor_listing_id", + |&v| ForbiddenFieldValue::Int(v), + )?; + check_forbidden_none(row, &row.terminal_return, "terminal_return", |&v| { + ForbiddenFieldValue::Float(v) + })?; + } + CorporateActionKind::Dividend => { + match row.cash_amount { + Some(c) if c.is_finite() && c > 0.0 => {} + other => { + return Err(ParquetCorporateActionsError::InvalidCashAmount { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: other, + }); + } + } + match row.currency.as_deref() { + Some(curr) if !curr.trim().is_empty() => {} + other => { + return Err(ParquetCorporateActionsError::InvalidCurrency { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: other.map(str::to_owned), + }); + } + } + check_forbidden_none(row, &row.ratio, "ratio", |&v| ForbiddenFieldValue::Float(v))?; + check_forbidden_none( + row, + &row.successor_listing_id, + "successor_listing_id", + |&v| ForbiddenFieldValue::Int(v), + )?; + check_forbidden_none(row, &row.terminal_return, "terminal_return", |&v| { + ForbiddenFieldValue::Float(v) + })?; + } + CorporateActionKind::OtcDelistTransfer => { + match row.successor_listing_id { + Some(succ) if succ != row.listing_id => {} + other => { + return Err(ParquetCorporateActionsError::InvalidSuccessorListingId { + listing_id: row.listing_id, + ex_date: row.ex_date, + successor_listing_id: other, + }); + } + } + check_forbidden_none(row, &row.ratio, "ratio", |&v| ForbiddenFieldValue::Float(v))?; + check_forbidden_none(row, &row.cash_amount, "cash_amount", |&v| { + ForbiddenFieldValue::Float(v) + })?; + check_forbidden_none(row, &row.currency, "currency", |v| { + ForbiddenFieldValue::String(v.as_ref().to_owned()) + })?; + check_forbidden_none(row, &row.terminal_return, "terminal_return", |&v| { + ForbiddenFieldValue::Float(v) + })?; + } + CorporateActionKind::Delisting => { + match row.terminal_return { + Some(r) if r.is_finite() && (-1.0..=0.0).contains(&r) => {} + other => { + return Err(ParquetCorporateActionsError::InvalidTerminalReturn { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: other, + }); + } + } + check_forbidden_none(row, &row.ratio, "ratio", |&v| ForbiddenFieldValue::Float(v))?; + check_forbidden_none(row, &row.cash_amount, "cash_amount", |&v| { + ForbiddenFieldValue::Float(v) + })?; + check_forbidden_none(row, &row.currency, "currency", |v| { + ForbiddenFieldValue::String(v.as_ref().to_owned()) + })?; + check_forbidden_none( + row, + &row.successor_listing_id, + "successor_listing_id", + |&v| ForbiddenFieldValue::Int(v), + )?; + } + } + + let known_at_ok = match (row.kind, row.known_at_source) { + ( + CorporateActionKind::Split | CorporateActionKind::Dividend, + KnownAtSource::DeclaredDate, + ) => row.declared_date.is_some(), + ( + CorporateActionKind::Split | CorporateActionKind::Dividend, + KnownAtSource::ExDateFallback, + ) => true, + ( + CorporateActionKind::OtcDelistTransfer | CorporateActionKind::Delisting, + KnownAtSource::DelistDate, + ) => true, + _ => false, + }; + if !known_at_ok { + return Err(ParquetCorporateActionsError::InconsistentKnownAtSource { + listing_id: row.listing_id, + ex_date: row.ex_date, + kind: row.kind, + known_at_source: row.known_at_source, + declared_date: row.declared_date, + }); + } + + Ok(()) +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + ex_date: Vec, + declared_date_vals: Vec, + declared_date_def_levels: Vec, + kind_ids: Vec, + kind_interner: StringInterner, + ratio_vals: Vec, + ratio_def_levels: Vec, + cash_amount_vals: Vec, + cash_amount_def_levels: Vec, + currency_ids: Vec, + currency_def_levels: Vec, + currency_interner: StringInterner, + successor_listing_id_vals: Vec, + successor_listing_id_def_levels: Vec, + terminal_return_vals: Vec, + terminal_return_def_levels: Vec, + known_at_micros: Vec, + known_at_source_ids: Vec, + known_at_source_interner: StringInterner, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &CorporateActionsParquetRow) { + self.listing_id.push(row.listing_id); + self.ex_date.push(row.ex_date); + + match row.declared_date { + Some(d) => { + self.declared_date_vals.push(d); + self.declared_date_def_levels.push(1); + } + None => self.declared_date_def_levels.push(0), + } + + let kind_id = self.kind_interner.intern(row.kind.as_str()); + self.kind_ids.push(kind_id); + + match row.ratio { + Some(r) => { + self.ratio_vals.push(r); + self.ratio_def_levels.push(1); + } + None => self.ratio_def_levels.push(0), + } + + match row.cash_amount { + Some(c) => { + self.cash_amount_vals.push(c); + self.cash_amount_def_levels.push(1); + } + None => self.cash_amount_def_levels.push(0), + } + + match row.currency.as_deref() { + Some(curr) => { + let id = self.currency_interner.intern(curr); + self.currency_ids.push(id); + self.currency_def_levels.push(1); + } + None => self.currency_def_levels.push(0), + } + + match row.successor_listing_id { + Some(succ) => { + self.successor_listing_id_vals.push(succ); + self.successor_listing_id_def_levels.push(1); + } + None => self.successor_listing_id_def_levels.push(0), + } + + match row.terminal_return { + Some(tr) => { + self.terminal_return_vals.push(tr); + self.terminal_return_def_levels.push(1); + } + None => self.terminal_return_def_levels.push(0), + } + + self.known_at_micros.push(row.known_at_micros); + + let src_id = self + .known_at_source_interner + .intern(row.known_at_source.as_str()); + self.known_at_source_ids.push(src_id); + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.ex_date.clear(); + self.declared_date_vals.clear(); + self.declared_date_def_levels.clear(); + self.kind_ids.clear(); + self.kind_interner.clear(); + self.ratio_vals.clear(); + self.ratio_def_levels.clear(); + self.cash_amount_vals.clear(); + self.cash_amount_def_levels.clear(); + self.currency_ids.clear(); + self.currency_def_levels.clear(); + self.currency_interner.clear(); + self.successor_listing_id_vals.clear(); + self.successor_listing_id_def_levels.clear(); + self.terminal_return_vals.clear(); + self.terminal_return_def_levels.clear(); + self.known_at_micros.clear(); + self.known_at_source_ids.clear(); + self.known_at_source_interner.clear(); + } +} + +struct CorporateActionsFileWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl CorporateActionsFileWriter { + fn from_file( + tmp_path: PathBuf, + final_path: PathBuf, + file: File, + schema: &TypePtr, + props: &WriterPropertiesPtr, + ) -> Result { + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetCorporateActionsError::Parquet { + path: tmp_path.clone(), + source, + }, + )?; + + Ok(Self { + tmp_path, + final_path, + writer, + buf: RowGroupBuffer::default(), + rows_written: 0, + row_groups_written: 0, + }) + } + + fn flush_row_group( + &mut self, + scratch: &mut Vec, + ) -> Result<(), ParquetCorporateActionsError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetCorporateActionsError::Parquet { + path: self.tmp_path.clone(), + source, + }; + + let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; + + // 1. listing_id (INT32, REQUIRED) + write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; + // 2. ex_date (INT32, REQUIRED, DATE) + write_i32_col(&mut rg_writer, &self.buf.ex_date).map_err(map_pq)?; + // 3. declared_date (INT32, OPTIONAL, DATE) + write_optional_i32_col( + &mut rg_writer, + &self.buf.declared_date_vals, + &self.buf.declared_date_def_levels, + ) + .map_err(map_pq)?; + // 4. kind (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.kind_ids, + &self.buf.kind_interner, + scratch, + ) + .map_err(map_pq)?; + // 5. ratio (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ratio_vals, + &self.buf.ratio_def_levels, + ) + .map_err(map_pq)?; + // 6. cash_amount (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.cash_amount_vals, + &self.buf.cash_amount_def_levels, + ) + .map_err(map_pq)?; + // 7. currency (BYTE_ARRAY, OPTIONAL, STRING) + write_optional_interned_str_col( + &mut rg_writer, + &self.buf.currency_ids, + &self.buf.currency_def_levels, + &self.buf.currency_interner, + scratch, + ) + .map_err(map_pq)?; + // 8. successor_listing_id (INT32, OPTIONAL) + write_optional_i32_col( + &mut rg_writer, + &self.buf.successor_listing_id_vals, + &self.buf.successor_listing_id_def_levels, + ) + .map_err(map_pq)?; + // 9. terminal_return (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.terminal_return_vals, + &self.buf.terminal_return_def_levels, + ) + .map_err(map_pq)?; + // 10. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; + // 11. known_at_source (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.known_at_source_ids, + &self.buf.known_at_source_interner, + scratch, + ) + .map_err(map_pq)?; + + rg_writer.close().map_err(map_pq)?; + + self.rows_written += row_count; + self.row_groups_written += 1; + self.buf.clear(); + Ok(()) + } + + fn finish_and_sync( + mut self, + scratch: &mut Vec, + ) -> Result { + self.flush_row_group(scratch)?; + + let mut buf_writer = + self.writer + .into_inner() + .map_err(|source| ParquetCorporateActionsError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer + .flush() + .map_err(|source| ParquetCorporateActionsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetCorporateActionsError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all() + .map_err(|source| ParquetCorporateActionsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetCorporateActionsError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedCorporateActionsFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedCorporateActionsFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +/// Streams non-decreasing `(listing_id, ex_date, kind)` rows into a single Zstd Parquet file +/// at `/corporate_actions/part.parquet`. +/// +/// Multiple rows may share the same `(listing_id, ex_date, kind)` key (for example, two separate +/// cash dividends on the same ex-date). +/// +/// # Empty Input +/// Empty input returns `Ok(CorporateActionsWriteStats::default())` without creating +/// `/corporate_actions` and without modifying or removing any pre-existing `part.parquet`. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/corporate_actions` directory are serialized +/// via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. The file +/// is written to an exclusively created per-run staging file (`part.parquet..tmp`), flushed, +/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists, +/// a live-preserving backup (`part.parquet..bak`) is created via hard link (or exclusive +/// copy fallback) so readers never observe a missing `part.parquet` before replacement by a +/// single atomic `rename`. On any error, the writer is dropped, any backup created by this run +/// is cleaned up (reporting cleanup failures via [`ParquetCorporateActionsError::RollbackFailed`]), +/// and only staging files owned by this run are unlinked. +pub fn write_corporate_actions_dataset( + out_dir: P, + rows: I, + options: CorporateActionsWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_corporate_actions_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _| {}, + |path| fs::remove_file(path), + ) +} + +fn write_corporate_actions_dataset_with_hooks( + out_dir: P, + rows: I, + options: CorporateActionsWriteOptions, + lock_timeout: Duration, + mut on_after_backup: F, + mut remove_backup: Rm, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(&Path, Option<&Path>), + Rm: FnMut(&Path) -> io::Result<()>, +{ + if options.row_group_rows == 0 { + return Err(ParquetCorporateActionsError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetCorporateActionsError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(CorporateActionsWriteStats::default()); + }; + validate_row(first_item.borrow())?; + + let out_dir = out_dir.as_ref(); + let dataset_dir = out_dir.join("corporate_actions"); + let schema = corporate_actions_parquet_schema().map_err(|source| { + ParquetCorporateActionsError::Parquet { + path: dataset_dir.clone(), + source, + } + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&dataset_dir).map_err(|source| ParquetCorporateActionsError::Io { + path: dataset_dir.clone(), + source, + })?; + + // Serialize writers targeting the same dataset directory across threads and processes. + // Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held, + // and only after all staging/publication/rollback work has finished. + let dataset_mu = dataset_mutex(&dataset_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire_with_timeout(&dataset_dir, lock_timeout)?; + + let run_id = next_run_id(); + let (tmp_path, tmp_file) = create_exclusive_tmp_file(&dataset_dir, &run_id)?; + // Declared before `file_writer` so Rust's reverse drop order closes the file handle + // before the guard unlinks the staging file on error or panic unwind, while `_file_lock` + // and `_in_process_guard` are still held. + let mut staging_guard = StagingFileGuard::new(tmp_path.clone()); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let mut file_writer = Some(CorporateActionsFileWriter::from_file( + tmp_path, + dataset_dir.join("part.parquet"), + tmp_file, + &schema, + &props, + )?); + + let synced = { + let mut prev_key: Option<(i32, i32, CorporateActionKind)> = None; + let writer = file_writer.as_mut().expect("writer initialized"); + + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + // Validate row fields before checking sort order so e.g. an out-of-range + // ex_date is reported as ExDateOutOfRange rather than UnsortedInput. + validate_row(row)?; + let key = (row.listing_id, row.ex_date, row.kind); + if let Some((prev_listing_id, prev_ex_date, prev_kind)) = prev_key { + if key.cmp(&(prev_listing_id, prev_ex_date, prev_kind)) == Ordering::Less { + return Err(ParquetCorporateActionsError::UnsortedInput { + prev_listing_id, + prev_ex_date, + prev_kind, + listing_id: row.listing_id, + ex_date: row.ex_date, + kind: row.kind, + }); + } + } + prev_key = Some(key); + + writer.buf.push(row); + if writer.buf.len() == options.row_group_rows { + writer.flush_row_group(&mut scratch)?; + } + } + + let writer = file_writer.take().expect("writer still present"); + writer.finish_and_sync(&mut scratch)? + }; + + let backup_path = match fs::symlink_metadata(&synced.final_path) { + Ok(meta) if !meta.is_dir() => { + Some(create_backup_preserving_live(&synced.final_path, &run_id)?) + } + // Directory occupying final_path: leave it in place so the rename below fails cleanly. + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + return Err(ParquetCorporateActionsError::Io { + path: synced.final_path, + source, + }); + } + }; + + on_after_backup(&synced.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&synced.tmp_path, &synced.final_path) { + // `synced.final_path` was never moved during backup creation, so it remains intact; + // remove the backup created for this run. `staging_guard` unlinks our staging file on drop. + let backup_remove_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak) + .err() + .map(|remove_err| RollbackFailure { + final_path: synced.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let cause = ParquetCorporateActionsError::Io { + path: synced.final_path, + source, + }; + return match backup_remove_failure { + Some(failure) => Err(ParquetCorporateActionsError::RollbackFailed { + cause: Box::new(cause), + failures: vec![failure], + }), + None => Err(cause), + }; + } + + staging_guard.disarm(); + + if let Some(bak) = backup_path { + if let Err(remove_err) = remove_backup(&bak) { + let cause = ParquetCorporateActionsError::Io { + path: bak.clone(), + source: remove_err, + }; + return match fs::rename(&bak, &synced.final_path) { + Ok(()) => Err(cause), + Err(restore_err) => Err(ParquetCorporateActionsError::RollbackFailed { + cause: Box::new(cause), + failures: vec![RollbackFailure { + final_path: synced.final_path, + backup_path: Some(bak), + source: restore_err, + }], + }), + }; + } + } + + Ok(CorporateActionsWriteStats { + rows_written: synced.rows_written, + files_written: 1, + row_groups_written: synced.row_groups_written, + bytes_written: synced.bytes, + }) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + + use parquet::basic::ConvertedType; + use parquet::column::reader::ColumnReader; + use parquet::file::reader::{FileReader, SerializedFileReader}; + + use super::*; + use crate::corporate_actions::{ + build_corporate_actions, DelistingOutcomeEvent, DividendActionEvent, SplitActionEvent, + }; + use crate::split::ymd_to_epoch_days; + + static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + + pub(super) struct TempDirGuard { + path: PathBuf, + } + + impl TempDirGuard { + pub(super) fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-corp-actions-test-{label}-{pid}-{seq}" + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + pub(super) fn path(&self) -> &Path { + &self.path + } + } + + impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + pub(super) fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") + } + + pub(super) fn known_at_from_day(d: i32) -> i64 { + i64::from(d) * 86_400_000_000 + 13 * 3_600_000_000 + 30 * 60_000_000 + } + + pub(super) fn make_split_row( + listing_id: i32, + ex_date: i32, + declared_date: Option, + ratio: f64, + ) -> CorporateActionsParquetRow { + let (known_at_day, known_at_source) = match declared_date { + Some(d) if d <= ex_date => (d, KnownAtSource::DeclaredDate), + _ => (ex_date, KnownAtSource::ExDateFallback), + }; + CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date, + kind: CorporateActionKind::Split, + ratio: Some(ratio), + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: None, + known_at_micros: known_at_from_day(known_at_day), + known_at_source, + } + } + + pub(super) fn make_div_row( + listing_id: i32, + ex_date: i32, + declared_date: Option, + cash_amount: f64, + currency: &'static str, + ) -> CorporateActionsParquetRow { + let (known_at_day, known_at_source) = match declared_date { + Some(d) if d <= ex_date => (d, KnownAtSource::DeclaredDate), + _ => (ex_date, KnownAtSource::ExDateFallback), + }; + CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date, + kind: CorporateActionKind::Dividend, + ratio: None, + cash_amount: Some(cash_amount), + currency: Some(Cow::Borrowed(currency)), + successor_listing_id: None, + terminal_return: None, + known_at_micros: known_at_from_day(known_at_day), + known_at_source, + } + } + + pub(super) fn make_otc_transfer_row( + listing_id: i32, + ex_date: i32, + successor_listing_id: i32, + ) -> CorporateActionsParquetRow { + CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date: None, + kind: CorporateActionKind::OtcDelistTransfer, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: Some(successor_listing_id), + terminal_return: None, + known_at_micros: known_at_from_day(ex_date), + known_at_source: KnownAtSource::DelistDate, + } + } + + pub(super) fn make_delisting_row( + listing_id: i32, + ex_date: i32, + terminal_return: f64, + ) -> CorporateActionsParquetRow { + CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date: None, + kind: CorporateActionKind::Delisting, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: Some(terminal_return), + known_at_micros: known_at_from_day(ex_date), + known_at_source: KnownAtSource::DelistDate, + } + } + + fn parse_kind(s: &str) -> CorporateActionKind { + match s { + "split" => CorporateActionKind::Split, + "dividend" => CorporateActionKind::Dividend, + "otc_delist_transfer" => CorporateActionKind::OtcDelistTransfer, + "delisting" => CorporateActionKind::Delisting, + other => panic!("unexpected kind string in Parquet: {other}"), + } + } + + fn parse_known_at_source(s: &str) -> KnownAtSource { + match s { + "declared_date" => KnownAtSource::DeclaredDate, + "ex_date_fallback" => KnownAtSource::ExDateFallback, + "delist_date" => KnownAtSource::DelistDate, + other => panic!("unexpected known_at_source string in Parquet: {other}"), + } + } + + pub(super) fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let read_i32 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i32"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + let read_opt_i32 = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(num_rows); + let mut def_levels = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, levels_read) = r + .read_records(num_rows, Some(&mut def_levels), None, &mut vals) + .expect("read optional i32"); + assert_eq!(read, num_rows); + assert_eq!(levels_read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + let mut val_idx = 0usize; + let mut result = Vec::with_capacity(num_rows); + for def in def_levels { + match def { + 0 => result.push(None), + 1 => { + result.push(Some(vals[val_idx])); + val_idx += 1; + } + other => panic!("unexpected definition level {other}"), + } + } + assert_eq!(val_idx, vals.len()); + result + }; + let read_i64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + let read_opt_f64 = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(num_rows); + let mut def_levels = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, levels_read) = r + .read_records(num_rows, Some(&mut def_levels), None, &mut vals) + .expect("read optional f64"); + assert_eq!(read, num_rows); + assert_eq!(levels_read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + let mut val_idx = 0usize; + let mut result = Vec::with_capacity(num_rows); + for def in def_levels { + match def { + 0 => result.push(None), + 1 => { + result.push(Some(vals[val_idx])); + val_idx += 1; + } + other => panic!("unexpected definition level {other}"), + } + } + assert_eq!(val_idx, vals.len()); + result + }; + let read_req_str = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read utf8"); + assert_eq!(read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + vals.into_iter() + .map(|ba| { + std::str::from_utf8(ba.data()) + .expect("valid utf8") + .to_owned() + }) + .collect() + }; + let read_opt_str = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(num_rows); + let mut def_levels = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, levels_read) = r + .read_records(num_rows, Some(&mut def_levels), None, &mut vals) + .expect("read optional utf8"); + assert_eq!(read, num_rows); + assert_eq!(levels_read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + let mut val_idx = 0usize; + let mut result = Vec::with_capacity(num_rows); + for def in def_levels { + match def { + 0 => result.push(None), + 1 => { + let text = std::str::from_utf8(vals[val_idx].data()) + .expect("valid utf8") + .to_owned(); + val_idx += 1; + result.push(Some(text)); + } + other => panic!("unexpected definition level {other}"), + } + } + assert_eq!(val_idx, vals.len()); + result + }; + + let listing_id = read_i32(0); + let ex_date = read_i32(1); + let declared_date = read_opt_i32(2); + let kind = read_req_str(3); + let ratio = read_opt_f64(4); + let cash_amount = read_opt_f64(5); + let currency = read_opt_str(6); + let successor_listing_id = read_opt_i32(7); + let terminal_return = read_opt_f64(8); + let known_at_micros = read_i64(9); + let known_at_source = read_req_str(10); + + for i in 0..num_rows { + out.push(CorporateActionsParquetRow { + listing_id: listing_id[i], + ex_date: ex_date[i], + declared_date: declared_date[i], + kind: parse_kind(&kind[i]), + ratio: ratio[i], + cash_amount: cash_amount[i], + currency: currency[i].clone().map(Cow::Owned), + successor_listing_id: successor_listing_id[i], + terminal_return: terminal_return[i], + known_at_micros: known_at_micros[i], + known_at_source: parse_known_at_source(&known_at_source[i]), + }); + } + } + out + } + + pub(super) fn assert_opt_f64_bitwise_eq(actual: Option, expected: Option) { + assert_eq!(actual.map(f64::to_bits), expected.map(f64::to_bits)); + } + + pub(super) fn assert_row_bitwise_eq( + actual: &CorporateActionsParquetRow, + expected: &CorporateActionsParquetRow, + ) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.ex_date, expected.ex_date); + assert_eq!(actual.declared_date, expected.declared_date); + assert_eq!(actual.kind, expected.kind); + assert_opt_f64_bitwise_eq(actual.ratio, expected.ratio); + assert_opt_f64_bitwise_eq(actual.cash_amount, expected.cash_amount); + assert_eq!(actual.currency, expected.currency); + assert_eq!(actual.successor_listing_id, expected.successor_listing_id); + assert_opt_f64_bitwise_eq(actual.terminal_return, expected.terminal_return); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + assert_eq!(actual.known_at_source, expected.known_at_source); + } + + pub(super) fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + for entry in fs::read_dir(dir).expect("read dir") { + let entry = entry.expect("dir entry"); + let name = entry.file_name().to_string_lossy().into_owned(); + assert!( + !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", + "unexpected transient file remaining: {}", + entry.path().display() + ); + } + } + + fn assert_contract_schema(schema: &Type) { + assert_eq!(schema.name(), "corporate_actions"); + let fields = schema.get_fields(); + assert_eq!(fields.len(), 11); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 11] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "ex_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "declared_date", + PhysicalType::INT32, + Repetition::OPTIONAL, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "kind", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "ratio", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "cash_amount", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "currency", + PhysicalType::BYTE_ARRAY, + Repetition::OPTIONAL, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "successor_listing_id", + PhysicalType::INT32, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "terminal_return", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "known_at_source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + let f = &fields[idx]; + assert_eq!(f.name(), name, "field {idx} name"); + assert_eq!(f.get_physical_type(), phys, "field {name} physical type"); + assert_eq!( + f.get_basic_info().repetition(), + rep, + "field {name} repetition" + ); + assert_eq!( + f.get_basic_info().logical_type_ref().cloned(), + logical, + "field {name} logical type" + ); + assert_eq!( + f.get_basic_info().converted_type(), + converted, + "field {name} converted type" + ); + } + } + + #[test] + fn schema_matches_contract_names_types_nullability_and_order() { + let schema = corporate_actions_parquet_schema().expect("build schema"); + assert_contract_schema(schema.as_ref()); + } + + #[test] + fn round_trip_all_kinds_same_date_dividends_multi_row_group_and_zstd_footer() { + let tmp = TempDirGuard::new("round-trip"); + let d_pre = day(1969, 12, 31); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 6, 10); + let d3 = day(2024, 9, 20); + let d4 = day(2025, 1, 15); + + let rows = vec![ + // Pre-1970 split with null declared_date (ex_date_fallback) + make_split_row(10, d_pre, None, 2.0), + // Split with declared_date <= ex_date + make_split_row(10, d2, Some(d2 - 20), 10.0), + // Two dividends on the exact same (listing_id, ex_date): regular + special + make_div_row(10, d2, Some(d2 - 14), 0.25, "USD"), + make_div_row(10, d2, None, 1.50, "USD"), + // Late declaration (declared_date > ex_date) falls back to ex_date_fallback + make_div_row(20, d1, Some(d1 + 5), 0.45, "CAD"), + // OTC delist transfer + make_otc_transfer_row(20, d3, 20_001), + // Terminal delisting at boundaries -1.0 and 0.0 + make_delisting_row(30, d4, -0.30), + make_delisting_row(31, d4, -1.0), + make_delisting_row(32, d4, 0.0), + ]; + + let opts = CorporateActionsWriteOptions { + row_group_rows: 3, + ..CorporateActionsWriteOptions::default() + }; + let stats = write_corporate_actions_dataset(tmp.path(), &rows, opts).unwrap(); + + assert_eq!(stats.rows_written, 9); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 3); + assert!(stats.bytes_written > 0); + + let path = tmp.path().join("corporate_actions/part.parquet"); + assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written); + + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().num_rows(), 9); + assert_eq!(meta.num_row_groups(), 3); + assert_contract_schema(meta.file_metadata().schema()); + + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} expected ZSTD, got {:?}", + col.column_path(), + col.compression() + ); + } + } + + let actual = read_parquet_rows(&path); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } + assert_eq!(actual[0].ex_date, -1); + assert_eq!(actual[0].declared_date, None); + assert_eq!(actual[4].declared_date, Some(d1 + 5)); + assert_eq!(actual[4].known_at_source, KnownAtSource::ExDateFallback); + assert_no_transient_files(&tmp.path().join("corporate_actions")); + } + + #[test] + fn build_corporate_actions_converts_and_writes_without_resorting() { + let tmp = TempDirGuard::new("from-builder"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 6, 10); + let d3 = day(2024, 9, 20); + + let splits = vec![ + ( + 101i32, + SplitActionEvent { + ex_date: d2, + ratio: 10.0, + declared_date: Some(d2 - 19), + }, + ), + ( + 101i32, + SplitActionEvent { + ex_date: d1, + ratio: 1.0, // no-op dropped by builder + declared_date: None, + }, + ), + ]; + let dividends = vec![ + ( + 101i32, + DividendActionEvent { + ex_date: d2, + cash: 0.10, + currency: "USD".to_string(), + declared_date: Some(d2 - 14), + }, + ), + ( + 101i32, + DividendActionEvent { + ex_date: d2, + cash: 0.50, + currency: "USD".to_string(), + declared_date: None, + }, + ), + ( + 202i32, + DividendActionEvent { + ex_date: d1, + cash: 0.90, + currency: "CAD".to_string(), + declared_date: Some(d1 + 3), // late declaration -> ExDateFallback + }, + ), + ]; + let delistings = vec![ + ( + 202i32, + DelistingOutcomeEvent { + delist_date: d3, + successor_key: Some(20_201), + terminal_return: None, + }, + ), + ( + 303i32, + DelistingOutcomeEvent { + delist_date: d3, + successor_key: None, + terminal_return: Some(-0.30), + }, + ), + ]; + + let built = build_corporate_actions(splits, dividends, delistings).unwrap(); + let rows: Vec = built + .rows + .iter() + .map(|r| { + CorporateActionsParquetRow::from_corporate_action_row( + r, + known_at_from_day(r.known_at_date), + ) + }) + .collect(); + assert_eq!(rows.len(), 6); + + let stats = write_corporate_actions_dataset( + tmp.path(), + &rows, + CorporateActionsWriteOptions { + row_group_rows: 2, + ..CorporateActionsWriteOptions::default() + }, + ) + .unwrap(); + assert_eq!(stats.rows_written, 6); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 3); + + let actual = read_parquet_rows(&tmp.path().join("corporate_actions/part.parquet")); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("corporate_actions")); + } + + #[test] + fn empty_input_creates_nothing_and_preserves_existing_part_parquet() { + let tmp = TempDirGuard::new("empty"); + let fresh = tmp.path().join("fresh"); + let stats = write_corporate_actions_dataset( + &fresh, + std::iter::empty::(), + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats, CorporateActionsWriteStats::default()); + assert!(!fresh.exists(), "empty input must not create out_dir"); + + let seeded = tmp.path().join("seeded"); + let seed_rows = vec![make_div_row(10, day(2024, 3, 15), None, 0.25, "USD")]; + write_corporate_actions_dataset( + &seeded, + &seed_rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + let part = seeded.join("corporate_actions/part.parquet"); + let before = fs::read(&part).unwrap(); + + let empty_stats = write_corporate_actions_dataset( + &seeded, + std::iter::empty::(), + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_stats, CorporateActionsWriteStats::default()); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&seeded.join("corporate_actions")); + } + + #[test] + fn determinism_identical_rows_produce_byte_identical_files() { + let tmp = TempDirGuard::new("determinism"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 6, 10); + let rows = vec![ + make_split_row(1, d1, Some(d1 - 14), 4.0), + make_div_row(1, d2, Some(d2 - 14), 0.25, "USD"), + make_otc_transfer_row(2, d2, 2001), + make_delisting_row(3, d2, -0.3), + ]; + + let out_a = tmp.path().join("a"); + let out_b = tmp.path().join("b"); + let opts = CorporateActionsWriteOptions { + row_group_rows: 2, + ..CorporateActionsWriteOptions::default() + }; + write_corporate_actions_dataset(&out_a, &rows, opts).unwrap(); + write_corporate_actions_dataset(&out_b, &rows, opts).unwrap(); + + let bytes_a = fs::read(out_a.join("corporate_actions/part.parquet")).unwrap(); + let bytes_b = fs::read(out_b.join("corporate_actions/part.parquet")).unwrap(); + assert_eq!(bytes_a, bytes_b); + } +} + +#[cfg(test)] +#[path = "parquet_corporate_actions_tests.rs"] +mod edge_case_tests; diff --git a/tools/curate-etl/src/parquet_corporate_actions_tests.rs b/tools/curate-etl/src/parquet_corporate_actions_tests.rs new file mode 100644 index 00000000..6045d806 --- /dev/null +++ b/tools/curate-etl/src/parquet_corporate_actions_tests.rs @@ -0,0 +1,1838 @@ +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use parquet::basic::Encoding; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::tests::{ + assert_no_transient_files, assert_row_bitwise_eq, day, known_at_from_day, make_delisting_row, + make_div_row, make_otc_transfer_row, make_split_row, read_parquet_rows, TempDirGuard, +}; +use super::{ + write_corporate_actions_dataset, write_corporate_actions_dataset_with_hooks, + CorporateActionsParquetRow, CorporateActionsWriteOptions, ForbiddenFieldValue, + ParquetCorporateActionsError, +}; +use crate::corporate_actions::{CorporateActionKind, KnownAtSource}; +use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; +use crate::parquet_publish::STRING_WRITE_BATCH_ROWS; + +fn seed_existing(out_dir: &Path) -> (PathBuf, Vec) { + let seed = vec![ + make_split_row(100, day(2024, 1, 15), Some(day(2024, 1, 1)), 2.0), + make_div_row(100, day(2024, 6, 15), Some(day(2024, 6, 1)), 0.50, "USD"), + ]; + write_corporate_actions_dataset(out_dir, &seed, CorporateActionsWriteOptions::default()) + .unwrap(); + let part = out_dir.join("corporate_actions/part.parquet"); + let before = fs::read(&part).unwrap(); + (part, before) +} + +#[test] +fn single_row_and_row_group_boundary_counts_with_pre_1970_split() { + let tmp = TempDirGuard::new("rg-boundaries"); + + // 1 row: pre-1970 split with null declared_date + let out_1 = tmp.path().join("one"); + let single = vec![make_split_row(7, day(1969, 12, 31), None, 2.0)]; + let stats_1 = + write_corporate_actions_dataset(&out_1, &single, CorporateActionsWriteOptions::default()) + .unwrap(); + assert_eq!(stats_1.rows_written, 1); + assert_eq!(stats_1.files_written, 1); + assert_eq!(stats_1.row_groups_written, 1); + let actual_1 = read_parquet_rows(&out_1.join("corporate_actions/part.parquet")); + assert_eq!(actual_1.len(), 1); + assert_row_bitwise_eq(&actual_1[0], &single[0]); + assert_eq!(actual_1[0].ex_date, -1); + assert!(actual_1[0].declared_date.is_none()); + + // Exactly row_group_rows (4 rows, row_group_rows = 4 => 1 row group) + let base = day(2024, 1, 2); + let rows_exact = vec![ + make_split_row(10, base, Some(base - 14), 2.0), + make_div_row(10, base, Some(base - 10), 0.25, "USD"), + make_otc_transfer_row(10, base + 30, 10_001), + make_delisting_row(11, base + 60, -0.30), + ]; + let out_exact = tmp.path().join("exact"); + let opts = CorporateActionsWriteOptions { + row_group_rows: 4, + ..CorporateActionsWriteOptions::default() + }; + let stats_exact = write_corporate_actions_dataset(&out_exact, &rows_exact, opts).unwrap(); + assert_eq!(stats_exact.rows_written, 4); + assert_eq!(stats_exact.row_groups_written, 1); + let reader_exact = SerializedFileReader::new( + File::open(out_exact.join("corporate_actions/part.parquet")).unwrap(), + ) + .unwrap(); + assert_eq!(reader_exact.metadata().num_row_groups(), 1); + assert_eq!(reader_exact.metadata().row_group(0).num_rows(), 4); + + // row_group_rows + 1 (5 rows, row_group_rows = 4 => 2 row groups: [4, 1]) + let rows_plus_one = vec![ + make_split_row(1, day(1969, 6, 15), None, 3.0), + make_div_row(1, base, Some(base - 14), 0.40, "USD"), + make_div_row(1, base, None, 0.80, "USD"), + make_otc_transfer_row(2, base, 2001), + make_delisting_row(3, base, -1.0), + ]; + let out_plus = tmp.path().join("plus-one"); + let stats_plus = write_corporate_actions_dataset(&out_plus, &rows_plus_one, opts).unwrap(); + assert_eq!(stats_plus.rows_written, 5); + assert_eq!(stats_plus.row_groups_written, 2); + let p_plus = out_plus.join("corporate_actions/part.parquet"); + let reader_plus = SerializedFileReader::new(File::open(&p_plus).unwrap()).unwrap(); + let rg_sizes: Vec = (0..reader_plus.metadata().num_row_groups()) + .map(|i| reader_plus.metadata().row_group(i).num_rows()) + .collect(); + assert_eq!(rg_sizes, vec![4, 1]); + let actual_plus = read_parquet_rows(&p_plus); + assert_eq!(actual_plus.len(), rows_plus_one.len()); + for (a, e) in actual_plus.iter().zip(&rows_plus_one) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&out_plus.join("corporate_actions")); +} + +#[test] +fn multi_batch_all_null_and_mixed_null_optional_columns_round_trip() { + let tmp = TempDirGuard::new("opt-col-batches"); + let base = day(2000, 1, 3); + + // 100% split rows with declared_date = None spanning > STRING_WRITE_BATCH_ROWS (4096) + // exercises all-null optional i32 (declared_date, successor_listing_id), + // optional f64 (cash_amount, terminal_return), and optional String (currency). + let all_null_count = STRING_WRITE_BATCH_ROWS + 137; + let all_null_rows: Vec = (0..all_null_count) + .map(|i| { + let listing_id = (i / 100) as i32 + 1; + let ex_date = base + (i % 100) as i32; + make_split_row(listing_id, ex_date, None, 2.0) + }) + .collect(); + let out_null = tmp.path().join("all-null"); + let stats_null = write_corporate_actions_dataset( + &out_null, + &all_null_rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats_null.rows_written, all_null_count); + assert_eq!(stats_null.row_groups_written, 1); + let actual_null = read_parquet_rows(&out_null.join("corporate_actions/part.parquet")); + assert_eq!(actual_null.len(), all_null_rows.len()); + for (a, e) in actual_null.iter().zip(&all_null_rows) { + assert_row_bitwise_eq(a, e); + } + + // > STRING_WRITE_BATCH_ROWS * 2 mixed rows crossing multiple 4,096-row batches + // including an all-null-currency middle chunk (rows 4096..8192) inside the same row group. + let mixed_count = STRING_WRITE_BATCH_ROWS * 2 + 257; + let mixed_rows: Vec = (0..mixed_count) + .map(|i| { + let listing_id = (i / 500) as i32 + 1; + let ex_date = base + (i % 500) as i32; + if (STRING_WRITE_BATCH_ROWS..STRING_WRITE_BATCH_ROWS * 2).contains(&i) { + make_delisting_row(listing_id, ex_date, -0.30) + } else { + match i % 4 { + 0 => make_split_row(listing_id, ex_date, Some(ex_date - 14), 2.0), + 1 => make_div_row(listing_id, ex_date, Some(ex_date - 10), 0.25, "USD"), + 2 => make_div_row(listing_id, ex_date, None, 0.40, "CAD"), + _ => make_otc_transfer_row(listing_id, ex_date, listing_id + 100_000), + } + } + }) + .collect(); + + let out_mixed = tmp.path().join("mixed-multi-batch"); + let stats_mixed = write_corporate_actions_dataset( + &out_mixed, + &mixed_rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats_mixed.rows_written, mixed_count); + assert_eq!(stats_mixed.row_groups_written, 1); + let actual_mixed = read_parquet_rows(&out_mixed.join("corporate_actions/part.parquet")); + assert_eq!(actual_mixed.len(), mixed_rows.len()); + for (a, e) in actual_mixed.iter().zip(&mixed_rows) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&out_mixed.join("corporate_actions")); +} + +#[test] +fn dictionary_encoding_active_on_string_columns_and_invalid_options_preserve_state() { + let tmp = TempDirGuard::new("dict-zstd"); + let base = day(2024, 1, 2); + let rows: Vec = (0..64_i32) + .map(|i| { + let listing_id = if i < 32 { 1 } else { 2 }; + let d = base + (i % 32); + match i % 4 { + 0 => make_split_row(listing_id, d, Some(d - 14), 2.0), + 1 => make_div_row(listing_id, d, Some(d - 10), 0.30, "USD"), + 2 => make_div_row(listing_id, d, None, 0.45, "CAD"), + _ => make_delisting_row(listing_id, d, -0.30), + } + }) + .collect(); + + let out_ok = tmp.path().join("lvl-3"); + write_corporate_actions_dataset(&out_ok, &rows, CorporateActionsWriteOptions::default()) + .unwrap(); + let p = out_ok.join("corporate_actions/part.parquet"); + let reader = SerializedFileReader::new(File::open(&p).unwrap()).unwrap(); + let rg0 = reader.metadata().row_group(0); + + for (col_idx, col_name) in [(3, "kind"), (6, "currency"), (10, "known_at_source")] { + let col = rg0.column(col_idx); + assert!( + col.encodings() + .any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)), + "expected dictionary encoding on {col_name} column, got {:?}", + col.encodings().collect::>() + ); + } + + // Invalid row_group_rows and zstd_level in fresh dir + let out_bad = tmp.path().join("bad-opts-fresh"); + assert!(matches!( + write_corporate_actions_dataset( + &out_bad, + &rows, + CorporateActionsWriteOptions { + row_group_rows: 0, + ..CorporateActionsWriteOptions::default() + } + ), + Err(ParquetCorporateActionsError::InvalidRowGroupRows) + )); + assert!(matches!( + write_corporate_actions_dataset( + &out_bad, + &rows, + CorporateActionsWriteOptions { + zstd_level: 23, + ..CorporateActionsWriteOptions::default() + } + ), + Err(ParquetCorporateActionsError::InvalidZstdLevel { level: 23 }) + )); + assert!(matches!( + write_corporate_actions_dataset( + &out_bad, + &rows, + CorporateActionsWriteOptions { + zstd_level: 99, + ..CorporateActionsWriteOptions::default() + } + ), + Err(ParquetCorporateActionsError::InvalidZstdLevel { level: 99 }) + )); + assert!(!out_bad.exists(), "invalid options must not create out_dir"); + + // Invalid options in seeded dir leave existing part.parquet byte-identical + let out_seeded = tmp.path().join("bad-opts-seeded"); + let (part, before) = seed_existing(&out_seeded); + assert!(matches!( + write_corporate_actions_dataset( + &out_seeded, + &rows, + CorporateActionsWriteOptions { + row_group_rows: 0, + ..CorporateActionsWriteOptions::default() + } + ), + Err(ParquetCorporateActionsError::InvalidRowGroupRows) + )); + assert!(matches!( + write_corporate_actions_dataset( + &out_seeded, + &rows, + CorporateActionsWriteOptions { + zstd_level: 23, + ..CorporateActionsWriteOptions::default() + } + ), + Err(ParquetCorporateActionsError::InvalidZstdLevel { level: 23 }) + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&out_seeded.join("corporate_actions")); +} + +#[test] +fn overwrite_replaces_existing_part_parquet_and_leaves_no_transients() { + let tmp = TempDirGuard::new("overwrite"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![ + make_div_row(500, day(2025, 4, 15), Some(day(2025, 4, 1)), 0.75, "CAD"), + make_delisting_row(500, day(2025, 6, 1), -0.50), + ]; + let stats = write_corporate_actions_dataset( + tmp.path(), + &replacement, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats.rows_written, 2); + assert_eq!(stats.files_written, 1); + + let after = fs::read(&part).unwrap(); + assert_ne!(after, before); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), replacement.len()); + for (a, e) in actual.iter().zip(&replacement) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn validation_errors_return_typed_variants_and_preserve_existing_state() { + let tmp = TempDirGuard::new("validation"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 6, 15); + + type ErrorCheck = fn(&ParquetCorporateActionsError) -> bool; + let bad_cases: Vec<(&str, Vec, ErrorCheck)> = vec![ + // Unsorted input on listing_id, ex_date, and kind + ( + "unsorted-listing", + vec![ + make_div_row(2, d1, None, 0.25, "USD"), + make_div_row(1, d1, None, 0.25, "USD"), + ], + |e| { + matches!( + e, + ParquetCorporateActionsError::UnsortedInput { + prev_listing_id: 2, + listing_id: 1, + .. + } + ) + }, + ), + ( + "unsorted-ex-date", + vec![ + make_div_row(1, d2, None, 0.25, "USD"), + make_div_row(1, d1, None, 0.25, "USD"), + ], + |e| { + matches!( + e, + ParquetCorporateActionsError::UnsortedInput { + listing_id: 1, + prev_kind: CorporateActionKind::Dividend, + kind: CorporateActionKind::Dividend, + .. + } + ) + }, + ), + ( + "unsorted-kind", + vec![ + make_div_row(1, d1, None, 0.25, "USD"), + make_split_row(1, d1, None, 2.0), + ], + |e| { + matches!( + e, + ParquetCorporateActionsError::UnsortedInput { + listing_id: 1, + prev_kind: CorporateActionKind::Dividend, + kind: CorporateActionKind::Split, + .. + } + ) + }, + ), + // Date year range checks + ( + "ex-date-below-min-year", + vec![make_split_row(1, day(1899, 12, 31), None, 2.0)], + |e| { + matches!( + e, + ParquetCorporateActionsError::ExDateOutOfRange { + year: 1899, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + ( + "ex-date-above-max-year", + vec![make_split_row(1, day(2201, 1, 1), None, 2.0)], + |e| { + matches!( + e, + ParquetCorporateActionsError::ExDateOutOfRange { + year: 2201, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + ( + "declared-date-below-min-year", + vec![make_split_row(1, d1, Some(day(1899, 12, 31)), 2.0)], + |e| { + matches!( + e, + ParquetCorporateActionsError::DeclaredDateOutOfRange { + year: 1899, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + ( + "declared-date-above-max-year", + vec![make_div_row(1, d1, Some(day(2201, 1, 1)), 0.25, "USD")], + |e| { + matches!( + e, + ParquetCorporateActionsError::DeclaredDateOutOfRange { + year: 2201, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + // Split ratio violations + ( + "split-ratio-none", + vec![CorporateActionsParquetRow { + ratio: None, + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidRatio { value: None, .. } + ) + }, + ), + ( + "split-ratio-zero", + vec![make_split_row(1, d1, None, 0.0)], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { value: Some(v), .. } if *v == 0.0), + ), + ( + "split-ratio-neg-zero", + vec![make_split_row(1, d1, None, -0.0)], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { .. }), + ), + ( + "split-ratio-negative", + vec![make_split_row(1, d1, None, -2.0)], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { .. }), + ), + ( + "split-ratio-nan", + vec![make_split_row(1, d1, None, f64::NAN)], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { .. }), + ), + ( + "split-ratio-inf", + vec![make_split_row(1, d1, None, f64::INFINITY)], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { .. }), + ), + // Dividend cash_amount & currency violations + ( + "div-cash-none", + vec![CorporateActionsParquetRow { + cash_amount: None, + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidCashAmount { value: None, .. } + ) + }, + ), + ( + "div-cash-zero", + vec![make_div_row(1, d1, None, 0.0, "USD")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { .. }), + ), + ( + "div-cash-neg-zero", + vec![make_div_row(1, d1, None, -0.0, "USD")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { .. }), + ), + ( + "div-cash-negative", + vec![make_div_row(1, d1, None, -0.05, "USD")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { .. }), + ), + ( + "div-cash-nan", + vec![make_div_row(1, d1, None, f64::NAN, "USD")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { .. }), + ), + ( + "div-cash-inf", + vec![make_div_row(1, d1, None, f64::INFINITY, "USD")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { .. }), + ), + ( + "div-currency-none", + vec![CorporateActionsParquetRow { + currency: None, + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidCurrency { + listing_id: 1, + ex_date, + value: None, + } if *ex_date == day(2024, 3, 15) + ) + }, + ), + ( + "div-currency-empty", + vec![make_div_row(1, d1, None, 0.25, "")], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidCurrency { + listing_id: 1, + ex_date, + value: Some(v), + } if *ex_date == day(2024, 3, 15) && v.is_empty() + ) + }, + ), + ( + "div-currency-whitespace", + vec![make_div_row(1, d1, None, 0.25, " \t ")], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidCurrency { + listing_id: 1, + ex_date, + value: Some(v), + } if *ex_date == day(2024, 3, 15) && v == " \t " + ) + }, + ), + ( + "div-same-key-second-whitespace-currency", + vec![ + make_div_row(1, d1, None, 0.25, "USD"), + make_div_row(1, d1, None, 0.50, " "), + ], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidCurrency { + listing_id: 1, + ex_date, + value: Some(v), + } if *ex_date == day(2024, 3, 15) && v == " " + ) && e.to_string().contains("\" \"") + }, + ), + // OTC delist transfer successor_listing_id violations + ( + "otc-successor-none", + vec![CorporateActionsParquetRow { + successor_listing_id: None, + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidSuccessorListingId { + successor_listing_id: None, + .. + } + ) + }, + ), + ( + "otc-successor-self", + vec![make_otc_transfer_row(42, d1, 42)], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidSuccessorListingId { + listing_id: 42, + successor_listing_id: Some(42), + .. + } + ) + }, + ), + // Delisting terminal_return violations + ( + "delist-return-none", + vec![CorporateActionsParquetRow { + terminal_return: None, + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidTerminalReturn { value: None, .. } + ) + }, + ), + ( + "delist-return-nan", + vec![make_delisting_row(1, d1, f64::NAN)], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidTerminalReturn { .. } + ) + }, + ), + ( + "delist-return-inf", + vec![make_delisting_row(1, d1, f64::NEG_INFINITY)], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidTerminalReturn { .. } + ) + }, + ), + ( + "delist-return-below-minus-one", + vec![make_delisting_row(1, d1, -1.0001)], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidTerminalReturn { .. } + ) + }, + ), + ( + "delist-return-above-zero", + vec![make_delisting_row(1, d1, 0.0001)], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidTerminalReturn { .. } + ) + }, + ), + // Forbidden fields for Split + ( + "split-forbids-cash", + vec![CorporateActionsParquetRow { + cash_amount: Some(0.25), + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Split, + field: "cash_amount", + value: ForbiddenFieldValue::Float(v), + } if *ex_date == day(2024, 3, 15) && *v == 0.25 + ) && e.to_string().contains("0.25") + }, + ), + ( + "split-forbids-currency", + vec![CorporateActionsParquetRow { + currency: Some(Cow::Borrowed("USD")), + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Split, + field: "currency", + value: ForbiddenFieldValue::String(v), + } if *ex_date == day(2024, 3, 15) && v == "USD" + ) && e.to_string().contains("\"USD\"") + }, + ), + ( + "split-forbids-successor", + vec![CorporateActionsParquetRow { + successor_listing_id: Some(2), + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Split, + field: "successor_listing_id", + value: ForbiddenFieldValue::Int(2), + } if *ex_date == day(2024, 3, 15) + ) && e.to_string().contains("value 2") + }, + ), + ( + "split-forbids-terminal-return", + vec![CorporateActionsParquetRow { + terminal_return: Some(-0.3), + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Split, + field: "terminal_return", + value: ForbiddenFieldValue::Float(v), + } if *ex_date == day(2024, 3, 15) && *v == -0.3 + ) + }, + ), + // Forbidden fields for Dividend + ( + "div-forbids-ratio", + vec![CorporateActionsParquetRow { + ratio: Some(2.0), + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Dividend, + field: "ratio", + value: ForbiddenFieldValue::Float(v), + } if *ex_date == day(2024, 3, 15) && *v == 2.0 + ) + }, + ), + ( + "div-forbids-successor", + vec![CorporateActionsParquetRow { + successor_listing_id: Some(2), + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Dividend, + field: "successor_listing_id", + value: ForbiddenFieldValue::Int(2), + } if *ex_date == day(2024, 3, 15) + ) + }, + ), + ( + "div-forbids-terminal-return", + vec![CorporateActionsParquetRow { + terminal_return: Some(-0.3), + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Dividend, + field: "terminal_return", + value: ForbiddenFieldValue::Float(v), + } if *ex_date == day(2024, 3, 15) && *v == -0.3 + ) + }, + ), + // Forbidden fields for OtcDelistTransfer + ( + "otc-forbids-ratio", + vec![CorporateActionsParquetRow { + ratio: Some(2.0), + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::OtcDelistTransfer, + field: "ratio", + value: ForbiddenFieldValue::Float(v), + } if *ex_date == day(2024, 3, 15) && *v == 2.0 + ) + }, + ), + ( + "otc-forbids-cash", + vec![CorporateActionsParquetRow { + cash_amount: Some(0.25), + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::OtcDelistTransfer, + field: "cash_amount", + value: ForbiddenFieldValue::Float(v), + } if *ex_date == day(2024, 3, 15) && *v == 0.25 + ) + }, + ), + ( + "otc-forbids-currency", + vec![CorporateActionsParquetRow { + currency: Some(Cow::Borrowed("USD")), + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::OtcDelistTransfer, + field: "currency", + value: ForbiddenFieldValue::String(v), + } if *ex_date == day(2024, 3, 15) && v == "USD" + ) + }, + ), + ( + "otc-forbids-terminal-return", + vec![CorporateActionsParquetRow { + terminal_return: Some(-0.3), + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::OtcDelistTransfer, + field: "terminal_return", + value: ForbiddenFieldValue::Float(v), + } if *ex_date == day(2024, 3, 15) && *v == -0.3 + ) + }, + ), + // Forbidden fields for Delisting + ( + "delist-forbids-ratio", + vec![CorporateActionsParquetRow { + ratio: Some(2.0), + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Delisting, + field: "ratio", + value: ForbiddenFieldValue::Float(v), + } if *ex_date == day(2024, 3, 15) && *v == 2.0 + ) + }, + ), + ( + "delist-forbids-cash", + vec![CorporateActionsParquetRow { + cash_amount: Some(0.25), + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Delisting, + field: "cash_amount", + value: ForbiddenFieldValue::Float(v), + } if *ex_date == day(2024, 3, 15) && *v == 0.25 + ) + }, + ), + ( + "delist-forbids-currency", + vec![CorporateActionsParquetRow { + currency: Some(Cow::Borrowed("USD")), + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Delisting, + field: "currency", + value: ForbiddenFieldValue::String(v), + } if *ex_date == day(2024, 3, 15) && v == "USD" + ) + }, + ), + ( + "delist-forbids-successor", + vec![CorporateActionsParquetRow { + successor_listing_id: Some(2), + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 1, + ex_date, + kind: CorporateActionKind::Delisting, + field: "successor_listing_id", + value: ForbiddenFieldValue::Int(2), + } if *ex_date == day(2024, 3, 15) + ) + }, + ), + // Inconsistent known_at_source + ( + "split-delist-date-source", + vec![CorporateActionsParquetRow { + known_at_source: KnownAtSource::DelistDate, + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Split, + known_at_source: KnownAtSource::DelistDate, + .. + } + ) + }, + ), + ( + "div-delist-date-source", + vec![CorporateActionsParquetRow { + known_at_source: KnownAtSource::DelistDate, + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Dividend, + known_at_source: KnownAtSource::DelistDate, + .. + } + ) + }, + ), + ( + "split-declared-source-without-declared-date", + vec![CorporateActionsParquetRow { + declared_date: None, + known_at_source: KnownAtSource::DeclaredDate, + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Split, + known_at_source: KnownAtSource::DeclaredDate, + declared_date: None, + .. + } + ) + }, + ), + ( + "div-declared-source-without-declared-date", + vec![CorporateActionsParquetRow { + declared_date: None, + known_at_source: KnownAtSource::DeclaredDate, + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Dividend, + known_at_source: KnownAtSource::DeclaredDate, + declared_date: None, + .. + } + ) + }, + ), + ( + "otc-ex-date-fallback-source", + vec![CorporateActionsParquetRow { + known_at_source: KnownAtSource::ExDateFallback, + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::OtcDelistTransfer, + known_at_source: KnownAtSource::ExDateFallback, + .. + } + ) + }, + ), + ( + "otc-declared-date-source", + vec![CorporateActionsParquetRow { + declared_date: Some(d1 - 5), + known_at_source: KnownAtSource::DeclaredDate, + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::OtcDelistTransfer, + known_at_source: KnownAtSource::DeclaredDate, + .. + } + ) + }, + ), + ( + "delist-ex-date-fallback-source", + vec![CorporateActionsParquetRow { + known_at_source: KnownAtSource::ExDateFallback, + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Delisting, + known_at_source: KnownAtSource::ExDateFallback, + .. + } + ) + }, + ), + ( + "delist-declared-date-source", + vec![CorporateActionsParquetRow { + declared_date: Some(d1 - 5), + known_at_source: KnownAtSource::DeclaredDate, + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Delisting, + known_at_source: KnownAtSource::DeclaredDate, + .. + } + ) + }, + ), + ]; + + for (label, rows, check) in bad_cases { + let fresh = tmp.path().join(format!("fresh-{label}")); + let err = + write_corporate_actions_dataset(&fresh, &rows, CorporateActionsWriteOptions::default()) + .unwrap_err(); + assert!(check(&err), "fresh case '{label}' got unexpected {err:?}"); + assert!( + !fresh.join("corporate_actions/part.parquet").exists(), + "fresh case '{label}' must not publish part.parquet" + ); + assert_no_transient_files(&fresh.join("corporate_actions")); + + let seeded = tmp.path().join(format!("seeded-{label}")); + let (part, before) = seed_existing(&seeded); + let err_s = write_corporate_actions_dataset( + &seeded, + &rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap_err(); + assert!( + check(&err_s), + "seeded case '{label}' got unexpected {err_s:?}" + ); + assert_eq!( + fs::read(&part).unwrap(), + before, + "seeded case '{label}' must preserve existing part.parquet" + ); + assert_no_transient_files(&seeded.join("corporate_actions")); + } +} + +#[test] +fn mid_stream_failure_after_flushed_row_groups_preserves_existing_file() { + let tmp = TempDirGuard::new("mid-stream-fail"); + let (part, before) = seed_existing(tmp.path()); + + let base = day(2024, 1, 2); + let mut rows: Vec = (0..5_i32) + .map(|i| make_div_row(1, base + i * 30, Some(base + i * 30 - 10), 0.25, "USD")) + .collect(); + rows.push(CorporateActionsParquetRow { + listing_id: 1, + ex_date: base + 6 * 30, + declared_date: None, + kind: CorporateActionKind::Split, + ratio: Some(f64::NAN), + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: None, + known_at_micros: known_at_from_day(base + 6 * 30), + known_at_source: KnownAtSource::ExDateFallback, + }); + + let err = write_corporate_actions_dataset( + tmp.path(), + &rows, + CorporateActionsWriteOptions { + row_group_rows: 2, + ..CorporateActionsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetCorporateActionsError::InvalidRatio { .. } + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn out_dir_or_corporate_actions_occupied_by_regular_file_returns_io_error() { + let tmp = TempDirGuard::new("io-blocker"); + let rows = vec![make_div_row(1, day(2024, 3, 15), None, 0.25, "USD")]; + + let file_as_out = tmp.path().join("not-a-dir"); + fs::write(&file_as_out, b"sentinel").unwrap(); + let err = write_corporate_actions_dataset( + &file_as_out, + &rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!(err, ParquetCorporateActionsError::Io { .. })); + assert!(StdError::source(&err).is_some()); + assert_eq!(fs::read(&file_as_out).unwrap(), b"sentinel"); + + let out_with_file_ds = tmp.path().join("ds-is-file"); + fs::create_dir_all(&out_with_file_ds).unwrap(); + let ds_file = out_with_file_ds.join("corporate_actions"); + fs::write(&ds_file, b"file-not-dir").unwrap(); + let err2 = write_corporate_actions_dataset( + &out_with_file_ds, + &rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!(err2, ParquetCorporateActionsError::Io { .. })); + assert_eq!(fs::read(&ds_file).unwrap(), b"file-not-dir"); +} + +#[test] +fn stale_lock_times_out_leaving_lock_and_existing_part_intact() { + let tmp = TempDirGuard::new("stale-lock"); + let (part, before) = seed_existing(tmp.path()); + let lock_path = tmp.path().join("corporate_actions/.write.lock"); + fs::write(&lock_path, b"999999\n").unwrap(); + + let rows = vec![make_div_row(1, day(2024, 6, 15), None, 0.50, "USD")]; + let err = write_corporate_actions_dataset_with_hooks( + tmp.path(), + &rows, + CorporateActionsWriteOptions::default(), + Duration::from_millis(30), + |_, _| {}, + |path| fs::remove_file(path), + ) + .unwrap_err(); + + assert!( + matches!(err, ParquetCorporateActionsError::LockTimeout { ref path, .. } if path == &lock_path), + "expected LockTimeout, got {err:?}" + ); + assert!( + lock_path.exists(), + "stale lock must not be deleted by timed-out writer" + ); + assert_eq!(fs::read(&part).unwrap(), before); +} + +#[test] +fn live_part_parquet_stays_readable_between_backup_and_rename() { + let tmp = TempDirGuard::new("live-readable"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![make_div_row(200, day(2024, 9, 15), None, 0.60, "CAD")]; + let observed_live = Arc::new(Mutex::new(false)); + let observed_clone = Arc::clone(&observed_live); + + write_corporate_actions_dataset_with_hooks( + tmp.path(), + &replacement, + CorporateActionsWriteOptions::default(), + Duration::from_secs(5), + move |final_path, backup_path| { + assert!( + backup_path.is_some(), + "expected backup path for existing file" + ); + assert_eq!(fs::read(final_path).unwrap(), before); + assert_eq!(fs::read(backup_path.unwrap()).unwrap(), before); + *observed_clone.lock().unwrap() = true; + }, + |path| fs::remove_file(path), + ) + .unwrap(); + + assert!(*observed_live.lock().unwrap()); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), 1); + assert_row_bitwise_eq(&actual[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn rename_failure_over_directory_blocker_cleans_up_staging_and_unowned_tmp_is_preserved() { + let tmp = TempDirGuard::new("rename-blocker"); + let ds_dir = tmp.path().join("corporate_actions"); + let blocking_dir = ds_dir.join("part.parquet"); + fs::create_dir_all(&blocking_dir).unwrap(); + + let unowned_tmp = ds_dir.join("part.parquet.unowned-other-run.tmp"); + fs::write(&unowned_tmp, b"keep-me").unwrap(); + + let rows = vec![make_div_row(1, day(2024, 3, 15), None, 0.25, "USD")]; + let err = + write_corporate_actions_dataset(tmp.path(), &rows, CorporateActionsWriteOptions::default()) + .unwrap_err(); + assert!( + matches!(err, ParquetCorporateActionsError::Io { .. }), + "got {err:?}" + ); + assert!( + blocking_dir.is_dir(), + "directory blocker must remain intact" + ); + assert_eq!( + fs::read(&unowned_tmp).unwrap(), + b"keep-me", + "unowned .tmp file must be preserved" + ); + + let mut entries: Vec = fs::read_dir(&ds_dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + entries.sort(); + assert_eq!( + entries, + vec![ + "part.parquet".to_string(), + "part.parquet.unowned-other-run.tmp".to_string(), + ] + ); +} + +#[test] +fn concurrent_in_process_writers_serialize_cleanly() { + let tmp = TempDirGuard::new("concurrent-unit"); + let out = Arc::new(tmp.path().to_path_buf()); + + let out_1 = Arc::clone(&out); + let handle_1 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + if i == 1 { + thread::sleep(Duration::from_millis(30)); + } + make_div_row(10, day(2024, 1, 15) + i * 30, None, 0.25, "USD") + }); + write_corporate_actions_dataset( + out_1.as_path(), + iter, + CorporateActionsWriteOptions::default(), + ) + }); + + thread::sleep(Duration::from_millis(5)); + let out_2 = Arc::clone(&out); + let handle_2 = thread::spawn(move || { + let iter = + (0..2_i32).map(move |i| make_split_row(20, day(2024, 2, 15) + i * 30, None, 2.0)); + write_corporate_actions_dataset( + out_2.as_path(), + iter, + CorporateActionsWriteOptions::default(), + ) + }); + + let s1 = handle_1.join().unwrap().unwrap(); + let s2 = handle_2.join().unwrap().unwrap(); + assert_eq!(s1.rows_written, 2); + assert_eq!(s2.rows_written, 2); + + let got = read_parquet_rows(&tmp.path().join("corporate_actions/part.parquet")); + assert_eq!(got.len(), 2); + assert!( + got.iter().all(|r| r.listing_id == 10) || got.iter().all(|r| r.listing_id == 20), + "output must come entirely from one writer generation" + ); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn panicking_iterator_cleans_up_staging_file_and_releases_lock() { + let tmp = TempDirGuard::new("panic-unwind"); + let (part, before) = seed_existing(tmp.path()); + + let out = tmp.path().to_path_buf(); + let opts = CorporateActionsWriteOptions { + row_group_rows: 2, + ..CorporateActionsWriteOptions::default() + }; + let result = std::panic::catch_unwind(move || { + let base = day(2024, 3, 15); + let iter = (0..5_i32).map(move |i| { + if i == 3 { + panic!("simulated iterator panic after row-group flush"); + } + make_div_row(1, base + i * 30, None, 0.25, "USD") + }); + let _ = write_corporate_actions_dataset(&out, iter, opts); + }); + assert!(result.is_err(), "iterator must have panicked"); + + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("corporate_actions")); + + let replacement = vec![make_div_row(99, day(2024, 6, 15), None, 0.75, "CAD")]; + let stats = write_corporate_actions_dataset( + tmp.path(), + &replacement, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats.rows_written, 1); + let got = read_parquet_rows(&part); + assert_eq!(got.len(), 1); + assert_row_bitwise_eq(&got[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn backup_unlink_failure_after_rename_restores_live_file_and_returns_error() { + let tmp = TempDirGuard::new("backup-unlink-fail"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![make_div_row(300, day(2024, 9, 15), None, 0.60, "CAD")]; + let observed_bak: Arc>> = Arc::new(Mutex::new(None)); + let observed_bak_clone = Arc::clone(&observed_bak); + + let err = write_corporate_actions_dataset_with_hooks( + tmp.path(), + &replacement, + CorporateActionsWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + move |bak_path| { + *observed_bak_clone.lock().unwrap() = Some(bak_path.to_path_buf()); + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "simulated backup unlink failure", + )) + }, + ) + .unwrap_err(); + + let expected_bak = observed_bak + .lock() + .unwrap() + .clone() + .expect("backup unlink hook must be called"); + assert!( + matches!( + err, + ParquetCorporateActionsError::Io { ref path, ref source } + if path == &expected_bak + && source.kind() == std::io::ErrorKind::PermissionDenied + ), + "expected Io error on backup path, got {err:?}" + ); + assert_eq!( + fs::read(&part).unwrap(), + before, + "live part.parquet must be atomically restored from backup" + ); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn backup_unlink_and_restore_failure_reports_rollback_failed() { + let tmp = TempDirGuard::new("backup-rollback-fail"); + let (part, _before) = seed_existing(tmp.path()); + + let replacement = vec![make_div_row(300, day(2024, 9, 15), None, 0.60, "CAD")]; + let observed_bak: Arc>> = Arc::new(Mutex::new(None)); + let observed_bak_clone = Arc::clone(&observed_bak); + + let err = write_corporate_actions_dataset_with_hooks( + tmp.path(), + &replacement, + CorporateActionsWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + move |bak_path| { + *observed_bak_clone.lock().unwrap() = Some(bak_path.to_path_buf()); + let _ = fs::remove_file(bak_path); + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "simulated backup unlink failure", + )) + }, + ) + .unwrap_err(); + + let expected_bak = observed_bak + .lock() + .unwrap() + .clone() + .expect("backup unlink hook must be called"); + match err { + ParquetCorporateActionsError::RollbackFailed { cause, failures } => { + assert!( + matches!( + *cause, + ParquetCorporateActionsError::Io { ref path, ref source } + if path == &expected_bak + && source.kind() == std::io::ErrorKind::PermissionDenied + ), + "unexpected cause: {cause:?}" + ); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].final_path, part); + assert_eq!( + failures[0].backup_path.as_deref(), + Some(expected_bak.as_path()) + ); + assert_eq!(failures[0].source.kind(), std::io::ErrorKind::NotFound); + } + other => panic!("expected RollbackFailed, got {other:?}"), + } + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn boundary_years_min_and_max_are_accepted() { + let tmp = TempDirGuard::new("boundary-years"); + let min_day = day(MIN_PARQUET_YEAR, 1, 1); + let max_day = day(MAX_PARQUET_YEAR, 12, 31); + let rows = vec![ + make_split_row(1, min_day, Some(min_day), 2.0), + make_div_row(1, max_day, Some(max_day), 0.25, "USD"), + ]; + let stats = + write_corporate_actions_dataset(tmp.path(), &rows, CorporateActionsWriteOptions::default()) + .unwrap(); + assert_eq!(stats.rows_written, 2); + let actual = read_parquet_rows(&tmp.path().join("corporate_actions/part.parquet")); + assert_eq!(actual.len(), 2); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } +} + +#[test] +fn extreme_values_and_non_ascii_currency_round_trip_bitwise() { + let tmp = TempDirGuard::new("extreme-values"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 3, 16); + let rows = vec![ + CorporateActionsParquetRow { + listing_id: i32::MIN, + ex_date: d1, + declared_date: None, + kind: CorporateActionKind::Split, + ratio: Some(f64::from_bits(1)), // smallest positive subnormal + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: None, + known_at_micros: i64::MIN, + known_at_source: KnownAtSource::ExDateFallback, + }, + CorporateActionsParquetRow { + listing_id: i32::MIN, + ex_date: d2, + declared_date: Some(d1), + kind: CorporateActionKind::Dividend, + ratio: None, + cash_amount: Some(f64::MAX), + currency: Some(Cow::Borrowed("€¥£")), + successor_listing_id: None, + terminal_return: None, + known_at_micros: i64::MAX, + known_at_source: KnownAtSource::DeclaredDate, + }, + CorporateActionsParquetRow { + listing_id: i32::MAX, + ex_date: d1, + declared_date: None, + kind: CorporateActionKind::OtcDelistTransfer, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: Some(i32::MIN), + terminal_return: None, + known_at_micros: 0, + known_at_source: KnownAtSource::DelistDate, + }, + CorporateActionsParquetRow { + listing_id: i32::MAX, + ex_date: d2, + declared_date: None, + kind: CorporateActionKind::Delisting, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: Some(-0.0), + known_at_micros: i64::MAX, + known_at_source: KnownAtSource::DelistDate, + }, + ]; + let stats = + write_corporate_actions_dataset(tmp.path(), &rows, CorporateActionsWriteOptions::default()) + .unwrap(); + assert_eq!(stats.rows_written, 4); + let actual = read_parquet_rows(&tmp.path().join("corporate_actions/part.parquet")); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } +} + +#[test] +fn duplicate_key_rows_preserve_input_order_across_row_groups() { + let tmp = TempDirGuard::new("dup-key-order"); + let d = day(2024, 6, 15); + let rows = vec![ + make_div_row(42, d, Some(d - 10), 0.10, "USD"), + make_div_row(42, d, None, 0.20, "CAD"), + make_div_row(42, d, Some(d - 5), 0.30, "USD"), + make_div_row(42, d, None, 0.40, "CAD"), + make_div_row(42, d, Some(d - 1), 0.50, "EUR"), + ]; + let opts = CorporateActionsWriteOptions { + row_group_rows: 2, + ..CorporateActionsWriteOptions::default() + }; + let stats = write_corporate_actions_dataset(tmp.path(), &rows, opts).unwrap(); + assert_eq!(stats.rows_written, 5); + assert_eq!(stats.row_groups_written, 3); + let actual = read_parquet_rows(&tmp.path().join("corporate_actions/part.parquet")); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } +} + +#[test] +fn late_declared_date_with_ex_date_fallback_is_accepted() { + let tmp = TempDirGuard::new("late-declared"); + let ex = day(2024, 5, 1); + let late_decl = day(2024, 5, 10); + let rows = vec![ + CorporateActionsParquetRow { + listing_id: 7, + ex_date: ex, + declared_date: Some(late_decl), + kind: CorporateActionKind::Dividend, + ratio: None, + cash_amount: Some(0.55), + currency: Some(Cow::Borrowed("USD")), + successor_listing_id: None, + terminal_return: None, + known_at_micros: known_at_from_day(ex), + known_at_source: KnownAtSource::ExDateFallback, + }, + CorporateActionsParquetRow { + listing_id: 8, + ex_date: ex, + declared_date: Some(late_decl), + kind: CorporateActionKind::Split, + ratio: Some(3.0), + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: None, + known_at_micros: known_at_from_day(ex), + known_at_source: KnownAtSource::ExDateFallback, + }, + ]; + let stats = + write_corporate_actions_dataset(tmp.path(), &rows, CorporateActionsWriteOptions::default()) + .unwrap(); + assert_eq!(stats.rows_written, 2); + let actual = read_parquet_rows(&tmp.path().join("corporate_actions/part.parquet")); + assert_eq!(actual.len(), 2); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } +} + +#[test] +fn unsorted_input_after_flushed_row_group_reports_both_keys_and_preserves_existing_file() { + let tmp = TempDirGuard::new("unsorted-after-rg"); + let (part, before) = seed_existing(tmp.path()); + let d1 = day(2024, 1, 10); + let d2 = day(2024, 2, 10); + let rows = vec![ + make_split_row(10, d1, None, 2.0), + make_div_row(10, d2, None, 0.25, "USD"), + // Flushed row group 1 above (row_group_rows = 2); now regress ex_date. + make_split_row(10, d1, None, 1.5), + ]; + let opts = CorporateActionsWriteOptions { + row_group_rows: 2, + ..CorporateActionsWriteOptions::default() + }; + let err = write_corporate_actions_dataset(tmp.path(), &rows, opts).unwrap_err(); + assert!( + matches!( + err, + ParquetCorporateActionsError::UnsortedInput { + prev_listing_id: 10, + prev_ex_date, + prev_kind: CorporateActionKind::Dividend, + listing_id: 10, + ex_date, + kind: CorporateActionKind::Split, + } if prev_ex_date == d2 && ex_date == d1 + ), + "expected UnsortedInput with exact keys, got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn nan_in_forbidden_field_is_rejected_not_treated_as_empty() { + let tmp = TempDirGuard::new("nan-forbidden"); + let d = day(2024, 4, 1); + let row = CorporateActionsParquetRow { + cash_amount: Some(f64::NAN), + ..make_split_row(15, d, None, 2.0) + }; + let err = write_corporate_actions_dataset( + tmp.path(), + &[row], + CorporateActionsWriteOptions::default(), + ) + .unwrap_err(); + assert!( + matches!( + err, + ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 15, + ex_date, + kind: CorporateActionKind::Split, + field: "cash_amount", + value: ForbiddenFieldValue::Float(v), + } if ex_date == d && v.is_nan() + ), + "expected ForbiddenFieldForKind with NaN float payload, got {err:?}" + ); + assert!(!tmp.path().join("corporate_actions").exists()); +} + +#[test] +fn invalid_first_row_creates_no_output_directory() { + let tmp = TempDirGuard::new("invalid-first-row"); + let out_dir = tmp.path().join("fresh-root"); + let bad = CorporateActionsParquetRow { + ratio: Some(0.0), + ..make_split_row(99, day(2024, 1, 2), None, 2.0) + }; + let err = + write_corporate_actions_dataset(&out_dir, &[bad], CorporateActionsWriteOptions::default()) + .unwrap_err(); + assert!(matches!( + err, + ParquetCorporateActionsError::InvalidRatio { + listing_id: 99, + value: Some(v), + .. + } if v == 0.0 + )); + assert!( + !out_dir.exists(), + "invalid first row must not create out_dir" + ); +} + +#[test] +fn bad_options_are_rejected_before_consuming_input_iterator() { + let tmp = TempDirGuard::new("bad-opts-no-poll"); + let polled = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let polled_clone = Arc::clone(&polled); + let iter = std::iter::from_fn(move || { + polled_clone.store(true, std::sync::atomic::Ordering::SeqCst); + Some(make_split_row(1, day(2024, 1, 2), None, 2.0)) + }); + let err = write_corporate_actions_dataset( + tmp.path(), + iter, + CorporateActionsWriteOptions { + row_group_rows: 0, + ..CorporateActionsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetCorporateActionsError::InvalidRowGroupRows + )); + assert!( + !polled.load(std::sync::atomic::Ordering::SeqCst), + "input iterator must not be polled when row_group_rows == 0" + ); + + let polled_z = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let polled_z_clone = Arc::clone(&polled_z); + let iter_z = std::iter::from_fn(move || { + polled_z_clone.store(true, std::sync::atomic::Ordering::SeqCst); + Some(make_split_row(1, day(2024, 1, 2), None, 2.0)) + }); + let err_z = write_corporate_actions_dataset( + tmp.path(), + iter_z, + CorporateActionsWriteOptions { + zstd_level: 99, + ..CorporateActionsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!( + err_z, + ParquetCorporateActionsError::InvalidZstdLevel { level: 99, .. } + )); + assert!( + !polled_z.load(std::sync::atomic::Ordering::SeqCst), + "input iterator must not be polled when zstd_level is invalid" + ); +} + +#[test] +fn zstd_min_and_max_levels_1_and_22_both_succeed() { + let tmp = TempDirGuard::new("zstd-min-max"); + let rows = vec![ + make_split_row(1, day(2024, 1, 15), Some(day(2024, 1, 2)), 2.0), + make_div_row(1, day(2024, 3, 15), None, 0.50, "USD"), + make_delisting_row(2, day(2024, 6, 30), -0.45), + ]; + for level in [1, 22] { + let out = tmp.path().join(format!("zstd-{level}")); + let stats = write_corporate_actions_dataset( + &out, + &rows, + CorporateActionsWriteOptions { + zstd_level: level, + ..CorporateActionsWriteOptions::default() + }, + ) + .unwrap(); + assert_eq!(stats.rows_written, rows.len()); + let actual = read_parquet_rows(&out.join("corporate_actions/part.parquet")); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } + } +} + +#[test] +fn error_display_includes_listing_and_value_and_io_preserves_source() { + let d = day(2024, 7, 1); + let err_curr = ParquetCorporateActionsError::InvalidCurrency { + listing_id: 777, + ex_date: d, + value: Some(" ".to_owned()), + }; + let msg_curr = err_curr.to_string(); + assert!(msg_curr.contains("777"), "msg={msg_curr}"); + assert!(msg_curr.contains(" "), "msg={msg_curr}"); + + let err_forbid = ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: 888, + ex_date: d, + kind: CorporateActionKind::Split, + field: "cash_amount", + value: ForbiddenFieldValue::Float(1.25), + }; + let msg_forbid = err_forbid.to_string(); + assert!(msg_forbid.contains("888"), "msg={msg_forbid}"); + assert!(msg_forbid.contains("cash_amount"), "msg={msg_forbid}"); + assert!(msg_forbid.contains("1.25"), "msg={msg_forbid}"); + + let io_err = ParquetCorporateActionsError::Io { + path: PathBuf::from("/tmp/dummy.parquet"), + source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied"), + }; + let src = io_err.source().expect("Io error must expose source()"); + assert!(src.to_string().contains("denied")); +} diff --git a/tools/curate-etl/src/parquet_events.rs b/tools/curate-etl/src/parquet_events.rs new file mode 100644 index 00000000..64c07c5c --- /dev/null +++ b/tools/curate-etl/src/parquet_events.rs @@ -0,0 +1,1376 @@ +//! Streaming, atomic, year-partitioned Zstd Parquet writer for `events`. +//! +//! Writes `/events/year=YYYY/part.parquet` files matching the 7-column contract schema in +//! `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 3. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 4. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 5. `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 6. `subtype` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 7. `payload_json` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::collections::BTreeMap; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use parquet::basic::{ + Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel, +}; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::events::{partition_year_utc, EventRow}; +pub use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; +use crate::parquet_publish::{ + create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, + rollback_published, write_byte_array_col, write_i32_col, write_i64_col, write_interned_str_col, + DatasetFileLock, PublishIoError, PublishedPartition, StagingFileGuard, StringInterner, + DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, +}; +pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; + +/// Single `events` row matching the `design/DATA-CONTRACTS.md` Parquet schema. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventsParquetRow { + pub listing_id: i32, + pub ts_micros: i64, + pub known_at_micros: i64, + pub known_at_source: Cow<'static, str>, + pub kind: Cow<'static, str>, + pub subtype: String, + pub payload_json: String, +} + +impl From<&EventRow> for EventsParquetRow { + fn from(row: &EventRow) -> Self { + Self { + listing_id: row.key, + ts_micros: row.ts_micros, + known_at_micros: row.known_at_micros, + known_at_source: Cow::Borrowed(row.known_at_source), + kind: Cow::Borrowed(row.kind), + subtype: row.subtype.clone(), + payload_json: row.payload_json.clone(), + } + } +} + +impl From> for EventsParquetRow { + fn from(row: EventRow) -> Self { + Self { + listing_id: row.key, + ts_micros: row.ts_micros, + known_at_micros: row.known_at_micros, + known_at_source: Cow::Borrowed(row.known_at_source), + kind: Cow::Borrowed(row.kind), + subtype: row.subtype, + payload_json: row.payload_json, + } + } +} + +/// Configuration for [`write_events_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EventsWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for EventsWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_events_dataset`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct EventsWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub rows_by_year: BTreeMap, +} + +/// Typed error returned by [`write_events_dataset`]. +#[derive(Debug)] +pub enum ParquetEventsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + UnsortedInput { + row_index: usize, + prev_listing_id: i32, + prev_ts_micros: i64, + listing_id: i32, + ts_micros: i64, + }, + DuplicateRow { + row_index: usize, + listing_id: i32, + ts_micros: i64, + }, + KnownAtBeforeTs { + row_index: usize, + listing_id: i32, + ts_micros: i64, + known_at_micros: i64, + }, + PartitionYearOutOfRange { + row_index: usize, + listing_id: i32, + ts_micros: i64, + year: i32, + min_year: i32, + max_year: i32, + }, + EmptyKnownAtSource { + row_index: usize, + listing_id: i32, + ts_micros: i64, + }, + EmptyKind { + row_index: usize, + listing_id: i32, + ts_micros: i64, + }, + EmptySubtype { + row_index: usize, + listing_id: i32, + ts_micros: i64, + }, + EmptyPayloadJson { + row_index: usize, + listing_id: i32, + ts_micros: i64, + }, + LockTimeout { + path: PathBuf, + waited: Duration, + }, + RollbackFailed { + cause: Box, + failures: Vec, + }, + Io { + path: PathBuf, + source: io::Error, + }, + Parquet { + path: PathBuf, + source: ParquetError, + }, +} + +impl fmt::Display for ParquetEventsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidRowGroupRows => { + write!(f, "invalid row_group_rows: must be greater than 0") + } + Self::InvalidZstdLevel { level } => { + write!(f, "invalid Zstd compression level: {level}") + } + Self::UnsortedInput { + row_index, + prev_listing_id, + prev_ts_micros, + listing_id, + ts_micros, + } => write!( + f, + "unsorted input at row {row_index}: ({listing_id}, {ts_micros}) follows ({prev_listing_id}, {prev_ts_micros})" + ), + Self::DuplicateRow { + row_index, + listing_id, + ts_micros, + } => write!( + f, + "duplicate event row at row {row_index}: (listing_id={listing_id}, ts_micros={ts_micros})" + ), + Self::KnownAtBeforeTs { + row_index, + listing_id, + ts_micros, + known_at_micros, + } => write!( + f, + "known_at {known_at_micros} is before ts {ts_micros} at row {row_index} for listing_id {listing_id}" + ), + Self::PartitionYearOutOfRange { + row_index, + listing_id, + ts_micros, + year, + min_year, + max_year, + } => write!( + f, + "partition year {year} (ts_micros {ts_micros}) at row {row_index} for listing_id {listing_id} is outside allowed range {min_year}..={max_year}" + ), + Self::EmptyKnownAtSource { + row_index, + listing_id, + ts_micros, + } => write!( + f, + "empty known_at_source at row {row_index} for ({listing_id}, {ts_micros}): must be non-empty" + ), + Self::EmptyKind { + row_index, + listing_id, + ts_micros, + } => write!( + f, + "empty kind at row {row_index} for ({listing_id}, {ts_micros}): must be non-empty" + ), + Self::EmptySubtype { + row_index, + listing_id, + ts_micros, + } => write!( + f, + "empty subtype at row {row_index} for ({listing_id}, {ts_micros}): must be non-empty" + ), + Self::EmptyPayloadJson { + row_index, + listing_id, + ts_micros, + } => write!( + f, + "empty payload_json at row {row_index} for ({listing_id}, {ts_micros}): must be non-empty" + ), + Self::LockTimeout { path, waited } => write!( + f, + "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", + waited.as_millis(), + path.display() + ), + Self::RollbackFailed { cause, failures } => { + write!( + f, + "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", + failures.len() + )?; + for failure in failures { + write!(f, " [{failure}]")?; + } + Ok(()) + } + Self::Io { path, source } => { + write!(f, "I/O error at '{}': {source}", path.display()) + } + Self::Parquet { path, source } => { + write!(f, "Parquet error at '{}': {source}", path.display()) + } + } + } +} + +impl Error for ParquetEventsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::Io { source, .. } => Some(source), + Self::Parquet { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for ParquetEventsError { + fn from(err: PublishIoError) -> Self { + match err { + PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, + PublishIoError::Io { path, source } => Self::Io { path, source }, + } + } +} + +/// Builds the exact 7-column Parquet schema for `events` per `design/DATA-CONTRACTS.md` (§3A). +pub fn events_parquet_schema() -> Result { + let fields: Vec = vec![ + Arc::new( + Type::primitive_type_builder("listing_id", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ts", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("kind", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("subtype", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("payload_json", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("events") + .with_fields(fields) + .build()?, + )) +} + +fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { + Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(zstd_level)) + .set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true) + .set_column_dictionary_enabled(ColumnPath::from("kind"), true) + .set_column_dictionary_enabled(ColumnPath::from("subtype"), false) + .set_column_dictionary_enabled(ColumnPath::from("payload_json"), false) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn compare_event_rows(a: &EventsParquetRow, b: &EventsParquetRow) -> Ordering { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) +} + +#[inline] +fn validate_row(row: &EventsParquetRow, row_index: usize) -> Result { + if row.known_at_micros < row.ts_micros { + return Err(ParquetEventsError::KnownAtBeforeTs { + row_index, + listing_id: row.listing_id, + ts_micros: row.ts_micros, + known_at_micros: row.known_at_micros, + }); + } + let year = partition_year_utc(row.ts_micros); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { + return Err(ParquetEventsError::PartitionYearOutOfRange { + row_index, + listing_id: row.listing_id, + ts_micros: row.ts_micros, + year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + if row.known_at_source.trim().is_empty() { + return Err(ParquetEventsError::EmptyKnownAtSource { + row_index, + listing_id: row.listing_id, + ts_micros: row.ts_micros, + }); + } + if row.kind.trim().is_empty() { + return Err(ParquetEventsError::EmptyKind { + row_index, + listing_id: row.listing_id, + ts_micros: row.ts_micros, + }); + } + if row.subtype.trim().is_empty() { + return Err(ParquetEventsError::EmptySubtype { + row_index, + listing_id: row.listing_id, + ts_micros: row.ts_micros, + }); + } + if row.payload_json.trim().is_empty() { + return Err(ParquetEventsError::EmptyPayloadJson { + row_index, + listing_id: row.listing_id, + ts_micros: row.ts_micros, + }); + } + Ok(year) +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + ts_micros: Vec, + known_at_micros: Vec, + known_at_source_ids: Vec, + known_at_source_interner: StringInterner, + kind_ids: Vec, + kind_interner: StringInterner, + subtype: Vec, + payload_json: Vec, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &EventsParquetRow) { + self.listing_id.push(row.listing_id); + self.ts_micros.push(row.ts_micros); + self.known_at_micros.push(row.known_at_micros); + let kas_id = self + .known_at_source_interner + .intern(row.known_at_source.as_ref()); + self.known_at_source_ids.push(kas_id); + let kind_id = self.kind_interner.intern(row.kind.as_ref()); + self.kind_ids.push(kind_id); + self.subtype.push(ByteArray::from(row.subtype.as_str())); + self.payload_json + .push(ByteArray::from(row.payload_json.as_str())); + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.ts_micros.clear(); + self.known_at_micros.clear(); + self.known_at_source_ids.clear(); + self.known_at_source_interner.clear(); + self.kind_ids.clear(); + self.kind_interner.clear(); + self.subtype.clear(); + self.payload_json.clear(); + } +} + +struct YearWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl YearWriter { + fn open( + events_dir: &Path, + year: i32, + run_id: &str, + schema: &TypePtr, + props: &WriterPropertiesPtr, + staging_guards: &mut BTreeMap, + ) -> Result { + let year_dir = events_dir.join(format!("year={year:04}")); + fs::create_dir_all(&year_dir).map_err(|source| ParquetEventsError::Io { + path: year_dir.clone(), + source, + })?; + + let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; + staging_guards.insert(year, StagingFileGuard::new(tmp_path.clone())); + let final_path = year_dir.join("part.parquet"); + + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetEventsError::Parquet { + path: tmp_path.clone(), + source, + }, + )?; + + Ok(Self { + tmp_path, + final_path, + writer, + buf: RowGroupBuffer::default(), + rows_written: 0, + row_groups_written: 0, + }) + } + + fn flush_row_group(&mut self, scratch: &mut Vec) -> Result<(), ParquetEventsError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetEventsError::Parquet { + path: self.tmp_path.clone(), + source, + }; + + let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; + + // 1. listing_id (INT32, REQUIRED) + write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; + // 2. ts (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.ts_micros).map_err(map_pq)?; + // 3. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; + // 4. known_at_source (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.known_at_source_ids, + &self.buf.known_at_source_interner, + scratch, + ) + .map_err(map_pq)?; + // 5. kind (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.kind_ids, + &self.buf.kind_interner, + scratch, + ) + .map_err(map_pq)?; + // 6. subtype (BYTE_ARRAY, REQUIRED, STRING) + write_byte_array_col(&mut rg_writer, &self.buf.subtype).map_err(map_pq)?; + // 7. payload_json (BYTE_ARRAY, REQUIRED, STRING) + write_byte_array_col(&mut rg_writer, &self.buf.payload_json).map_err(map_pq)?; + + rg_writer.close().map_err(map_pq)?; + + self.rows_written += row_count; + self.row_groups_written += 1; + self.buf.clear(); + Ok(()) + } + + fn finish_and_sync( + mut self, + scratch: &mut Vec, + ) -> Result { + self.flush_row_group(scratch)?; + + let mut buf_writer = + self.writer + .into_inner() + .map_err(|source| ParquetEventsError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer.flush().map_err(|source| ParquetEventsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetEventsError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all().map_err(|source| ParquetEventsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetEventsError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedYearFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedYearFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +fn finish_with_rollback( + cause: ParquetEventsError, + published: &[PublishedPartition], + extra_failure: Option, +) -> ParquetEventsError { + let mut failures = Vec::new(); + if let Some(failure) = extra_failure { + failures.push(failure); + } + failures.extend(rollback_published(published)); + if failures.is_empty() { + cause + } else { + ParquetEventsError::RollbackFailed { + cause: Box::new(cause), + failures, + } + } +} + +/// Streams strictly ascending `events` rows into year-partitioned Zstd Parquet files at +/// `/events/year=YYYY/part.parquet`. +/// +/// # Sort Order & Validation +/// Input rows must be strictly ascending by the `build_events` sort key: +/// `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`. +/// Out-of-order rows, exact duplicates, `known_at_micros < ts_micros`, partition years outside +/// `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR`, and empty (or whitespace-only) `known_at_source`, +/// `kind`, `subtype`, or `payload_json` return typed [`ParquetEventsError`] variants with nothing +/// published. Empty input returns `Ok(EventsWriteStats::default())` without creating +/// `/events` or touching pre-existing partitions. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/events` directory are serialized via an +/// in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. Every year +/// partition is written to an exclusively created per-run staging file (`part.parquet..tmp`), +/// flushed, and `sync_all`'d before publication. Pre-existing `part.parquet` files are backed up +/// in place (hard link with exclusive copy fallback) so the live path remains readable until +/// replaced by a single atomic `rename`; on any error or unwind, all open writers close before +/// owned staging files are unlinked, replaced partitions are restored from backup, and newly +/// published partitions are removed (reporting rollback errors via +/// [`ParquetEventsError::RollbackFailed`]). +pub fn write_events_dataset( + out_dir: P, + rows: I, + options: EventsWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_events_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _, _| {}, + ) +} + +fn write_events_dataset_with_hooks( + out_dir: P, + rows: I, + options: EventsWriteOptions, + lock_timeout: Duration, + on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(i32, &Path, Option<&Path>), +{ + write_events_dataset_with_lock_and_backup_hooks( + out_dir, + rows, + options, + lock_timeout, + || {}, + on_after_backup, + ) +} + +fn write_events_dataset_with_lock_and_backup_hooks( + out_dir: P, + rows: I, + options: EventsWriteOptions, + lock_timeout: Duration, + mut on_lock_contended: G, + mut on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + G: FnMut(), + F: FnMut(i32, &Path, Option<&Path>), +{ + if options.row_group_rows == 0 { + return Err(ParquetEventsError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetEventsError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(EventsWriteStats::default()); + }; + validate_row(first_item.borrow(), 0)?; + + let out_dir = out_dir.as_ref(); + let events_dir = out_dir.join("events"); + let schema = events_parquet_schema().map_err(|source| ParquetEventsError::Parquet { + path: events_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&events_dir).map_err(|source| ParquetEventsError::Io { + path: events_dir.clone(), + source, + })?; + + // Serialize writers targeting the same dataset directory across threads and processes. + // Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held, + // and only after all staging/publication/rollback work has finished. + let dataset_mu = dataset_mutex(&events_dir); + let _in_process_guard = match dataset_mu.try_lock() { + Ok(guard) => guard, + Err(std::sync::TryLockError::Poisoned(err)) => err.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + on_lock_contended(); + dataset_mu.lock().unwrap_or_else(|err| err.into_inner()) + } + }; + let _file_lock = DatasetFileLock::acquire_with_timeout(&events_dir, lock_timeout)?; + + let run_id = next_run_id(); + // Declared before `writers` so Rust's reverse drop order closes all Parquet file handles + // before unlinking owned `.tmp` staging files on error or panic unwind. + let mut staging_guards: BTreeMap = BTreeMap::new(); + let mut writers: BTreeMap = BTreeMap::new(); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let synced_files: Vec<(i32, SyncedYearFile)> = { + let mut prev_item: Option = None; + + for (row_index, item) in std::iter::once(first_item).chain(row_iter).enumerate() { + let row = item.borrow(); + if let Some(prev) = prev_item.as_ref() { + let prev_row = prev.borrow(); + match compare_event_rows(row, prev_row) { + Ordering::Equal => { + return Err(ParquetEventsError::DuplicateRow { + row_index, + listing_id: row.listing_id, + ts_micros: row.ts_micros, + }); + } + Ordering::Less => { + return Err(ParquetEventsError::UnsortedInput { + row_index, + prev_listing_id: prev_row.listing_id, + prev_ts_micros: prev_row.ts_micros, + listing_id: row.listing_id, + ts_micros: row.ts_micros, + }); + } + Ordering::Greater => {} + } + } + let year = validate_row(row, row_index)?; + + let yw = match writers.entry(year) { + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::btree_map::Entry::Vacant(entry) => { + let opened = YearWriter::open( + &events_dir, + year, + &run_id, + &schema, + &props, + &mut staging_guards, + )?; + entry.insert(opened) + } + }; + + yw.buf.push(row); + if yw.buf.len() == options.row_group_rows { + yw.flush_row_group(&mut scratch)?; + } + prev_item = Some(item); + } + + let mut synced = Vec::with_capacity(writers.len()); + let drained: Vec<(i32, YearWriter)> = std::mem::take(&mut writers).into_iter().collect(); + for (year, yw) in drained { + let file = yw.finish_and_sync(&mut scratch)?; + synced.push((year, file)); + } + synced + }; + + let mut stats = EventsWriteStats::default(); + let mut published: Vec = Vec::with_capacity(synced_files.len()); + for (year, file) in synced_files { + let backup_path = match fs::symlink_metadata(&file.final_path) { + Ok(meta) if !meta.is_dir() => { + match create_backup_preserving_live(&file.final_path, &run_id) { + Ok(bak) => Some(bak), + Err(err) => { + return Err(finish_with_rollback(err.into(), &published, None)); + } + } + } + // Directory occupying final_path: leave it in place so the rename below fails + // cleanly and triggers rollback of all earlier partitions. + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + let err = ParquetEventsError::Io { + path: file.final_path, + source, + }; + return Err(finish_with_rollback(err, &published, None)); + } + }; + + on_after_backup(year, &file.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { + let extra_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: file.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let err = ParquetEventsError::Io { + path: file.final_path, + source, + }; + return Err(finish_with_rollback(err, &published, extra_failure)); + } + + if let Some(guard) = staging_guards.get_mut(&year) { + guard.disarm(); + } + + published.push(PublishedPartition { + final_path: file.final_path, + backup_path, + }); + stats.rows_written += file.rows_written; + stats.files_written += 1; + stats.row_groups_written += file.row_groups_written; + stats.bytes_written += file.bytes; + stats.rows_by_year.insert(year, file.rows_written); + } + + for part in &published { + if let Some(bak) = &part.backup_path { + let _ = fs::remove_file(bak); + } + } + + Ok(stats) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + + use parquet::basic::{ConvertedType, Encoding}; + use parquet::column::reader::ColumnReader; + use parquet::file::reader::{FileReader, SerializedFileReader}; + + use super::*; + use crate::events::{ + build_events, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, + }; + use crate::split::ymd_to_epoch_days; + + static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + + pub(super) struct TempDirGuard { + path: PathBuf, + } + + impl TempDirGuard { + pub(super) fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-pq-events-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + pub(super) fn path(&self) -> &Path { + &self.path + } + } + + impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + pub(super) fn utc_micros( + year: i32, + month: u32, + day: u32, + hour: u8, + minute: u8, + second: u8, + micro: i64, + ) -> i64 { + let epoch_day = ymd_to_epoch_days(year, month, day).expect("valid test date"); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000_000 + micro + } + + pub(super) fn make_event_row( + listing_id: i32, + ts_micros: i64, + known_at_micros: i64, + known_at_source: &'static str, + kind: &'static str, + subtype: &str, + payload_json: &str, + ) -> EventsParquetRow { + EventsParquetRow { + listing_id, + ts_micros, + known_at_micros, + known_at_source: Cow::Borrowed(known_at_source), + kind: Cow::Borrowed(kind), + subtype: subtype.to_string(), + payload_json: payload_json.to_string(), + } + } + + pub(super) fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_rows = meta.row_group(rg_idx).num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_i32_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i32 records"); + assert!(n > 0, "unexpected short read in INT32 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + + let read_i64_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i64 records"); + assert!(n > 0, "unexpected short read in INT64 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + + let read_str_col = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read byte_array records"); + assert!(n > 0, "unexpected short read in BYTE_ARRAY column {col_idx}"); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + raw.iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) + .collect() + }; + + let listing_ids = read_i32_col(0); + let ts = read_i64_col(1); + let known_at = read_i64_col(2); + let known_at_source = read_str_col(3); + let kind = read_str_col(4); + let subtype = read_str_col(5); + let payload_json = read_str_col(6); + + for i in 0..rg_rows { + out.push(EventsParquetRow { + listing_id: listing_ids[i], + ts_micros: ts[i], + known_at_micros: known_at[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + + out + } + + pub(super) fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + fn walk(dir: &Path) { + for entry in fs::read_dir(dir).expect("read_dir") { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(&path); + } else { + let name = path + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or_default(); + assert!( + !name.ends_with(".tmp") + && !name.ends_with(".bak") + && name != ".write.lock", + "unexpected transient file left behind: {}", + path.display() + ); + } + } + } + walk(dir); + } + + #[test] + fn schema_matches_contract_columns_types_and_order() { + let schema = events_parquet_schema().expect("build schema"); + assert_eq!(schema.name(), "events"); + + let fields = schema.get_fields(); + assert_eq!(fields.len(), 7); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 7] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "ts", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "known_at_source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "kind", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "subtype", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "payload_json", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + let field = &fields[idx]; + assert_eq!(field.name(), name, "column {idx} name"); + assert_eq!(field.get_physical_type(), phys, "column {idx} physical type"); + assert_eq!( + field.get_basic_info().repetition(), + rep, + "column {idx} repetition" + ); + assert_eq!( + field.get_basic_info().logical_type_ref().cloned(), + logical, + "column {idx} logical type" + ); + assert_eq!( + field.get_basic_info().converted_type(), + converted, + "column {idx} converted type" + ); + } + } + + #[test] + fn build_events_round_trip_partitions_by_utc_year_with_zstd_and_multi_row_groups() { + let tmp = TempDirGuard::new("roundtrip"); + + let filings = vec![ + // 2022 filing + QmFiling { + key: 10_i32, + timefiled: "2022-06-15T10:30:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-2022-01".to_string()), + url: Some("https://sec.example/2022-10q".to_string()), + }, + // 2023 8-K linked to same-day earnings + QmFiling { + key: 10_i32, + timefiled: "2023-05-04T16:10:00 EDT".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("F-2023-8K".to_string()), + url: Some("https://sec.example/2023-8k".to_string()), + }, + // Second 2023 8-K so a single row group contains repeated `subtype = "8-k"` values + QmFiling { + key: 10_i32, + timefiled: "2023-05-05T10:00:00 EDT".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("F-2023-8K-2".to_string()), + url: Some("https://sec.example/2023-8k-2".to_string()), + }, + // Late-evening ET on 2024-12-31 21:30:00 EST -> 2025-01-01 02:30:00 UTC (year=2025) + QmFiling { + key: 10_i32, + timefiled: "2024-12-31T21:30:00 EST".to_string(), + form_type: "News release".to_string(), + filing_id: Some("F-2024-EVE".to_string()), + url: None, + }, + // 2024 filing for listing 20 + QmFiling { + key: 20_i32, + timefiled: "2024-03-15T08:00:00 EDT".to_string(), + form_type: "10-K/A".to_string(), + filing_id: Some("F-2024-10KA".to_string()), + url: Some("https://sec.example/2024-10ka".to_string()), + }, + ]; + + let earnings = vec![ + // Linked to 2023-05-04 8-K + QmEarning { + key: 10_i32, + report_date: ymd_to_epoch_days(2023, 5, 4).unwrap(), + announce_time: "AMC".to_string(), + fiscal_period_end: Some(ymd_to_epoch_days(2023, 3, 31).unwrap()), + actual_eps: Some(1.42), + revenue: Some(9_500_000_000.0), + }, + // Unlinked -> lagged to 2024-08-01 16:05 EDT (20:05 UTC, year=2024) + QmEarning { + key: 20_i32, + report_date: ymd_to_epoch_days(2024, 8, 1).unwrap(), + announce_time: "BTO".to_string(), + fiscal_period_end: Some(ymd_to_epoch_days(2024, 6, 30).unwrap()), + actual_eps: Some(0.85), + revenue: None, + }, + ]; + + let built = build_events(filings, earnings); + assert_eq!(built.stats.filings_out, 5); + assert_eq!(built.stats.earnings_linked_to_filing, 1); + assert_eq!(built.stats.earnings_lagged_1605, 1); + + let rows_from_ref: Vec = + built.rows.iter().map(EventsParquetRow::from).collect(); + let mut rows: Vec = + built.rows.into_iter().map(EventsParquetRow::from).collect(); + assert_eq!(rows_from_ref, rows); + + // Add exact UTC year boundary rows: 2023-12-31T23:59:59.999999Z and 2024-01-01T00:00:00.000000Z + rows.push(make_event_row( + 30, + utc_micros(2023, 12, 31, 23, 59, 59, 999_999), + utc_micros(2023, 12, 31, 23, 59, 59, 999_999), + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + EVENT_KIND_FILING, + "8-k", + r#"{"boundary":"end_2023"}"#, + )); + rows.push(make_event_row( + 30, + utc_micros(2024, 1, 1, 0, 0, 0, 0), + utc_micros(2024, 1, 1, 0, 0, 0, 0), + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + EVENT_KIND_FILING, + "8-k", + r#"{"boundary":"start_2024"}"#, + )); + // Also include a row where known_at_micros > ts_micros (e.g. lagged reporting). + rows.push(make_event_row( + 30, + utc_micros(2025, 2, 10, 14, 0, 0, 0), + utc_micros(2025, 2, 10, 21, 5, 0, 0), + KNOWN_AT_SOURCE_STATUTORY_LAG, + EVENT_KIND_EARNINGS, + "amc", + r#"{"lagged":true}"#, + )); + + let opts = EventsWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }; + let stats = write_events_dataset(tmp.path(), &rows, opts).expect("write events"); + + let expected_by_year = BTreeMap::from([(2022, 1), (2023, 4), (2024, 3), (2025, 2)]); + assert_eq!(stats.rows_written, rows.len()); + assert_eq!(stats.files_written, 4); + // 2022: 1 row (1 rg), 2023: 4 rows (2 rgs), 2024: 3 rows (2 rgs), 2025: 2 rows (1 rg) + assert_eq!(stats.row_groups_written, 6); + assert_eq!(stats.rows_by_year, expected_by_year); + + let expected_schema = events_parquet_schema().unwrap(); + let mut total_bytes = 0u64; + for (&year, &expected_count) in &expected_by_year { + let path = tmp + .path() + .join(format!("events/year={year:04}/part.parquet")); + assert!(path.is_file(), "missing {}", path.display()); + total_bytes += fs::metadata(&path).unwrap().len(); + + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref()); + assert_eq!(meta.file_metadata().num_rows() as usize, expected_count); + + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "year {year} column {} must be ZSTD", + col.column_path() + ); + } + for dict_col in [3usize, 4usize] { + assert!( + rg.column(dict_col).encodings().any(|e| matches!( + e, + Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY + )), + "year {year} column {dict_col} should use dictionary encoding" + ); + } + for plain_col in [5usize, 6usize] { + assert!( + !rg.column(plain_col).encodings().any(|e| matches!( + e, + Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY + )), + "year {year} column {plain_col} must not use dictionary encoding" + ); + assert!( + rg.column(plain_col) + .encodings() + .any(|e| e == Encoding::PLAIN), + "year {year} column {plain_col} should use PLAIN encoding" + ); + } + } + + let actual = read_parquet_rows(&path); + let expected: Vec = rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == year) + .cloned() + .collect(); + assert_eq!(actual, expected, "year {year} row mismatch"); + } + assert_eq!(stats.bytes_written, total_bytes); + assert_no_transient_files(&tmp.path().join("events")); + } +} + +#[cfg(test)] +#[path = "parquet_events_tests.rs"] +mod edge_case_tests; diff --git a/tools/curate-etl/src/parquet_events_tests.rs b/tools/curate-etl/src/parquet_events_tests.rs new file mode 100644 index 00000000..bd12232f --- /dev/null +++ b/tools/curate-etl/src/parquet_events_tests.rs @@ -0,0 +1,1215 @@ +//! Edge-case, validation, atomic-publish, rollback, and concurrency tests for `parquet_events`. + +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::error::Error; +use std::fs::{self, File}; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::path::{Path, PathBuf}; +use std::sync::{mpsc, Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use parquet::basic::Compression; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::tests::{assert_no_transient_files, make_event_row, read_parquet_rows, utc_micros, TempDirGuard}; +use super::{ + write_events_dataset, write_events_dataset_with_hooks, + write_events_dataset_with_lock_and_backup_hooks, EventsParquetRow, EventsWriteOptions, + EventsWriteStats, ParquetEventsError, DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, +}; +use crate::events::{ + build_events, partition_year_utc, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::parquet_publish::DEFAULT_LOCK_TIMEOUT; +use crate::split::ymd_to_epoch_days; + +fn base_row(listing_id: i32, year: i32, month: u32, day: u32) -> EventsParquetRow { + let ts = utc_micros(year, month, day, 14, 30, 0, 0); + make_event_row( + listing_id, + ts, + ts, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + EVENT_KIND_FILING, + "8-k", + r#"{"form_type":"8-K","is_amendment":false}"#, + ) +} + +#[test] +fn non_ascii_json_escaped_and_large_64kib_payloads_round_trip_and_are_byte_identical() { + let tmp_a = TempDirGuard::new("payload-a"); + let tmp_b = TempDirGuard::new("payload-b"); + + let large_body = "é".repeat(48 * 1024); // 96 KiB UTF-8 + let large_payload = format!( + r#"{{"note":"line1\nline2\t\"quoted\"\\slash\u0000","body":"{large_body}"}}"# + ); + assert!(large_payload.len() > 64 * 1024); + + let non_ascii_payload = + r#"{"issuer":"Société Générale / 日本銀行 / 🚀","escape":"a\"b\\c\nd\te\u0000f"}"#; + + let rows = vec![ + make_event_row( + 1, + utc_micros(2023, 6, 15, 13, 0, 0, 0), + utc_micros(2023, 6, 15, 13, 0, 0, 0), + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + EVENT_KIND_FILING, + "news_release", + non_ascii_payload, + ), + make_event_row( + 1, + utc_micros(2024, 1, 10, 12, 0, 0, 0), + utc_micros(2024, 1, 10, 21, 5, 0, 0), + KNOWN_AT_SOURCE_STATUTORY_LAG, + EVENT_KIND_EARNINGS, + "amc", + &large_payload, + ), + ]; + + let opts = EventsWriteOptions::default(); + let stats_a = write_events_dataset(tmp_a.path(), &rows, opts).unwrap(); + let stats_b = write_events_dataset(tmp_b.path(), &rows, opts).unwrap(); + assert_eq!(stats_a, stats_b); + + for year in [2023, 2024] { + let pa = tmp_a + .path() + .join(format!("events/year={year:04}/part.parquet")); + let pb = tmp_b + .path() + .join(format!("events/year={year:04}/part.parquet")); + assert_eq!( + fs::read(&pa).unwrap(), + fs::read(&pb).unwrap(), + "year {year} output must be byte-identical across runs" + ); + let actual = read_parquet_rows(&pa); + let expected: Vec = rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == year) + .cloned() + .collect(); + assert_eq!(actual, expected); + } + assert_no_transient_files(&tmp_a.path().join("events")); + assert_no_transient_files(&tmp_b.path().join("events")); +} + +#[test] +fn row_group_boundaries_exact_plus_one_single_and_interleaved_years() { + // Interleaved years across listings: listing 1 has 2023 & 2024, listing 2 has 2023 & 2024, etc. + let mut rows = Vec::new(); + for lid in 1..=5_i32 { + rows.push(base_row(lid, 2023, 5, lid as u32)); + rows.push(base_row(lid, 2024, 5, lid as u32)); + } + + // Exact multiple: 5 rows per year with row_group_rows = 5 -> 1 rg/year + let tmp_eq = TempDirGuard::new("rg-eq"); + let s_eq = write_events_dataset( + tmp_eq.path(), + &rows, + EventsWriteOptions { + row_group_rows: 5, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap(); + assert_eq!(s_eq.files_written, 2); + assert_eq!(s_eq.row_groups_written, 2); + assert_eq!(s_eq.rows_by_year, BTreeMap::from([(2023, 5), (2024, 5)])); + + // Plus-one: 5 rows per year with row_group_rows = 4 -> 2 rgs/year ([4, 1]) + let tmp_plus = TempDirGuard::new("rg-plus"); + let s_plus = write_events_dataset( + tmp_plus.path(), + &rows, + EventsWriteOptions { + row_group_rows: 4, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap(); + assert_eq!(s_plus.row_groups_written, 4); + for year in [2023, 2024] { + let path = tmp_plus + .path() + .join(format!("events/year={year:04}/part.parquet")); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.num_row_groups(), 2); + assert_eq!(meta.row_group(0).num_rows(), 4); + assert_eq!(meta.row_group(1).num_rows(), 1); + } + + // row_group_rows = 1 -> 5 rgs/year + let tmp_one = TempDirGuard::new("rg-one"); + let s_one = write_events_dataset( + tmp_one.path(), + &rows, + EventsWriteOptions { + row_group_rows: 1, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap(); + assert_eq!(s_one.row_groups_written, 10); + for year in [2023, 2024] { + let actual = read_parquet_rows( + &tmp_one + .path() + .join(format!("events/year={year:04}/part.parquet")), + ); + let expected: Vec = rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == year) + .cloned() + .collect(); + assert_eq!(actual, expected); + } +} + +#[test] +fn empty_input_creates_no_directory_and_preserves_existing_dataset() { + let tmp_fresh = TempDirGuard::new("empty-fresh"); + let stats = write_events_dataset( + tmp_fresh.path(), + std::iter::empty::(), + EventsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats, EventsWriteStats::default()); + assert!(!tmp_fresh.path().join("events").exists()); + + let tmp_existing = TempDirGuard::new("empty-existing"); + let seed = vec![base_row(1, 2024, 3, 1)]; + write_events_dataset(tmp_existing.path(), &seed, EventsWriteOptions::default()).unwrap(); + let part = tmp_existing.path().join("events/year=2024/part.parquet"); + let before = fs::read(&part).unwrap(); + + let stats2 = write_events_dataset( + tmp_existing.path(), + std::iter::empty::(), + EventsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats2, EventsWriteStats::default()); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp_existing.path().join("events")); +} + +#[test] +fn invalid_options_rejected_without_touching_filesystem() { + let tmp = TempDirGuard::new("bad-opts"); + let rows = vec![base_row(1, 2024, 3, 1)]; + + let err_rg = write_events_dataset( + tmp.path(), + &rows, + EventsWriteOptions { + row_group_rows: 0, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap_err(); + assert!(matches!(err_rg, ParquetEventsError::InvalidRowGroupRows)); + assert!(!tmp.path().join("events").exists()); + + for bad_level in [23, 99] { + let err_zstd = write_events_dataset( + tmp.path(), + &rows, + EventsWriteOptions { + row_group_rows: 10, + zstd_level: bad_level, + }, + ) + .unwrap_err(); + assert!( + matches!(err_zstd, ParquetEventsError::InvalidZstdLevel { level } if level == bad_level), + "expected InvalidZstdLevel({bad_level}), got {err_zstd:?}" + ); + assert!(!tmp.path().join("events").exists()); + } +} + +#[test] +fn unsorted_and_duplicate_rows_rejected_with_exact_row_index_across_all_sort_keys() { + let tmp = TempDirGuard::new("sort-checks"); + let seed = vec![base_row(1, 2024, 1, 1)]; + write_events_dataset(tmp.path(), &seed, EventsWriteOptions::default()).unwrap(); + let part_2024 = tmp.path().join("events/year=2024/part.parquet"); + let before = fs::read(&part_2024).unwrap(); + + let t1 = utc_micros(2024, 5, 1, 10, 0, 0, 0); + let t2 = utc_micros(2024, 5, 2, 10, 0, 0, 0); + let r_base = make_event_row( + 10, + t1, + t1 + 1_000_000, + KNOWN_AT_SOURCE_STATUTORY_LAG, + EVENT_KIND_FILING, + "8-k", + r#"{"b":1}"#, + ); + + let unsorted_cases: Vec<(&str, Vec, usize)> = vec![ + ( + "listing_id", + vec![base_row(2, 2024, 5, 1), base_row(1, 2024, 5, 2)], + 1, + ), + ( + "ts_micros", + vec![ + make_event_row(1, t2, t2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, EVENT_KIND_FILING, "8-k", "{}"), + make_event_row(1, t1, t1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, EVENT_KIND_FILING, "8-k", "{}"), + ], + 1, + ), + ( + "kind", + vec![ + r_base.clone(), + make_event_row(10, t1, t1 + 1_000_000, KNOWN_AT_SOURCE_STATUTORY_LAG, EVENT_KIND_EARNINGS, "8-k", r#"{"b":1}"#), + ], + 1, + ), + ( + "subtype", + vec![ + r_base.clone(), + make_event_row(10, t1, t1 + 1_000_000, KNOWN_AT_SOURCE_STATUTORY_LAG, EVENT_KIND_FILING, "10-k", r#"{"b":1}"#), + ], + 1, + ), + ( + "payload_json", + vec![ + r_base.clone(), + make_event_row(10, t1, t1 + 1_000_000, KNOWN_AT_SOURCE_STATUTORY_LAG, EVENT_KIND_FILING, "8-k", r#"{"a":1}"#), + ], + 1, + ), + ( + "known_at_micros", + vec![ + r_base.clone(), + make_event_row(10, t1, t1, KNOWN_AT_SOURCE_STATUTORY_LAG, EVENT_KIND_FILING, "8-k", r#"{"b":1}"#), + ], + 1, + ), + ( + "known_at_source", + vec![ + r_base.clone(), + make_event_row(10, t1, t1 + 1_000_000, KNOWN_AT_SOURCE_FILING_TIMESTAMP, EVENT_KIND_FILING, "8-k", r#"{"b":1}"#), + ], + 1, + ), + ]; + + for (label, rows, expected_idx) in unsorted_cases { + let err = write_events_dataset(tmp.path(), &rows, EventsWriteOptions::default()) + .unwrap_err(); + assert!( + matches!(err, ParquetEventsError::UnsortedInput { row_index, .. } if row_index == expected_idx), + "case {label}: expected UnsortedInput at row {expected_idx}, got {err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before); + assert_no_transient_files(&tmp.path().join("events")); + } + + // Exact duplicate at row_index = 2 + let dup_rows = vec![base_row(1, 2024, 1, 1), r_base.clone(), r_base]; + let dup_err = + write_events_dataset(tmp.path(), &dup_rows, EventsWriteOptions::default()).unwrap_err(); + assert!( + matches!(dup_err, ParquetEventsError::DuplicateRow { row_index: 2, listing_id: 10, .. }), + "expected DuplicateRow at row 2, got {dup_err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before); + assert_no_transient_files(&tmp.path().join("events")); +} + +#[test] +fn pit_year_and_empty_field_validations_reject_with_typed_errors_and_no_side_effects() { + let tmp = TempDirGuard::new("field-checks"); + let t = utc_micros(2024, 6, 1, 12, 0, 0, 0); + + // known_at_micros < ts_micros + let err = write_events_dataset( + tmp.path(), + &[make_event_row( + 1, + t, + t - 1, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + EVENT_KIND_FILING, + "8-k", + "{}", + )], + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetEventsError::KnownAtBeforeTs { + row_index: 0, + listing_id: 1, + .. + } + )); + assert!(!tmp.path().join("events").exists()); + + // Year out of range: 1899, 2201, i64::MIN, i64::MAX + for bad_ts in [ + utc_micros(MIN_PARQUET_YEAR - 1, 12, 31, 23, 59, 59, 0), + utc_micros(MAX_PARQUET_YEAR + 1, 1, 1, 0, 0, 0, 0), + i64::MIN, + i64::MAX, + ] { + let err = write_events_dataset( + tmp.path(), + &[make_event_row( + 1, + bad_ts, + bad_ts, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + EVENT_KIND_FILING, + "8-k", + "{}", + )], + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!( + matches!(err, ParquetEventsError::PartitionYearOutOfRange { row_index: 0, .. }), + "expected PartitionYearOutOfRange for ts={bad_ts}, got {err:?}" + ); + assert!(!tmp.path().join("events").exists()); + } + + // Empty and whitespace-only string fields + for empty in ["", " \t\n "] { + let e1 = write_events_dataset( + tmp.path(), + &[EventsParquetRow { + known_at_source: Cow::Owned(empty.to_string()), + ..base_row(1, 2024, 6, 1) + }], + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!(e1, ParquetEventsError::EmptyKnownAtSource { row_index: 0, .. })); + + let e2 = write_events_dataset( + tmp.path(), + &[EventsParquetRow { + kind: Cow::Owned(empty.to_string()), + ..base_row(1, 2024, 6, 1) + }], + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!(e2, ParquetEventsError::EmptyKind { row_index: 0, .. })); + + let e3 = write_events_dataset( + tmp.path(), + &[EventsParquetRow { + subtype: empty.to_string(), + ..base_row(1, 2024, 6, 1) + }], + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!(e3, ParquetEventsError::EmptySubtype { row_index: 0, .. })); + + let e4 = write_events_dataset( + tmp.path(), + &[EventsParquetRow { + payload_json: empty.to_string(), + ..base_row(1, 2024, 6, 1) + }], + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!(e4, ParquetEventsError::EmptyPayloadJson { row_index: 0, .. })); + assert!(!tmp.path().join("events").exists()); + } +} + +#[test] +fn mid_stream_failure_after_flushed_row_groups_leaves_no_published_or_tmp_files() { + let tmp = TempDirGuard::new("midstream-fail"); + let rows = vec![ + base_row(1, 2023, 1, 10), + base_row(2, 2023, 1, 11), + base_row(3, 2023, 1, 12), + base_row(4, 2024, 2, 10), + // Row 4 triggers row_group flush for 2023 (row_group_rows = 2); row 5 fails validation. + EventsParquetRow { + payload_json: String::new(), + ..base_row(5, 2024, 2, 11) + }, + ]; + + let err = write_events_dataset( + tmp.path(), + &rows, + EventsWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetEventsError::EmptyPayloadJson { + row_index: 4, + listing_id: 5, + .. + } + )); + assert!(!tmp.path().join("events/year=2023/part.parquet").exists()); + assert!(!tmp.path().join("events/year=2024/part.parquet").exists()); + assert_no_transient_files(&tmp.path().join("events")); +} + +#[test] +fn unwritable_out_dir_returns_io_error_with_source() { + let tmp = TempDirGuard::new("unwritable"); + let blocker = tmp.path().join("not-a-dir"); + fs::write(&blocker, b"file").unwrap(); + + let err = write_events_dataset(&blocker, &[base_row(1, 2024, 3, 1)], EventsWriteOptions::default()) + .unwrap_err(); + assert!(matches!(err, ParquetEventsError::Io { .. })); + assert!(err.source().is_some()); +} + +#[test] +fn overwrite_replaces_touched_years_and_preserves_untouched_years() { + let tmp = TempDirGuard::new("overwrite"); + let initial = vec![ + base_row(1, 2022, 4, 1), + base_row(1, 2023, 4, 1), + base_row(1, 2024, 4, 1), + ]; + write_events_dataset(tmp.path(), &initial, EventsWriteOptions::default()).unwrap(); + + let path_2022 = tmp.path().join("events/year=2022/part.parquet"); + let bytes_2022 = fs::read(&path_2022).unwrap(); + + let refresh = vec![ + base_row(1, 2023, 6, 1), + base_row(1, 2024, 6, 1), + base_row(2, 2023, 6, 2), + ]; + let stats = write_events_dataset(tmp.path(), &refresh, EventsWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 2); + assert_eq!(stats.rows_by_year, BTreeMap::from([(2023, 2), (2024, 1)])); + + // Untouched 2022 partition is byte-identical. + assert_eq!(fs::read(&path_2022).unwrap(), bytes_2022); + assert_eq!( + read_parquet_rows(&tmp.path().join("events/year=2023/part.parquet")), + vec![refresh[0].clone(), refresh[2].clone()] + ); + assert_eq!( + read_parquet_rows(&tmp.path().join("events/year=2024/part.parquet")), + vec![refresh[1].clone()] + ); + assert_no_transient_files(&tmp.path().join("events")); +} + +#[test] +fn publish_failure_rolls_back_replaced_and_newly_created_partitions() { + let tmp = TempDirGuard::new("rollback"); + + // Pre-existing 2023 partition; 2022 will be newly created; 2024 will be blocked by a directory. + let initial_2023 = vec![base_row(1, 2023, 5, 10)]; + write_events_dataset(tmp.path(), &initial_2023, EventsWriteOptions::default()).unwrap(); + let path_2023 = tmp.path().join("events/year=2023/part.parquet"); + let original_2023_bytes = fs::read(&path_2023).unwrap(); + + let blocker_2024 = tmp.path().join("events/year=2024/part.parquet"); + fs::create_dir_all(&blocker_2024).unwrap(); + + let refresh = vec![ + base_row(1, 2022, 6, 1), + base_row(1, 2023, 6, 1), + base_row(1, 2024, 6, 1), + ]; + let err = write_events_dataset(tmp.path(), &refresh, EventsWriteOptions::default()).unwrap_err(); + assert!( + matches!(err, ParquetEventsError::Io { ref path, .. } if path == &blocker_2024), + "expected Io error at {}, got {err:?}", + blocker_2024.display() + ); + + // Newly created 2022 partition must be removed by rollback. + assert!(!tmp.path().join("events/year=2022/part.parquet").exists()); + // Replaced 2023 partition must be restored byte-for-byte. + assert_eq!(fs::read(&path_2023).unwrap(), original_2023_bytes); + // Blocker directory remains untouched. + assert!(blocker_2024.is_dir()); + assert_no_transient_files(&tmp.path().join("events")); +} + +#[test] +fn rollback_failure_reports_original_error_and_backup_path() { + let tmp = TempDirGuard::new("rollback-fail"); + + let initial_2023 = vec![base_row(1, 2023, 5, 10)]; + write_events_dataset(tmp.path(), &initial_2023, EventsWriteOptions::default()).unwrap(); + let path_2023 = tmp.path().join("events/year=2023/part.parquet"); + let original_2023_bytes = fs::read(&path_2023).unwrap(); + + let blocker_2024 = tmp.path().join("events/year=2024/part.parquet"); + fs::create_dir_all(&blocker_2024).unwrap(); + + let refresh = vec![base_row(1, 2023, 6, 1), base_row(1, 2024, 6, 1)]; + let mut captured_2023_backup: Option = None; + let path_2023_hook = path_2023.clone(); + + let err = write_events_dataset_with_hooks( + tmp.path(), + &refresh, + EventsWriteOptions::default(), + DEFAULT_LOCK_TIMEOUT, + |year, _final_path, backup_path| { + if year == 2023 { + captured_2023_backup = backup_path.map(Path::to_path_buf); + } else if year == 2024 { + fs::remove_file(&path_2023_hook).unwrap(); + fs::create_dir(&path_2023_hook).unwrap(); + } + }, + ) + .unwrap_err(); + + let expected_bak = captured_2023_backup.expect("2023 backup recorded"); + match &err { + ParquetEventsError::RollbackFailed { cause, failures } => { + assert!( + matches!(cause.as_ref(), ParquetEventsError::Io { path, .. } if path == &blocker_2024) + ); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].final_path, path_2023); + assert_eq!( + failures[0].backup_path.as_deref(), + Some(expected_bak.as_path()) + ); + } + other => panic!("expected RollbackFailed, got {other:?}"), + } + let msg = err.to_string(); + assert!(msg.contains(&blocker_2024.display().to_string()), "{msg}"); + assert!(msg.contains(&path_2023.display().to_string()), "{msg}"); + assert!(msg.contains(&expected_bak.display().to_string()), "{msg}"); + assert!(err.source().is_some()); + assert_eq!(fs::read(&expected_bak).unwrap(), original_2023_bytes); +} + +#[test] +fn live_partition_remains_readable_between_backup_and_rename() { + let tmp = TempDirGuard::new("live-readable"); + let initial = vec![base_row(1, 2023, 5, 10)]; + write_events_dataset(tmp.path(), &initial, EventsWriteOptions::default()).unwrap(); + let path_2023 = tmp.path().join("events/year=2023/part.parquet"); + let original_bytes = fs::read(&path_2023).unwrap(); + + let refresh = vec![base_row(1, 2023, 6, 1), base_row(2, 2023, 6, 2)]; + let mut observed = false; + + write_events_dataset_with_hooks( + tmp.path(), + &refresh, + EventsWriteOptions::default(), + DEFAULT_LOCK_TIMEOUT, + |year, final_path, backup_path| { + assert_eq!(year, 2023); + assert!(backup_path.expect("backup created").exists()); + assert_eq!(fs::read(final_path).unwrap(), original_bytes); + assert_eq!(read_parquet_rows(final_path), initial); + observed = true; + }, + ) + .unwrap(); + + assert!(observed); + assert_eq!(read_parquet_rows(&path_2023), refresh); + assert_no_transient_files(&tmp.path().join("events")); +} + +#[test] +fn held_write_lock_times_out_without_deleting_lock_file() { + let tmp = TempDirGuard::new("lock-timeout"); + let initial = vec![base_row(1, 2024, 1, 2)]; + write_events_dataset(tmp.path(), &initial, EventsWriteOptions::default()).unwrap(); + let existing = tmp.path().join("events/year=2024/part.parquet"); + let original_bytes = fs::read(&existing).unwrap(); + + let lock_path = tmp.path().join("events/.write.lock"); + fs::write(&lock_path, b"999999\n").unwrap(); + + let timeout = Duration::from_millis(40); + let err = write_events_dataset_with_hooks( + tmp.path(), + &[base_row(1, 2024, 2, 1)], + EventsWriteOptions::default(), + timeout, + |_, _, _| {}, + ) + .unwrap_err(); + + match &err { + ParquetEventsError::LockTimeout { path, waited } => { + assert_eq!(path, &lock_path); + assert!(*waited >= timeout); + } + other => panic!("expected LockTimeout, got {other:?}"), + } + assert!(err.to_string().contains(&lock_path.display().to_string())); + assert_eq!(fs::read(&lock_path).unwrap(), b"999999\n"); + assert_eq!(fs::read(&existing).unwrap(), original_bytes); + fs::remove_file(&lock_path).unwrap(); + assert_no_transient_files(&tmp.path().join("events")); +} + +#[test] +fn concurrent_writers_serialize_without_mixed_generations() { + let tmp = TempDirGuard::new("concurrent"); + let out_dir = tmp.path().to_path_buf(); + + let rows_a = vec![ + base_row(1, 2023, 3, 1), + base_row(1, 2024, 3, 1), + base_row(2, 2023, 3, 1), + base_row(2, 2024, 3, 1), + ]; + let rows_b = vec![ + base_row(1, 2023, 4, 1), + base_row(1, 2024, 4, 1), + base_row(2, 2023, 4, 1), + base_row(2, 2024, 4, 1), + ]; + + struct SignalingIter { + rows: std::vec::IntoIter, + seen: usize, + on_second: Option>, + on_end: Option>, + } + + impl Iterator for SignalingIter { + type Item = EventsParquetRow; + fn next(&mut self) -> Option { + self.seen += 1; + if self.seen == 2 { + if let Some(cb) = self.on_second.take() { + cb(); + } + } + let item = self.rows.next(); + if item.is_none() { + if let Some(cb) = self.on_end.take() { + cb(); + } + } + item + } + } + + let order = Arc::new(Mutex::new(Vec::<&'static str>::new())); + let (t1_locked_tx, t1_locked_rx) = mpsc::channel::<()>(); + let (t2_contended_tx, t2_contended_rx) = mpsc::channel::<()>(); + + let out_1 = out_dir.clone(); + let order_1 = Arc::clone(&order); + let order_1_end = Arc::clone(&order); + let rows_a_clone = rows_a.clone(); + let h1 = thread::spawn(move || { + let iter = SignalingIter { + rows: rows_a_clone.into_iter(), + seen: 0, + on_second: Some(Box::new(move || { + order_1.lock().unwrap().push("t1_row2"); + let _ = t1_locked_tx.send(()); + // Hold the dataset lock until we directly observe writer 2 contend for it. + t2_contended_rx + .recv_timeout(Duration::from_secs(5)) + .expect("expected writer 2 to contend on the dataset lock"); + })), + on_end: Some(Box::new(move || { + order_1_end.lock().unwrap().push("t1_iter_end"); + })), + }; + write_events_dataset(&out_1, iter, EventsWriteOptions::default()) + }); + + let out_2 = out_dir.clone(); + let order_2_contended = Arc::clone(&order); + let order_2 = Arc::clone(&order); + let rows_b_clone = rows_b.clone(); + let h2 = thread::spawn(move || { + t1_locked_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + let iter = SignalingIter { + rows: rows_b_clone.into_iter(), + seen: 0, + on_second: Some(Box::new(move || { + order_2.lock().unwrap().push("t2_row2"); + })), + on_end: None, + }; + write_events_dataset_with_lock_and_backup_hooks( + &out_2, + iter, + EventsWriteOptions::default(), + DEFAULT_LOCK_TIMEOUT, + || { + order_2_contended.lock().unwrap().push("t2_contended"); + let _ = t2_contended_tx.send(()); + }, + |_, _, _| {}, + ) + }); + + assert_eq!(h1.join().unwrap().unwrap().rows_written, rows_a.len()); + assert_eq!(h2.join().unwrap().unwrap().rows_written, rows_b.len()); + + let recorded = order.lock().unwrap(); + let pos_t1_row2 = recorded.iter().position(|&e| e == "t1_row2").unwrap(); + let pos_t2_contended = recorded.iter().position(|&e| e == "t2_contended").unwrap(); + let pos_t1_end = recorded.iter().position(|&e| e == "t1_iter_end").unwrap(); + let pos_t2_row2 = recorded.iter().position(|&e| e == "t2_row2").unwrap(); + assert!( + pos_t1_row2 < pos_t2_contended && pos_t2_contended < pos_t1_end && pos_t1_end < pos_t2_row2, + "expected strict serialization with observed lock contention: {recorded:?}" + ); + + for year in [2023, 2024] { + let actual = read_parquet_rows(&out_dir.join(format!("events/year={year:04}/part.parquet"))); + let expected: Vec = rows_b + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == year) + .cloned() + .collect(); + assert_eq!(actual, expected); + } + assert_no_transient_files(&out_dir.join("events")); +} + +#[test] +fn panicking_iterator_cleans_up_owned_staging_files_and_releases_lock() { + let tmp = TempDirGuard::new("panic-unwind"); + let year_dir = tmp.path().join("events/year=2024"); + fs::create_dir_all(&year_dir).unwrap(); + let foreign_tmp = year_dir.join("part.parquet.foreign.tmp"); + fs::write(&foreign_tmp, b"foreign").unwrap(); + + struct PanicIter { + yielded: usize, + } + impl Iterator for PanicIter { + type Item = EventsParquetRow; + fn next(&mut self) -> Option { + self.yielded += 1; + match self.yielded { + 1 => Some(base_row(1, 2023, 5, 1)), + 2 => Some(base_row(1, 2024, 5, 1)), + _ => panic!("simulated iterator panic"), + } + } + } + + let res = catch_unwind(AssertUnwindSafe(|| { + let _ = write_events_dataset( + tmp.path(), + PanicIter { yielded: 0 }, + EventsWriteOptions::default(), + ); + })); + assert!(res.is_err(), "expected panic from iterator"); + + // Lock must be released and foreign tmp preserved; no owned .tmp or part.parquet left behind. + assert!(!tmp.path().join("events/.write.lock").exists()); + assert!(!tmp.path().join("events/year=2023/part.parquet").exists()); + assert!(!tmp.path().join("events/year=2024/part.parquet").exists()); + assert_eq!(fs::read(&foreign_tmp).unwrap(), b"foreign"); + fs::remove_file(&foreign_tmp).unwrap(); + assert_no_transient_files(&tmp.path().join("events")); + + // Subsequent write succeeds cleanly. + let stats = write_events_dataset( + tmp.path(), + &[base_row(1, 2024, 5, 1)], + EventsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats.rows_written, 1); +} + +#[test] +fn exact_year_bounds_one_microsecond_either_side_and_pre_1970_timestamps() { + let min_ok = utc_micros(MIN_PARQUET_YEAR, 1, 1, 0, 0, 0, 0); + let min_under = min_ok - 1; + let pre_epoch = utc_micros(1969, 12, 31, 23, 59, 59, 999_999); + let max_ok = utc_micros(MAX_PARQUET_YEAR, 12, 31, 23, 59, 59, 999_999); + let max_over = max_ok + 1; + + assert!(min_ok < 0 && pre_epoch < 0); + assert_eq!(partition_year_utc(min_under), MIN_PARQUET_YEAR - 1); + assert_eq!(partition_year_utc(min_ok), MIN_PARQUET_YEAR); + assert_eq!(partition_year_utc(pre_epoch), 1969); + assert_eq!(partition_year_utc(max_ok), MAX_PARQUET_YEAR); + assert_eq!(partition_year_utc(max_over), MAX_PARQUET_YEAR + 1); + + let tmp_ok = TempDirGuard::new("year-bounds-ok"); + let valid_rows = vec![ + make_event_row( + 1, + min_ok, + min_ok, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + EVENT_KIND_FILING, + "8-k", + r#"{"bound":"min"}"#, + ), + make_event_row( + 1, + pre_epoch, + pre_epoch + 1, + KNOWN_AT_SOURCE_STATUTORY_LAG, + EVENT_KIND_EARNINGS, + "amc", + r#"{"bound":"pre_1970"}"#, + ), + make_event_row( + 1, + max_ok, + max_ok, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + EVENT_KIND_FILING, + "10-k", + r#"{"bound":"max"}"#, + ), + ]; + let stats = + write_events_dataset(tmp_ok.path(), &valid_rows, EventsWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 3); + assert_eq!( + stats.rows_by_year, + BTreeMap::from([(MIN_PARQUET_YEAR, 1), (1969, 1), (MAX_PARQUET_YEAR, 1)]) + ); + for (year, expected) in [ + (MIN_PARQUET_YEAR, &valid_rows[0]), + (1969, &valid_rows[1]), + (MAX_PARQUET_YEAR, &valid_rows[2]), + ] { + let path = tmp_ok + .path() + .join(format!("events/year={year:04}/part.parquet")); + assert_eq!(read_parquet_rows(&path), vec![expected.clone()]); + } + assert_no_transient_files(&tmp_ok.path().join("events")); + + for (tag, bad_ts, expected_year) in [ + ("under", min_under, MIN_PARQUET_YEAR - 1), + ("over", max_over, MAX_PARQUET_YEAR + 1), + ] { + let tmp_bad = TempDirGuard::new(&format!("year-bounds-{tag}")); + let err = write_events_dataset( + tmp_bad.path(), + &[make_event_row( + 1, + bad_ts, + bad_ts, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + EVENT_KIND_FILING, + "8-k", + "{}", + )], + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!( + matches!( + err, + ParquetEventsError::PartitionYearOutOfRange { + row_index: 0, + year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } if year == expected_year + ), + "unexpected error for {tag}: {err:?}" + ); + assert!(!tmp_bad.path().join("events").exists()); + } +} + +#[test] +fn partitions_by_ts_not_known_at_when_known_at_crosses_year_boundary() { + let tmp = TempDirGuard::new("partition-by-ts"); + let ts_2023 = utc_micros(2023, 12, 31, 23, 59, 0, 0); + let known_at_2024 = utc_micros(2024, 1, 1, 2, 0, 0, 0); + let row = make_event_row( + 10, + ts_2023, + known_at_2024, + KNOWN_AT_SOURCE_STATUTORY_LAG, + EVENT_KIND_EARNINGS, + "amc", + r#"{"cross_year_lag":true}"#, + ); + + let stats = write_events_dataset(tmp.path(), &[row.clone()], EventsWriteOptions::default()) + .unwrap(); + assert_eq!(stats.rows_written, 1); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.rows_by_year, BTreeMap::from([(2023, 1)])); + + let p2023 = tmp.path().join("events/year=2023/part.parquet"); + assert!(p2023.exists()); + assert!(!tmp.path().join("events/year=2024").exists()); + assert_eq!(read_parquet_rows(&p2023), vec![row]); + assert_no_transient_files(&tmp.path().join("events")); +} + +#[test] +fn mid_stream_failure_after_flushed_row_groups_preserves_existing_files_byte_for_byte() { + let tmp = TempDirGuard::new("mid-stream-preserve"); + let initial = vec![base_row(1, 2023, 3, 1), base_row(1, 2024, 3, 1)]; + write_events_dataset(tmp.path(), &initial, EventsWriteOptions::default()).unwrap(); + + let p2023 = tmp.path().join("events/year=2023/part.parquet"); + let p2024 = tmp.path().join("events/year=2024/part.parquet"); + let orig_2023 = fs::read(&p2023).unwrap(); + let orig_2024 = fs::read(&p2024).unwrap(); + + // Flush multiple row groups across 2023, 2024, and a brand-new 2025 partition before failing. + let failing = vec![ + base_row(1, 2023, 4, 1), + base_row(1, 2023, 4, 2), + base_row(1, 2024, 4, 1), + base_row(1, 2024, 4, 2), + base_row(1, 2025, 4, 1), + make_event_row( + 2, + utc_micros(2024, 5, 1, 14, 0, 0, 0), + utc_micros(2024, 5, 1, 13, 59, 59, 999_999), + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + EVENT_KIND_FILING, + "8-k", + "{}", + ), + ]; + let err = write_events_dataset( + tmp.path(), + &failing, + EventsWriteOptions { + row_group_rows: 1, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetEventsError::KnownAtBeforeTs { row_index: 5, .. } + )); + + assert_eq!(fs::read(&p2023).unwrap(), orig_2023); + assert_eq!(fs::read(&p2024).unwrap(), orig_2024); + assert!(!tmp.path().join("events/year=2025/part.parquet").exists()); + assert_no_transient_files(&tmp.path().join("events")); +} + +#[test] +fn leading_and_trailing_whitespace_fields_are_stored_verbatim() { + let tmp = TempDirGuard::new("whitespace-verbatim"); + let row = EventsParquetRow { + listing_id: 7, + ts_micros: utc_micros(2024, 6, 15, 12, 0, 0, 0), + known_at_micros: utc_micros(2024, 6, 15, 12, 0, 0, 0), + known_at_source: Cow::Owned(" filing_timestamp ".to_string()), + kind: Cow::Owned("\tfiling\n".to_string()), + subtype: " 8-k/a ".to_string(), + payload_json: " {\"note\": \" padded \"} ".to_string(), + }; + + let stats = write_events_dataset(tmp.path(), &[row.clone()], EventsWriteOptions::default()) + .unwrap(); + assert_eq!(stats.rows_written, 1); + + let read_back = read_parquet_rows(&tmp.path().join("events/year=2024/part.parquet")); + assert_eq!(read_back, vec![row]); + assert_no_transient_files(&tmp.path().join("events")); +} + +#[test] +fn zstd_level_extremes_1_and_22_match_on_disk_bytes_written() { + let rows = vec![ + base_row(1, 2023, 2, 1), + base_row(1, 2024, 2, 1), + base_row(2, 2023, 2, 2), + base_row(2, 2024, 2, 2), + ]; + + for level in [1, 22] { + let tmp = TempDirGuard::new(&format!("zstd-lvl-{level}")); + let stats = write_events_dataset( + tmp.path(), + &rows, + EventsWriteOptions { + row_group_rows: 2, + zstd_level: level, + }, + ) + .unwrap(); + assert_eq!(stats.rows_written, 4); + assert_eq!(stats.files_written, 2); + + let mut disk_bytes = 0_u64; + for year in [2023, 2024] { + let path = tmp + .path() + .join(format!("events/year={year:04}/part.parquet")); + disk_bytes += fs::metadata(&path).unwrap().len(); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + for rg in reader.metadata().row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "expected ZSTD compression for level {level}, got {:?}", + col.compression() + ); + } + } + let expected: Vec = rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == year) + .cloned() + .collect(); + assert_eq!(read_parquet_rows(&path), expected); + } + assert_eq!(stats.bytes_written, disk_bytes); + assert_no_transient_files(&tmp.path().join("events")); + } +} + +#[test] +fn large_build_events_round_trip_preserves_order_and_fields_across_years() { + let tmp = TempDirGuard::new("large-build-events"); + let mut filings = Vec::with_capacity(2_500); + let mut earnings = Vec::with_capacity(600); + + for listing_id in 1..=50_i32 { + for idx in 0..50_u32 { + let year = 2020 + (idx % 5) as i32; + let month = 1 + (idx % 12); + let day = 1 + (idx % 28); + let form_type = match idx % 4 { + 0 => "8-K", + 1 => "10-Q", + 2 => "10-K", + _ => "News release", + }; + filings.push(QmFiling { + key: listing_id, + timefiled: format!("{year:04}-{month:02}-{day:02}T16:15:00 EDT"), + form_type: form_type.to_string(), + filing_id: Some(format!("F-{listing_id}-{idx}")), + url: if idx % 2 == 0 { + Some(format!("https://sec.example/{listing_id}/{idx}")) + } else { + None + }, + }); + } + for q in 0..12_u32 { + let year = 2020 + (q / 3) as i32; + let month = 2 + (q % 3) * 3; + let day = 10 + (q % 15); + let report_date = ymd_to_epoch_days(year, month, day).unwrap(); + earnings.push(QmEarning { + key: listing_id, + report_date, + announce_time: if q % 2 == 0 { "AMC" } else { "BTO" }.to_string(), + fiscal_period_end: Some(report_date - 30), + actual_eps: Some(0.5 + (q as f64) * 0.1), + revenue: Some(1_000_000.0 + (listing_id as f64) * 10_000.0), + }); + } + } + + let built = build_events(filings, earnings); + let rows: Vec = built.rows.into_iter().map(EventsParquetRow::from).collect(); + assert!(rows.len() > 3_000, "expected >3000 rows, got {}", rows.len()); + + let stats = write_events_dataset( + tmp.path(), + &rows, + EventsWriteOptions { + row_group_rows: 128, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap(); + assert_eq!(stats.rows_written, rows.len()); + assert_eq!(stats.files_written, stats.rows_by_year.len()); + + let mut total_read = 0_usize; + for (&year, &expected_count) in &stats.rows_by_year { + let path = tmp + .path() + .join(format!("events/year={year:04}/part.parquet")); + let actual = read_parquet_rows(&path); + assert_eq!(actual.len(), expected_count); + let expected: Vec = rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == year) + .cloned() + .collect(); + assert_eq!(actual, expected); + // Verify strict ascending order preserved inside each year partition. + for pair in actual.windows(2) { + let a = &pair[0]; + let b = &pair[1]; + let ord = ( + a.listing_id, + a.ts_micros, + a.kind.as_ref(), + a.subtype.as_str(), + a.payload_json.as_str(), + a.known_at_micros, + a.known_at_source.as_ref(), + ) + .cmp(&( + b.listing_id, + b.ts_micros, + b.kind.as_ref(), + b.subtype.as_str(), + b.payload_json.as_str(), + b.known_at_micros, + b.known_at_source.as_ref(), + )); + assert_eq!(ord, std::cmp::Ordering::Less); + } + total_read += actual.len(); + } + assert_eq!(total_read, rows.len()); + assert_no_transient_files(&tmp.path().join("events")); +} diff --git a/tools/curate-etl/src/parquet_fx.rs b/tools/curate-etl/src/parquet_fx.rs new file mode 100644 index 00000000..860cdabd --- /dev/null +++ b/tools/curate-etl/src/parquet_fx.rs @@ -0,0 +1,1310 @@ +//! Streaming, atomic Zstd Parquet writer for `fx_1d`. +//! +//! Writes `/fx_1d/part.parquet` matching the 9-column contract schema in +//! `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `pair` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 2. `session_date` (`INT32`, `REQUIRED`, `DATE`) +//! 3. `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 4. `open` (`DOUBLE`, `REQUIRED`) +//! 5. `high` (`DOUBLE`, `REQUIRED`) +//! 6. `low` (`DOUBLE`, `REQUIRED`) +//! 7. `close` (`DOUBLE`, `REQUIRED`) +//! 8. `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 9. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::fx::Fx1dRow; +use crate::parquet_publish::{ + create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, + write_f64_col, write_i32_col, write_i64_col, write_interned_str_col, DatasetFileLock, + PublishIoError, StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, + FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, +}; +pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; + +const MICROS_PER_DAY: i128 = 86_400_000_000; + +/// Single `fx_1d` row matching the `design/DATA-CONTRACTS.md` Parquet schema. +#[derive(Debug, Clone, PartialEq)] +pub struct Fx1dParquetRow { + pub pair: Cow<'static, str>, + pub session_date: i32, + pub ts_micros: i64, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub source: Cow<'static, str>, + pub known_at_micros: i64, +} + +impl Fx1dParquetRow { + /// Builds a [`Fx1dParquetRow`] from a curated [`Fx1dRow`] and caller-supplied UTC microsecond + /// timestamps without heap allocation. + #[inline] + pub fn from_fx_row(row: &Fx1dRow, ts_micros: i64, known_at_micros: i64) -> Self { + Self { + pair: Cow::Borrowed(row.pair), + session_date: row.session_date, + ts_micros, + open: row.open, + high: row.high, + low: row.low, + close: row.close, + source: Cow::Borrowed(row.source.as_str()), + known_at_micros, + } + } +} + +/// Configuration for [`write_fx_1d_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Fx1dWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for Fx1dWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_fx_1d_dataset`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Fx1dWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, +} + +/// Typed error returned by [`write_fx_1d_dataset`]. +#[derive(Debug)] +pub enum ParquetFxError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + UnsortedInput { + prev_pair: String, + prev_session_date: i32, + pair: String, + session_date: i32, + }, + DuplicateKey { + pair: String, + session_date: i32, + }, + EmptyPair { + session_date: i32, + }, + EmptySource { + pair: String, + session_date: i32, + }, + InvalidOhlc { + pair: String, + session_date: i32, + open: f64, + high: f64, + low: f64, + close: f64, + }, + InconsistentOhlc { + pair: String, + session_date: i32, + open: f64, + high: f64, + low: f64, + close: f64, + }, + TsOutsideSessionDate { + pair: String, + session_date: i32, + ts_micros: i64, + }, + KnownAtBeforeTs { + pair: String, + session_date: i32, + ts_micros: i64, + known_at_micros: i64, + }, + LockTimeout { + path: PathBuf, + waited: Duration, + }, + RollbackFailed { + cause: Box, + failures: Vec, + }, + Io { + path: PathBuf, + source: io::Error, + }, + Parquet { + path: PathBuf, + source: ParquetError, + }, +} + +impl fmt::Display for ParquetFxError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidRowGroupRows => { + write!(f, "invalid row_group_rows: must be greater than 0") + } + Self::InvalidZstdLevel { level } => { + write!(f, "invalid Zstd compression level: {level}") + } + Self::UnsortedInput { + prev_pair, + prev_session_date, + pair, + session_date, + } => write!( + f, + "unsorted input: ({pair}, {session_date}) follows ({prev_pair}, {prev_session_date})" + ), + Self::DuplicateKey { pair, session_date } => { + write!(f, "duplicate (pair, session_date) key: ({pair}, {session_date})") + } + Self::EmptyPair { session_date } => { + write!(f, "empty pair for session_date {session_date}: must be non-empty") + } + Self::EmptySource { pair, session_date } => { + write!(f, "empty source for ({pair}, {session_date}): must be non-empty") + } + Self::InvalidOhlc { + pair, + session_date, + open, + high, + low, + close, + } => write!( + f, + "invalid OHLC ({open}, {high}, {low}, {close}) for ({pair}, {session_date}): all values must be finite and > 0" + ), + Self::InconsistentOhlc { + pair, + session_date, + open, + high, + low, + close, + } => write!( + f, + "inconsistent OHLC ({open}, {high}, {low}, {close}) for ({pair}, {session_date}): must satisfy high >= low and open, close in [low, high]" + ), + Self::TsOutsideSessionDate { + pair, + session_date, + ts_micros, + } => write!( + f, + "ts {ts_micros} is outside UTC day of session_date {session_date} for pair '{pair}'" + ), + Self::KnownAtBeforeTs { + pair, + session_date, + ts_micros, + known_at_micros, + } => write!( + f, + "known_at {known_at_micros} precedes ts {ts_micros} for ({pair}, {session_date})" + ), + Self::LockTimeout { path, waited } => write!( + f, + "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", + waited.as_millis(), + path.display() + ), + Self::RollbackFailed { cause, failures } => { + write!( + f, + "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", + failures.len() + )?; + for failure in failures { + write!(f, " [{failure}]")?; + } + Ok(()) + } + Self::Io { path, source } => { + write!(f, "I/O error at '{}': {source}", path.display()) + } + Self::Parquet { path, source } => { + write!(f, "Parquet error at '{}': {source}", path.display()) + } + } + } +} + +impl Error for ParquetFxError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::Io { source, .. } => Some(source), + Self::Parquet { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for ParquetFxError { + fn from(err: PublishIoError) -> Self { + match err { + PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, + PublishIoError::Io { path, source } => Self::Io { path, source }, + } + } +} + +/// Builds the exact 9-column Parquet schema for `fx_1d` per `design/DATA-CONTRACTS.md` (§3A). +pub fn fx_1d_parquet_schema() -> Result { + let fields: Vec = vec![ + Arc::new( + Type::primitive_type_builder("pair", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("session_date", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ts", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("open", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("high", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("low", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("close", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("fx_1d") + .with_fields(fields) + .build()?, + )) +} + +fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { + Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(zstd_level)) + .set_column_dictionary_enabled(ColumnPath::from("pair"), true) + .set_column_dictionary_enabled(ColumnPath::from("source"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn is_valid_rate(rate: f64) -> bool { + rate.is_finite() && rate > 0.0 +} + +#[inline] +fn validate_row(row: &Fx1dParquetRow) -> Result<(), ParquetFxError> { + if row.pair.trim().is_empty() { + return Err(ParquetFxError::EmptyPair { + session_date: row.session_date, + }); + } + if row.source.trim().is_empty() { + return Err(ParquetFxError::EmptySource { + pair: row.pair.as_ref().to_owned(), + session_date: row.session_date, + }); + } + if !is_valid_rate(row.open) + || !is_valid_rate(row.high) + || !is_valid_rate(row.low) + || !is_valid_rate(row.close) + { + return Err(ParquetFxError::InvalidOhlc { + pair: row.pair.as_ref().to_owned(), + session_date: row.session_date, + open: row.open, + high: row.high, + low: row.low, + close: row.close, + }); + } + if row.high < row.low + || row.open < row.low + || row.open > row.high + || row.close < row.low + || row.close > row.high + { + return Err(ParquetFxError::InconsistentOhlc { + pair: row.pair.as_ref().to_owned(), + session_date: row.session_date, + open: row.open, + high: row.high, + low: row.low, + close: row.close, + }); + } + let day_start = i128::from(row.session_date) * MICROS_PER_DAY; + let day_end = day_start + MICROS_PER_DAY; + let ts = i128::from(row.ts_micros); + if ts < day_start || ts >= day_end { + return Err(ParquetFxError::TsOutsideSessionDate { + pair: row.pair.as_ref().to_owned(), + session_date: row.session_date, + ts_micros: row.ts_micros, + }); + } + if row.known_at_micros < row.ts_micros { + return Err(ParquetFxError::KnownAtBeforeTs { + pair: row.pair.as_ref().to_owned(), + session_date: row.session_date, + ts_micros: row.ts_micros, + known_at_micros: row.known_at_micros, + }); + } + Ok(()) +} + +#[derive(Default)] +struct RowGroupBuffer { + pair_ids: Vec, + pair_interner: StringInterner, + session_date: Vec, + ts_micros: Vec, + open: Vec, + high: Vec, + low: Vec, + close: Vec, + source_ids: Vec, + source_interner: StringInterner, + known_at_micros: Vec, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.session_date.len() + } + + fn push(&mut self, row: &Fx1dParquetRow) { + let pair_id = self.pair_interner.intern(row.pair.as_ref()); + self.pair_ids.push(pair_id); + self.session_date.push(row.session_date); + self.ts_micros.push(row.ts_micros); + self.open.push(row.open); + self.high.push(row.high); + self.low.push(row.low); + self.close.push(row.close); + let source_id = self.source_interner.intern(row.source.as_ref()); + self.source_ids.push(source_id); + self.known_at_micros.push(row.known_at_micros); + } + + fn clear(&mut self) { + self.pair_ids.clear(); + self.pair_interner.clear(); + self.session_date.clear(); + self.ts_micros.clear(); + self.open.clear(); + self.high.clear(); + self.low.clear(); + self.close.clear(); + self.source_ids.clear(); + self.source_interner.clear(); + self.known_at_micros.clear(); + } +} + +struct Fx1dFileWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl Fx1dFileWriter { + fn from_file( + tmp_path: PathBuf, + final_path: PathBuf, + file: File, + schema: &TypePtr, + props: &WriterPropertiesPtr, + ) -> Result { + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetFxError::Parquet { + path: tmp_path.clone(), + source, + }, + )?; + + Ok(Self { + tmp_path, + final_path, + writer, + buf: RowGroupBuffer::default(), + rows_written: 0, + row_groups_written: 0, + }) + } + + fn flush_row_group(&mut self, scratch: &mut Vec) -> Result<(), ParquetFxError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetFxError::Parquet { + path: self.tmp_path.clone(), + source, + }; + + let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; + + // 1. pair (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.pair_ids, + &self.buf.pair_interner, + scratch, + ) + .map_err(map_pq)?; + // 2. session_date (INT32, REQUIRED, DATE) + write_i32_col(&mut rg_writer, &self.buf.session_date).map_err(map_pq)?; + // 3. ts (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.ts_micros).map_err(map_pq)?; + // 4. open (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.open, None).map_err(map_pq)?; + // 5. high (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.high, None).map_err(map_pq)?; + // 6. low (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.low, None).map_err(map_pq)?; + // 7. close (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.close, None).map_err(map_pq)?; + // 8. source (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.source_ids, + &self.buf.source_interner, + scratch, + ) + .map_err(map_pq)?; + // 9. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; + + rg_writer.close().map_err(map_pq)?; + + self.rows_written += row_count; + self.row_groups_written += 1; + self.buf.clear(); + Ok(()) + } + + fn finish_and_sync( + mut self, + scratch: &mut Vec, + ) -> Result { + self.flush_row_group(scratch)?; + + let mut buf_writer = + self.writer + .into_inner() + .map_err(|source| ParquetFxError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer.flush().map_err(|source| ParquetFxError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetFxError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all().map_err(|source| ParquetFxError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetFxError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedFx1dFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedFx1dFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +/// Streams strictly ascending `(pair, session_date)` rows into a single Zstd Parquet file +/// at `/fx_1d/part.parquet`. +/// +/// # Empty Input +/// Empty input returns `Ok(Fx1dWriteStats::default())` without creating `/fx_1d` +/// and without modifying or removing any pre-existing `part.parquet`. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/fx_1d` directory are serialized via an +/// in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. The file is +/// written to an exclusively created per-run staging file (`part.parquet..tmp`), flushed, +/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists, +/// a live-preserving backup (`part.parquet..bak`) is created via hard link (or exclusive +/// copy fallback) so readers never observe a missing `part.parquet` before replacement by a +/// single atomic `rename`. On any error, the writer is dropped, any backup created by this run +/// is cleaned up (reporting cleanup failures via [`ParquetFxError::RollbackFailed`]), and +/// only staging files owned by this run are unlinked. +pub fn write_fx_1d_dataset( + out_dir: P, + rows: I, + options: Fx1dWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_fx_1d_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _| {}, + |path| fs::remove_file(path), + ) +} + +fn write_fx_1d_dataset_with_hooks( + out_dir: P, + rows: I, + options: Fx1dWriteOptions, + lock_timeout: Duration, + mut on_after_backup: F, + mut remove_backup: Rm, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(&Path, Option<&Path>), + Rm: FnMut(&Path) -> io::Result<()>, +{ + if options.row_group_rows == 0 { + return Err(ParquetFxError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetFxError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(Fx1dWriteStats::default()); + }; + validate_row(first_item.borrow())?; + + let out_dir = out_dir.as_ref(); + let fx_dir = out_dir.join("fx_1d"); + let schema = fx_1d_parquet_schema().map_err(|source| ParquetFxError::Parquet { + path: fx_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&fx_dir).map_err(|source| ParquetFxError::Io { + path: fx_dir.clone(), + source, + })?; + + // Serialize writers targeting the same dataset directory across threads and processes. + // Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held, + // and only after all staging/publication/rollback work has finished. + let dataset_mu = dataset_mutex(&fx_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire_with_timeout(&fx_dir, lock_timeout)?; + + let run_id = next_run_id(); + let (tmp_path, tmp_file) = create_exclusive_tmp_file(&fx_dir, &run_id)?; + // Declared before `file_writer` so Rust's reverse drop order closes the file handle + // before the guard unlinks the staging file on error or panic unwind, while `_file_lock` + // and `_in_process_guard` are still held. + let mut staging_guard = StagingFileGuard::new(tmp_path.clone()); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let mut file_writer = Some(Fx1dFileWriter::from_file( + tmp_path, + fx_dir.join("part.parquet"), + tmp_file, + &schema, + &props, + )?); + + let synced = { + let mut has_prev = false; + let mut prev_pair = String::new(); + let mut prev_session_date = 0i32; + let writer = file_writer.as_mut().expect("writer initialized"); + + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + // Validate row fields before checking sort order so e.g. an empty pair + // is reported as EmptyPair rather than UnsortedInput. + validate_row(row)?; + let pair = row.pair.as_ref(); + if has_prev { + match (pair, row.session_date).cmp(&(prev_pair.as_str(), prev_session_date)) { + Ordering::Equal => { + return Err(ParquetFxError::DuplicateKey { + pair: pair.to_owned(), + session_date: row.session_date, + }); + } + Ordering::Less => { + return Err(ParquetFxError::UnsortedInput { + prev_pair, + prev_session_date, + pair: pair.to_owned(), + session_date: row.session_date, + }); + } + Ordering::Greater => {} + } + } + if !has_prev || pair != prev_pair.as_str() { + prev_pair.clear(); + prev_pair.push_str(pair); + } + prev_session_date = row.session_date; + has_prev = true; + + writer.buf.push(row); + if writer.buf.len() == options.row_group_rows { + writer.flush_row_group(&mut scratch)?; + } + } + + let writer = file_writer.take().expect("writer still present"); + writer.finish_and_sync(&mut scratch)? + }; + + let backup_path = match fs::symlink_metadata(&synced.final_path) { + Ok(meta) if !meta.is_dir() => { + Some(create_backup_preserving_live(&synced.final_path, &run_id)?) + } + // Directory occupying final_path: leave it in place so the rename below fails cleanly. + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + return Err(ParquetFxError::Io { + path: synced.final_path, + source, + }); + } + }; + + on_after_backup(&synced.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&synced.tmp_path, &synced.final_path) { + // `synced.final_path` was never moved during backup creation, so it remains intact; + // remove the backup created for this run. `staging_guard` unlinks our staging file on drop. + let backup_remove_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: synced.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let cause = ParquetFxError::Io { + path: synced.final_path, + source, + }; + return match backup_remove_failure { + Some(failure) => Err(ParquetFxError::RollbackFailed { + cause: Box::new(cause), + failures: vec![failure], + }), + None => Err(cause), + }; + } + + staging_guard.disarm(); + + if let Some(bak) = backup_path { + if let Err(remove_err) = remove_backup(&bak) { + let cause = ParquetFxError::Io { + path: bak.clone(), + source: remove_err, + }; + return match fs::rename(&bak, &synced.final_path) { + Ok(()) => Err(cause), + Err(restore_err) => Err(ParquetFxError::RollbackFailed { + cause: Box::new(cause), + failures: vec![RollbackFailure { + final_path: synced.final_path, + backup_path: Some(bak), + source: restore_err, + }], + }), + }; + } + } + + Ok(Fx1dWriteStats { + rows_written: synced.rows_written, + files_written: 1, + row_groups_written: synced.row_groups_written, + bytes_written: synced.bytes, + }) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + + use parquet::basic::ConvertedType; + use parquet::column::reader::ColumnReader; + use parquet::file::reader::{FileReader, SerializedFileReader}; + + use super::*; + use crate::fx::{build_fx_1d, FxDailyBar, FxSource, FX_PAIR_USDCAD}; + use crate::split::ymd_to_epoch_days; + + static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + + pub(super) struct TempDirGuard { + path: PathBuf, + } + + impl TempDirGuard { + pub(super) fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-pq-fx-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + pub(super) fn path(&self) -> &Path { + &self.path + } + } + + impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + pub(super) fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") + } + + pub(super) fn close_ts_micros(session_date: i32) -> i64 { + i64::from(session_date) * 86_400_000_000 + 22 * 3_600_000_000 + } + + pub(super) fn make_row( + pair: &'static str, + session_date: i32, + open: f64, + high: f64, + low: f64, + close: f64, + source: FxSource, + ) -> Fx1dParquetRow { + let ts_micros = close_ts_micros(session_date); + Fx1dParquetRow { + pair: Cow::Borrowed(pair), + session_date, + ts_micros, + open, + high, + low, + close, + source: Cow::Borrowed(source.as_str()), + known_at_micros: ts_micros + 900_000_000, + } + } + + pub(super) fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let read_i32 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i32"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + let read_i64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + let read_f64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read f64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + vals + }; + let read_str = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read utf8"); + assert_eq!(read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + vals.into_iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_owned()) + .collect() + }; + + let pair = read_str(0); + let session_date = read_i32(1); + let ts_micros = read_i64(2); + let open = read_f64(3); + let high = read_f64(4); + let low = read_f64(5); + let close = read_f64(6); + let source = read_str(7); + let known_at_micros = read_i64(8); + + for i in 0..num_rows { + out.push(Fx1dParquetRow { + pair: Cow::Owned(pair[i].clone()), + session_date: session_date[i], + ts_micros: ts_micros[i], + open: open[i], + high: high[i], + low: low[i], + close: close[i], + source: Cow::Owned(source[i].clone()), + known_at_micros: known_at_micros[i], + }); + } + } + out + } + + pub(super) fn assert_row_bitwise_eq(actual: &Fx1dParquetRow, expected: &Fx1dParquetRow) { + assert_eq!(actual.pair, expected.pair); + assert_eq!(actual.session_date, expected.session_date); + assert_eq!(actual.ts_micros, expected.ts_micros); + assert_eq!(actual.open.to_bits(), expected.open.to_bits()); + assert_eq!(actual.high.to_bits(), expected.high.to_bits()); + assert_eq!(actual.low.to_bits(), expected.low.to_bits()); + assert_eq!(actual.close.to_bits(), expected.close.to_bits()); + assert_eq!(actual.source, expected.source); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + } + + pub(super) fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + for entry in fs::read_dir(dir).expect("read dir") { + let entry = entry.expect("dir entry"); + let name = entry.file_name().to_string_lossy().into_owned(); + assert!( + !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", + "unexpected transient file remaining: {}", + entry.path().display() + ); + } + } + + #[test] + fn schema_matches_contract_names_types_nullability_and_order() { + let schema = fx_1d_parquet_schema().expect("build schema"); + assert_eq!(schema.name(), "fx_1d"); + let fields = schema.get_fields(); + assert_eq!(fields.len(), 9); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 9] = [ + ( + "pair", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "session_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "ts", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "open", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "high", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "low", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "close", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + let f = &fields[idx]; + assert_eq!(f.name(), name, "field {idx} name"); + assert_eq!(f.get_physical_type(), phys, "field {name} physical type"); + assert_eq!( + f.get_basic_info().repetition(), + rep, + "field {name} repetition" + ); + assert_eq!( + f.get_basic_info().logical_type_ref().cloned(), + logical, + "field {name} logical type" + ); + assert_eq!( + f.get_basic_info().converted_type(), + converted, + "field {name} converted type" + ); + } + } + + #[test] + fn build_fx_1d_round_trip_bitwise_and_zstd_on_every_column_chunk() { + let tmp = TempDirGuard::new("round-trip"); + let d0 = day(1969, 12, 31); // negative epoch day (-1) + let d1 = day(1971, 1, 4); + let d2 = day(2025, 1, 3); + let d3 = day(2026, 1, 2); + + let eod = [ + FxDailyBar { + session_date: d0, + open: 1.0731, + high: 1.0755, + low: 1.0710, + close: 1.0742, + }, + FxDailyBar { + session_date: d1, + open: 1.0105, + high: 1.0120, + low: 1.0090, + close: 1.0112, + }, + ]; + let te = [ + FxDailyBar { + session_date: d2, + open: 1.4340, + high: 1.4395, + low: 1.4310, + close: 1.4375, + }, + FxDailyBar { + session_date: d3, + open: 1.3805, + high: 1.3900, + low: 1.3750, + close: 1.3855, + }, + ]; + + let built = build_fx_1d(&eod, &te); + let rows: Vec = built + .rows + .iter() + .map(|r| { + let ts = close_ts_micros(r.session_date); + let row = Fx1dParquetRow::from_fx_row(r, ts, ts); + assert!(matches!(row.pair, Cow::Borrowed(_))); + assert!(matches!(row.source, Cow::Borrowed(_))); + row + }) + .collect(); + + let opts = Fx1dWriteOptions { + row_group_rows: 2, + ..Fx1dWriteOptions::default() + }; + let stats = write_fx_1d_dataset(tmp.path(), &rows, opts).unwrap(); + + assert_eq!(stats.rows_written, 4); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 2); + assert!(stats.bytes_written > 0); + + let path = tmp.path().join("fx_1d/part.parquet"); + assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written); + + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().num_rows(), 4); + assert_eq!(meta.num_row_groups(), 2); + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} expected ZSTD, got {:?}", + col.column_path(), + col.compression() + ); + } + } + + let actual = read_parquet_rows(&path); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } + assert_eq!(actual[0].session_date, -1); + assert_eq!(actual[0].source.as_ref(), FxSource::EodCadForex.as_str()); + assert_eq!(actual[2].source.as_ref(), FxSource::TeUsdCad.as_str()); + assert_no_transient_files(&tmp.path().join("fx_1d")); + } + + #[test] + fn empty_input_creates_nothing_and_preserves_existing_part_parquet() { + let tmp = TempDirGuard::new("empty"); + let fresh = tmp.path().join("fresh"); + let stats = write_fx_1d_dataset( + &fresh, + std::iter::empty::(), + Fx1dWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats, Fx1dWriteStats::default()); + assert!(!fresh.exists(), "empty input must not create out_dir"); + + let seeded = tmp.path().join("seeded"); + let seed_rows = vec![make_row( + FX_PAIR_USDCAD, + day(2024, 3, 15), + 1.350, + 1.360, + 1.345, + 1.355, + FxSource::EodCadForex, + )]; + write_fx_1d_dataset(&seeded, &seed_rows, Fx1dWriteOptions::default()).unwrap(); + let part = seeded.join("fx_1d/part.parquet"); + let before = fs::read(&part).unwrap(); + + let empty_stats = write_fx_1d_dataset( + &seeded, + std::iter::empty::(), + Fx1dWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_stats, Fx1dWriteStats::default()); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&seeded.join("fx_1d")); + } + + #[test] + fn determinism_identical_rows_produce_byte_identical_files() { + let tmp = TempDirGuard::new("determinism"); + let rows = vec![ + make_row( + "EURUSD", + day(2024, 1, 15), + 1.090, + 1.095, + 1.088, + 1.092, + FxSource::EodCadForex, + ), + make_row( + FX_PAIR_USDCAD, + day(2024, 1, 15), + 1.340, + 1.345, + 1.338, + 1.342, + FxSource::EodCadForex, + ), + make_row( + FX_PAIR_USDCAD, + day(2024, 1, 16), + 1.342, + 1.350, + 1.341, + 1.348, + FxSource::TeUsdCad, + ), + ]; + + let out_a = tmp.path().join("a"); + let out_b = tmp.path().join("b"); + let opts = Fx1dWriteOptions { + row_group_rows: 2, + ..Fx1dWriteOptions::default() + }; + write_fx_1d_dataset(&out_a, &rows, opts).unwrap(); + write_fx_1d_dataset(&out_b, &rows, opts).unwrap(); + + let bytes_a = fs::read(out_a.join("fx_1d/part.parquet")).unwrap(); + let bytes_b = fs::read(out_b.join("fx_1d/part.parquet")).unwrap(); + assert_eq!(bytes_a, bytes_b); + } +} + +#[cfg(test)] +#[path = "parquet_fx_tests.rs"] +mod edge_case_tests; diff --git a/tools/curate-etl/src/parquet_fx_tests.rs b/tools/curate-etl/src/parquet_fx_tests.rs new file mode 100644 index 00000000..ef9beb07 --- /dev/null +++ b/tools/curate-etl/src/parquet_fx_tests.rs @@ -0,0 +1,1091 @@ +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use parquet::basic::Encoding; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::tests::{ + assert_no_transient_files, assert_row_bitwise_eq, close_ts_micros, day, make_row, + read_parquet_rows, TempDirGuard, +}; +use super::{ + write_fx_1d_dataset, write_fx_1d_dataset_with_hooks, Fx1dParquetRow, Fx1dWriteOptions, + ParquetFxError, +}; +use crate::fx::{FxSource, FX_PAIR_USDCAD}; + +fn seed_existing(out_dir: &Path) -> (PathBuf, Vec) { + let seed = vec![ + make_row( + FX_PAIR_USDCAD, + day(2024, 1, 15), + 1.340, + 1.348, + 1.337, + 1.344, + FxSource::EodCadForex, + ), + make_row( + FX_PAIR_USDCAD, + day(2024, 1, 16), + 1.344, + 1.352, + 1.341, + 1.349, + FxSource::TeUsdCad, + ), + ]; + write_fx_1d_dataset(out_dir, &seed, Fx1dWriteOptions::default()).unwrap(); + let part = out_dir.join("fx_1d/part.parquet"); + let before = fs::read(&part).unwrap(); + (part, before) +} + +#[test] +fn single_row_and_row_group_boundary_counts_with_multi_pair_and_pre_1970() { + let tmp = TempDirGuard::new("rg-boundaries"); + + // 1 row (including negative pre-1970 epoch day) + let out_1 = tmp.path().join("one"); + let single = vec![make_row( + FX_PAIR_USDCAD, + day(1969, 12, 31), + 1.073, + 1.076, + 1.071, + 1.074, + FxSource::EodCadForex, + )]; + let stats_1 = write_fx_1d_dataset(&out_1, &single, Fx1dWriteOptions::default()).unwrap(); + assert_eq!(stats_1.rows_written, 1); + assert_eq!(stats_1.files_written, 1); + assert_eq!(stats_1.row_groups_written, 1); + let actual_1 = read_parquet_rows(&out_1.join("fx_1d/part.parquet")); + assert_eq!(actual_1.len(), 1); + assert_row_bitwise_eq(&actual_1[0], &single[0]); + assert_eq!(actual_1[0].session_date, -1); + + // Exactly row_group_rows (4 rows, row_group_rows = 4 => 1 row group) + let base = day(2024, 1, 2); + let rows_exact: Vec = (0..4_i32) + .map(|i| { + let open = 1.33 + f64::from(i) * 0.005; + make_row( + FX_PAIR_USDCAD, + base + i, + open, + open + 0.008, + open - 0.004, + open + 0.002, + if i % 2 == 0 { + FxSource::EodCadForex + } else { + FxSource::TeUsdCad + }, + ) + }) + .collect(); + let out_exact = tmp.path().join("exact"); + let opts = Fx1dWriteOptions { + row_group_rows: 4, + ..Fx1dWriteOptions::default() + }; + let stats_exact = write_fx_1d_dataset(&out_exact, &rows_exact, opts).unwrap(); + assert_eq!(stats_exact.rows_written, 4); + assert_eq!(stats_exact.row_groups_written, 1); + let reader_exact = + SerializedFileReader::new(File::open(out_exact.join("fx_1d/part.parquet")).unwrap()) + .unwrap(); + assert_eq!(reader_exact.metadata().num_row_groups(), 1); + assert_eq!(reader_exact.metadata().row_group(0).num_rows(), 4); + + // row_group_rows + 1 (5 rows, row_group_rows = 4 => 2 row groups: [4, 1]) + // Multi-pair + negative pre-1970 date + both sources. + let rows_plus_one = vec![ + make_row( + "EURUSD", + day(1969, 6, 15), + 1.120, + 1.125, + 1.118, + 1.122, + FxSource::EodCadForex, + ), + make_row( + "EURUSD", + base, + 1.090, + 1.096, + 1.087, + 1.093, + FxSource::TeUsdCad, + ), + make_row( + "GBPUSD", + base, + 1.265, + 1.272, + 1.261, + 1.268, + FxSource::EodCadForex, + ), + make_row( + FX_PAIR_USDCAD, + day(1969, 12, 31), + 1.073, + 1.075, + 1.071, + 1.074, + FxSource::EodCadForex, + ), + make_row( + FX_PAIR_USDCAD, + base, + 1.345, + 1.351, + 1.342, + 1.348, + FxSource::TeUsdCad, + ), + ]; + let out_plus = tmp.path().join("plus-one"); + let stats_plus = write_fx_1d_dataset(&out_plus, &rows_plus_one, opts).unwrap(); + assert_eq!(stats_plus.rows_written, 5); + assert_eq!(stats_plus.row_groups_written, 2); + let p_plus = out_plus.join("fx_1d/part.parquet"); + let reader_plus = SerializedFileReader::new(File::open(&p_plus).unwrap()).unwrap(); + let rg_sizes: Vec = (0..reader_plus.metadata().num_row_groups()) + .map(|i| reader_plus.metadata().row_group(i).num_rows()) + .collect(); + assert_eq!(rg_sizes, vec![4, 1]); + let actual_plus = read_parquet_rows(&p_plus); + assert_eq!(actual_plus.len(), rows_plus_one.len()); + for (a, e) in actual_plus.iter().zip(&rows_plus_one) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&out_plus.join("fx_1d")); +} + +#[test] +fn pair_and_source_columns_use_dictionary_encoding_and_invalid_options_preserve_state() { + let tmp = TempDirGuard::new("dict-zstd"); + let base = day(2024, 1, 2); + let rows: Vec = (0..64_i32) + .map(|i| { + let pair = if i < 32 { "EURUSD" } else { FX_PAIR_USDCAD }; + let d = base + (i % 32); + let open = 1.20 + f64::from(i % 32) * 0.001; + make_row( + pair, + d, + open, + open + 0.005, + open - 0.003, + open + 0.001, + if i % 3 == 0 { + FxSource::TeUsdCad + } else { + FxSource::EodCadForex + }, + ) + }) + .collect(); + + let out_ok = tmp.path().join("lvl-3"); + write_fx_1d_dataset(&out_ok, &rows, Fx1dWriteOptions::default()).unwrap(); + let p = out_ok.join("fx_1d/part.parquet"); + let reader = SerializedFileReader::new(File::open(&p).unwrap()).unwrap(); + let rg0 = reader.metadata().row_group(0); + + for (col_idx, name) in [(0usize, "pair"), (7usize, "source")] { + let col = rg0.column(col_idx); + assert!( + col.encodings().any(|e| { + matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY) + }), + "expected dictionary encoding on {name} column, got {:?}", + col.encodings().collect::>() + ); + } + + // Invalid row_group_rows and zstd_level in fresh dir + let out_bad = tmp.path().join("bad-opts-fresh"); + assert!(matches!( + write_fx_1d_dataset( + &out_bad, + &rows, + Fx1dWriteOptions { + row_group_rows: 0, + ..Fx1dWriteOptions::default() + } + ), + Err(ParquetFxError::InvalidRowGroupRows) + )); + assert!(matches!( + write_fx_1d_dataset( + &out_bad, + &rows, + Fx1dWriteOptions { + zstd_level: 23, + ..Fx1dWriteOptions::default() + } + ), + Err(ParquetFxError::InvalidZstdLevel { level: 23 }) + )); + assert!(matches!( + write_fx_1d_dataset( + &out_bad, + &rows, + Fx1dWriteOptions { + zstd_level: 99, + ..Fx1dWriteOptions::default() + } + ), + Err(ParquetFxError::InvalidZstdLevel { level: 99 }) + )); + assert!(!out_bad.exists(), "invalid options must not create out_dir"); + + // Invalid options in seeded dir leave existing part.parquet byte-identical + let out_seeded = tmp.path().join("bad-opts-seeded"); + let (part, before) = seed_existing(&out_seeded); + assert!(matches!( + write_fx_1d_dataset( + &out_seeded, + &rows, + Fx1dWriteOptions { + row_group_rows: 0, + ..Fx1dWriteOptions::default() + } + ), + Err(ParquetFxError::InvalidRowGroupRows) + )); + assert!(matches!( + write_fx_1d_dataset( + &out_seeded, + &rows, + Fx1dWriteOptions { + zstd_level: 23, + ..Fx1dWriteOptions::default() + } + ), + Err(ParquetFxError::InvalidZstdLevel { level: 23 }) + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&out_seeded.join("fx_1d")); +} + +#[test] +fn overwrite_replaces_existing_part_parquet_and_leaves_no_transients() { + let tmp = TempDirGuard::new("overwrite"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![ + make_row( + FX_PAIR_USDCAD, + day(2025, 4, 15), + 1.385, + 1.392, + 1.380, + 1.389, + FxSource::EodCadForex, + ), + make_row( + FX_PAIR_USDCAD, + day(2025, 4, 16), + 1.389, + 1.395, + 1.386, + 1.391, + FxSource::TeUsdCad, + ), + ]; + let stats = + write_fx_1d_dataset(tmp.path(), &replacement, Fx1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 2); + assert_eq!(stats.files_written, 1); + + let after = fs::read(&part).unwrap(); + assert_ne!(after, before); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), replacement.len()); + for (a, e) in actual.iter().zip(&replacement) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("fx_1d")); +} + +#[test] +fn ts_and_known_at_boundaries_pass_and_extreme_dates_do_not_overflow() { + let tmp = TempDirGuard::new("ts-bounds"); + let neg_day = day(1969, 12, 31); // -1 + let pos_day = day(2024, 3, 15); + let micros_per_day = 86_400_000_000_i64; + + // First microsecond and last microsecond of both negative and positive days pass, + // including known_at_micros == ts_micros. + let valid_rows = vec![ + Fx1dParquetRow { + ts_micros: i64::from(neg_day) * micros_per_day, + known_at_micros: i64::from(neg_day) * micros_per_day, + ..make_row( + "EURUSD", + neg_day, + 1.05, + 1.06, + 1.04, + 1.055, + FxSource::EodCadForex, + ) + }, + Fx1dParquetRow { + ts_micros: i64::from(neg_day + 1) * micros_per_day - 1, + known_at_micros: i64::from(neg_day + 1) * micros_per_day - 1, + ..make_row( + FX_PAIR_USDCAD, + neg_day, + 1.073, + 1.076, + 1.071, + 1.074, + FxSource::EodCadForex, + ) + }, + Fx1dParquetRow { + ts_micros: i64::from(pos_day) * micros_per_day, + known_at_micros: i64::from(pos_day) * micros_per_day, + ..make_row( + FX_PAIR_USDCAD, + pos_day, + 1.350, + 1.358, + 1.347, + 1.354, + FxSource::TeUsdCad, + ) + }, + Fx1dParquetRow { + ts_micros: i64::from(pos_day + 1) * micros_per_day - 1, + known_at_micros: i64::from(pos_day + 1) * micros_per_day - 1, + ..make_row( + FX_PAIR_USDCAD, + pos_day + 1, + 1.354, + 1.360, + 1.350, + 1.356, + FxSource::TeUsdCad, + ) + }, + ]; + // Fix row 3 ts_micros to be last microsecond of pos_day + 1 + let mut valid_rows = valid_rows; + valid_rows[3].ts_micros = i64::from(pos_day + 2) * micros_per_day - 1; + valid_rows[3].known_at_micros = valid_rows[3].ts_micros; + + let out = tmp.path().join("valid"); + let stats = write_fx_1d_dataset(&out, &valid_rows, Fx1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 4); + let actual = read_parquet_rows(&out.join("fx_1d/part.parquet")); + for (a, e) in actual.iter().zip(&valid_rows) { + assert_row_bitwise_eq(a, e); + } + + // One microsecond before day_start or at day_end fails (both negative and positive days), + // and extreme i32::MIN / i32::MAX do not overflow. + let bad_ts_cases = [ + (neg_day, i64::from(neg_day) * micros_per_day - 1), + (neg_day, i64::from(neg_day + 1) * micros_per_day), + (pos_day, i64::from(pos_day) * micros_per_day - 1), + (pos_day, i64::from(pos_day + 1) * micros_per_day), + (i32::MIN, i64::MIN), + (i32::MAX, i64::MAX), + ]; + let bad_out = tmp.path().join("bad-ts"); + for (session_date, ts_micros) in bad_ts_cases { + let row = Fx1dParquetRow { + pair: Cow::Borrowed(FX_PAIR_USDCAD), + session_date, + ts_micros, + open: 1.35, + high: 1.36, + low: 1.34, + close: 1.355, + source: Cow::Borrowed(FxSource::EodCadForex.as_str()), + known_at_micros: ts_micros, + }; + let err = + write_fx_1d_dataset(&bad_out, &[row], Fx1dWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetFxError::TsOutsideSessionDate { + session_date: sd, + ts_micros: ts, + .. + } if sd == session_date && ts == ts_micros + ), + "expected TsOutsideSessionDate for ({session_date}, {ts_micros}), got {err:?}" + ); + } + assert!(!bad_out.exists()); +} + +#[test] +fn invalid_inputs_return_typed_errors_in_fresh_and_seeded_dirs() { + let tmp = TempDirGuard::new("invalid-inputs"); + let fresh = tmp.path().join("fresh"); + let seeded = tmp.path().join("seeded"); + let (part, before) = seed_existing(&seeded); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 3, 18); + + let check_both = |rows: &[Fx1dParquetRow], check: &dyn Fn(&ParquetFxError)| { + let err_fresh = + write_fx_1d_dataset(&fresh, rows, Fx1dWriteOptions::default()).unwrap_err(); + check(&err_fresh); + assert!( + !fresh.join("fx_1d/part.parquet").exists(), + "fresh dir must not contain part.parquet after error: {err_fresh}" + ); + assert_no_transient_files(&fresh.join("fx_1d")); + + let err_seeded = + write_fx_1d_dataset(&seeded, rows, Fx1dWriteOptions::default()).unwrap_err(); + check(&err_seeded); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&seeded.join("fx_1d")); + }; + + // 1. Unsorted (pair goes backwards) + let unsorted_pair = vec![ + make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex), + make_row("EURUSD", d2, 1.09, 1.10, 1.08, 1.095, FxSource::EodCadForex), + ]; + check_both(&unsorted_pair, &|err| { + assert!( + matches!( + err, + ParquetFxError::UnsortedInput { + prev_pair, + prev_session_date, + pair, + session_date, + } if prev_pair == FX_PAIR_USDCAD + && *prev_session_date == d1 + && pair == "EURUSD" + && *session_date == d2 + ), + "got {err:?}" + ); + }); + + // 2. Unsorted (session_date goes backwards for same pair) + let unsorted_date = vec![ + make_row(FX_PAIR_USDCAD, d2, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex), + make_row(FX_PAIR_USDCAD, d1, 1.34, 1.35, 1.33, 1.345, FxSource::EodCadForex), + ]; + check_both(&unsorted_date, &|err| { + assert!( + matches!( + err, + ParquetFxError::UnsortedInput { + prev_pair, + prev_session_date, + pair, + session_date, + } if prev_pair == FX_PAIR_USDCAD + && *prev_session_date == d2 + && pair == FX_PAIR_USDCAD + && *session_date == d1 + ), + "got {err:?}" + ); + }); + + // 3. Duplicate (pair, session_date) + let duplicate = vec![ + make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex), + make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::TeUsdCad), + ]; + check_both(&duplicate, &|err| { + assert!( + matches!( + err, + ParquetFxError::DuplicateKey { pair, session_date } + if pair == FX_PAIR_USDCAD && *session_date == d1 + ), + "got {err:?}" + ); + }); + + // 4. EmptyPair (empty & whitespace, both first row and after a valid row) + for bad_pair in ["", " ", "\t\n"] { + let first_bad = vec![Fx1dParquetRow { + pair: Cow::Owned(bad_pair.to_string()), + ..make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex) + }]; + check_both(&first_bad, &|err| { + assert!( + matches!(err, ParquetFxError::EmptyPair { session_date } if *session_date == d1), + "expected EmptyPair for {bad_pair:?}, got {err:?}" + ); + }); + + // Second row empty pair must report EmptyPair (not UnsortedInput) + let second_bad = vec![ + make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex), + Fx1dParquetRow { + pair: Cow::Owned(bad_pair.to_string()), + ..make_row(FX_PAIR_USDCAD, d2, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex) + }, + ]; + check_both(&second_bad, &|err| { + assert!( + matches!(err, ParquetFxError::EmptyPair { session_date } if *session_date == d2), + "expected EmptyPair on row 2 for {bad_pair:?}, got {err:?}" + ); + }); + } + + // 5. EmptySource (empty & whitespace) + for bad_source in ["", " ", "\t\n"] { + let rows = vec![Fx1dParquetRow { + source: Cow::Owned(bad_source.to_string()), + ..make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex) + }]; + check_both(&rows, &|err| { + assert!( + matches!( + err, + ParquetFxError::EmptySource { pair, session_date } + if pair == FX_PAIR_USDCAD && *session_date == d1 + ), + "expected EmptySource for {bad_source:?}, got {err:?}" + ); + }); + } + + // 6. InvalidOhlc (NaN, +inf, -inf, 0.0, -0.0, negative) + let invalid_ohlc_cases = [ + (f64::NAN, 1.36, 1.34, 1.35), + (1.35, f64::INFINITY, 1.34, 1.35), + (1.35, 1.36, f64::NEG_INFINITY, 1.35), + (1.35, 1.36, 1.34, 0.0), + (-0.0, 1.36, 1.34, 1.35), + (1.35, 1.36, -0.01, 1.35), + ]; + for (o, h, l, c) in invalid_ohlc_cases { + let rows = vec![make_row( + FX_PAIR_USDCAD, + d1, + o, + h, + l, + c, + FxSource::EodCadForex, + )]; + check_both(&rows, &|err| { + assert!( + matches!( + err, + ParquetFxError::InvalidOhlc { pair, session_date, .. } + if pair == FX_PAIR_USDCAD && *session_date == d1 + ), + "expected InvalidOhlc for ({o}, {h}, {l}, {c}), got {err:?}" + ); + }); + } + + // 7. InconsistentOhlc (high < low, open < low, open > high, close < low, close > high) + let inconsistent_ohlc_cases = [ + (1.35, 1.33, 1.36, 1.35), // high < low + (1.33, 1.36, 1.34, 1.35), // open < low + (1.37, 1.36, 1.34, 1.35), // open > high + (1.35, 1.36, 1.34, 1.33), // close < low + (1.35, 1.36, 1.34, 1.37), // close > high + ]; + for (o, h, l, c) in inconsistent_ohlc_cases { + let rows = vec![make_row( + FX_PAIR_USDCAD, + d1, + o, + h, + l, + c, + FxSource::EodCadForex, + )]; + check_both(&rows, &|err| { + assert!( + matches!( + err, + ParquetFxError::InconsistentOhlc { pair, session_date, .. } + if pair == FX_PAIR_USDCAD && *session_date == d1 + ), + "expected InconsistentOhlc for ({o}, {h}, {l}, {c}), got {err:?}" + ); + }); + } + + // 8. TsOutsideSessionDate + let day_start = i64::from(d1) * 86_400_000_000; + for bad_ts in [day_start - 1, day_start + 86_400_000_000] { + let rows = vec![Fx1dParquetRow { + ts_micros: bad_ts, + known_at_micros: bad_ts, + ..make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex) + }]; + check_both(&rows, &|err| { + assert!( + matches!( + err, + ParquetFxError::TsOutsideSessionDate { pair, session_date, ts_micros } + if pair == FX_PAIR_USDCAD && *session_date == d1 && *ts_micros == bad_ts + ), + "expected TsOutsideSessionDate for {bad_ts}, got {err:?}" + ); + }); + } + + // 9. KnownAtBeforeTs + let ts = close_ts_micros(d1); + let bad_known = vec![Fx1dParquetRow { + ts_micros: ts, + known_at_micros: ts - 1, + ..make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex) + }]; + check_both(&bad_known, &|err| { + assert!( + matches!( + err, + ParquetFxError::KnownAtBeforeTs { + pair, + session_date, + ts_micros, + known_at_micros, + } if pair == FX_PAIR_USDCAD + && *session_date == d1 + && *ts_micros == ts + && *known_at_micros == ts - 1 + ), + "expected KnownAtBeforeTs, got {err:?}" + ); + }); +} + +#[test] +fn mid_stream_failure_after_flushed_row_groups_preserves_existing_part_parquet() { + let tmp = TempDirGuard::new("mid-stream-fail"); + let (part, before) = seed_existing(tmp.path()); + let base = day(2024, 1, 2); + + let mut rows = vec![ + make_row(FX_PAIR_USDCAD, base, 1.33, 1.34, 1.32, 1.335, FxSource::EodCadForex), + make_row(FX_PAIR_USDCAD, base + 1, 1.335, 1.345, 1.33, 1.34, FxSource::EodCadForex), + make_row(FX_PAIR_USDCAD, base + 2, 1.34, 1.35, 1.335, 1.345, FxSource::TeUsdCad), + make_row(FX_PAIR_USDCAD, base + 3, 1.345, 1.355, 1.34, 1.35, FxSource::TeUsdCad), + ]; + // 5th row fails after 2 row groups of size 2 have already been flushed to staging. + rows.push(make_row( + FX_PAIR_USDCAD, + base + 4, + -1.0, + 1.36, + 1.34, + 1.35, + FxSource::TeUsdCad, + )); + + let err = write_fx_1d_dataset( + tmp.path(), + &rows, + Fx1dWriteOptions { + row_group_rows: 2, + ..Fx1dWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetFxError::InvalidOhlc { .. })); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("fx_1d")); +} + +#[test] +fn out_dir_or_fx_1d_occupied_by_regular_file_returns_io_error() { + let tmp = TempDirGuard::new("io-blocker"); + let rows = vec![make_row( + FX_PAIR_USDCAD, + day(2024, 3, 15), + 1.35, + 1.36, + 1.34, + 1.355, + FxSource::EodCadForex, + )]; + + let file_as_out = tmp.path().join("not-a-dir"); + fs::write(&file_as_out, b"sentinel").unwrap(); + let err = write_fx_1d_dataset(&file_as_out, &rows, Fx1dWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetFxError::Io { .. })); + assert!(StdError::source(&err).is_some()); + assert_eq!(fs::read(&file_as_out).unwrap(), b"sentinel"); + + let out_with_file_fx = tmp.path().join("fx-is-file"); + fs::create_dir_all(&out_with_file_fx).unwrap(); + let fx_file = out_with_file_fx.join("fx_1d"); + fs::write(&fx_file, b"file-not-dir").unwrap(); + let err2 = + write_fx_1d_dataset(&out_with_file_fx, &rows, Fx1dWriteOptions::default()).unwrap_err(); + assert!(matches!(err2, ParquetFxError::Io { .. })); + assert_eq!(fs::read(&fx_file).unwrap(), b"file-not-dir"); +} + +#[test] +fn stale_lock_times_out_leaving_lock_and_existing_part_intact() { + let tmp = TempDirGuard::new("stale-lock"); + let (part, before) = seed_existing(tmp.path()); + let lock_path = tmp.path().join("fx_1d/.write.lock"); + fs::write(&lock_path, b"999999\n").unwrap(); + + let rows = vec![make_row( + FX_PAIR_USDCAD, + day(2024, 6, 15), + 1.37, + 1.38, + 1.36, + 1.375, + FxSource::EodCadForex, + )]; + let err = write_fx_1d_dataset_with_hooks( + tmp.path(), + &rows, + Fx1dWriteOptions::default(), + Duration::from_millis(30), + |_, _| {}, + |path| fs::remove_file(path), + ) + .unwrap_err(); + + assert!( + matches!(err, ParquetFxError::LockTimeout { ref path, .. } if path == &lock_path), + "expected LockTimeout, got {err:?}" + ); + assert!( + lock_path.exists(), + "stale lock must not be deleted by timed-out writer" + ); + assert_eq!(fs::read(&part).unwrap(), before); +} + +#[test] +fn live_part_parquet_stays_readable_between_backup_and_rename() { + let tmp = TempDirGuard::new("live-readable"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![make_row( + FX_PAIR_USDCAD, + day(2024, 9, 15), + 1.360, + 1.365, + 1.355, + 1.362, + FxSource::TeUsdCad, + )]; + let observed_live = Arc::new(Mutex::new(false)); + let observed_clone = Arc::clone(&observed_live); + + write_fx_1d_dataset_with_hooks( + tmp.path(), + &replacement, + Fx1dWriteOptions::default(), + Duration::from_secs(5), + move |final_path, backup_path| { + assert!( + backup_path.is_some(), + "expected backup path for existing file" + ); + assert_eq!(fs::read(final_path).unwrap(), before); + assert_eq!(fs::read(backup_path.unwrap()).unwrap(), before); + *observed_clone.lock().unwrap() = true; + }, + |path| fs::remove_file(path), + ) + .unwrap(); + + assert!(*observed_live.lock().unwrap()); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), 1); + assert_row_bitwise_eq(&actual[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("fx_1d")); +} + +#[test] +fn rename_failure_over_directory_blocker_cleans_up_staging_and_unowned_tmp_is_preserved() { + let tmp = TempDirGuard::new("rename-blocker"); + let fx_dir = tmp.path().join("fx_1d"); + let blocking_dir = fx_dir.join("part.parquet"); + fs::create_dir_all(&blocking_dir).unwrap(); + + let unowned_tmp = fx_dir.join("part.parquet.unowned-other-run.tmp"); + fs::write(&unowned_tmp, b"keep-me").unwrap(); + + let rows = vec![make_row( + FX_PAIR_USDCAD, + day(2024, 3, 15), + 1.35, + 1.36, + 1.34, + 1.355, + FxSource::EodCadForex, + )]; + let err = write_fx_1d_dataset(tmp.path(), &rows, Fx1dWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetFxError::Io { .. }), "got {err:?}"); + assert!(blocking_dir.is_dir(), "directory blocker must remain intact"); + assert_eq!( + fs::read(&unowned_tmp).unwrap(), + b"keep-me", + "unowned .tmp file must be preserved" + ); + + let mut entries: Vec = fs::read_dir(&fx_dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + entries.sort(); + assert_eq!( + entries, + vec![ + "part.parquet".to_string(), + "part.parquet.unowned-other-run.tmp".to_string(), + ] + ); +} + +#[test] +fn concurrent_in_process_writers_serialize_cleanly() { + let tmp = TempDirGuard::new("concurrent-unit"); + let out = Arc::new(tmp.path().to_path_buf()); + + let out_1 = Arc::clone(&out); + let handle_1 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + if i == 1 { + thread::sleep(Duration::from_millis(30)); + } + make_row( + "EURUSD", + day(2024, 1, 15) + i, + 1.09, + 1.10, + 1.08, + 1.095, + FxSource::EodCadForex, + ) + }); + write_fx_1d_dataset(out_1.as_path(), iter, Fx1dWriteOptions::default()) + }); + + thread::sleep(Duration::from_millis(5)); + let out_2 = Arc::clone(&out); + let handle_2 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + make_row( + FX_PAIR_USDCAD, + day(2024, 2, 15) + i, + 1.35, + 1.36, + 1.34, + 1.355, + FxSource::TeUsdCad, + ) + }); + write_fx_1d_dataset(out_2.as_path(), iter, Fx1dWriteOptions::default()) + }); + + let s1 = handle_1.join().unwrap().unwrap(); + let s2 = handle_2.join().unwrap().unwrap(); + assert_eq!(s1.rows_written, 2); + assert_eq!(s2.rows_written, 2); + + let got = read_parquet_rows(&tmp.path().join("fx_1d/part.parquet")); + assert_eq!(got.len(), 2); + assert!( + got.iter().all(|r| r.pair == "EURUSD") || got.iter().all(|r| r.pair == FX_PAIR_USDCAD), + "output must come entirely from one writer generation" + ); + assert_no_transient_files(&tmp.path().join("fx_1d")); +} + +#[test] +fn panicking_iterator_cleans_up_staging_file_and_releases_lock() { + let tmp = TempDirGuard::new("panic-unwind"); + let (part, before) = seed_existing(tmp.path()); + + let out = tmp.path().to_path_buf(); + let opts = Fx1dWriteOptions { + row_group_rows: 2, + ..Fx1dWriteOptions::default() + }; + let result = std::panic::catch_unwind(move || { + let base = day(2024, 3, 15); + let iter = (0..5_i32).map(move |i| { + if i == 3 { + panic!("simulated iterator panic after row-group flush"); + } + make_row( + FX_PAIR_USDCAD, + base + i, + 1.35, + 1.36, + 1.34, + 1.355, + FxSource::EodCadForex, + ) + }); + let _ = write_fx_1d_dataset(&out, iter, opts); + }); + assert!(result.is_err(), "iterator must have panicked"); + + // Pre-existing live file stays byte-identical and both staging `.tmp` and `.write.lock` + // are removed during unwind. + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("fx_1d")); + + // Subsequent writer succeeds immediately without hanging on a stale lock. + let replacement = vec![make_row( + FX_PAIR_USDCAD, + day(2024, 6, 15), + 1.37, + 1.38, + 1.36, + 1.375, + FxSource::TeUsdCad, + )]; + let stats = + write_fx_1d_dataset(tmp.path(), &replacement, Fx1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 1); + let got = read_parquet_rows(&part); + assert_eq!(got.len(), 1); + assert_row_bitwise_eq(&got[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("fx_1d")); +} + +#[test] +fn backup_unlink_failure_after_rename_restores_live_file_and_returns_error() { + let tmp = TempDirGuard::new("backup-unlink-fail"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![make_row( + FX_PAIR_USDCAD, + day(2024, 9, 15), + 1.360, + 1.365, + 1.355, + 1.362, + FxSource::TeUsdCad, + )]; + let observed_bak: Arc>> = Arc::new(Mutex::new(None)); + let observed_bak_clone = Arc::clone(&observed_bak); + + let err = write_fx_1d_dataset_with_hooks( + tmp.path(), + &replacement, + Fx1dWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + move |bak_path| { + *observed_bak_clone.lock().unwrap() = Some(bak_path.to_path_buf()); + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "simulated backup unlink failure", + )) + }, + ) + .unwrap_err(); + + let expected_bak = observed_bak + .lock() + .unwrap() + .clone() + .expect("backup unlink hook must be called"); + assert!( + matches!( + err, + ParquetFxError::Io { ref path, ref source } + if path == &expected_bak + && source.kind() == std::io::ErrorKind::PermissionDenied + ), + "expected Io error on backup path, got {err:?}" + ); + assert_eq!( + fs::read(&part).unwrap(), + before, + "live part.parquet must be atomically restored from backup" + ); + assert_no_transient_files(&tmp.path().join("fx_1d")); +} + +#[test] +fn backup_unlink_and_restore_failure_reports_rollback_failed() { + let tmp = TempDirGuard::new("backup-rollback-fail"); + let (part, _before) = seed_existing(tmp.path()); + + let replacement = vec![make_row( + FX_PAIR_USDCAD, + day(2024, 9, 15), + 1.360, + 1.365, + 1.355, + 1.362, + FxSource::TeUsdCad, + )]; + let observed_bak: Arc>> = Arc::new(Mutex::new(None)); + let observed_bak_clone = Arc::clone(&observed_bak); + + let err = write_fx_1d_dataset_with_hooks( + tmp.path(), + &replacement, + Fx1dWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + move |bak_path| { + *observed_bak_clone.lock().unwrap() = Some(bak_path.to_path_buf()); + // Remove the backup before returning an error so the restore rename also fails. + let _ = fs::remove_file(bak_path); + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "simulated backup unlink failure", + )) + }, + ) + .unwrap_err(); + + let expected_bak = observed_bak + .lock() + .unwrap() + .clone() + .expect("backup unlink hook must be called"); + match err { + ParquetFxError::RollbackFailed { cause, failures } => { + assert!( + matches!( + *cause, + ParquetFxError::Io { ref path, ref source } + if path == &expected_bak + && source.kind() == std::io::ErrorKind::PermissionDenied + ), + "unexpected cause: {cause:?}" + ); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].final_path, part); + assert_eq!(failures[0].backup_path.as_deref(), Some(expected_bak.as_path())); + assert_eq!(failures[0].source.kind(), std::io::ErrorKind::NotFound); + } + other => panic!("expected RollbackFailed, got {other:?}"), + } + assert_no_transient_files(&tmp.path().join("fx_1d")); +} diff --git a/tools/curate-etl/src/parquet_publish.rs b/tools/curate-etl/src/parquet_publish.rs new file mode 100644 index 00000000..fd9b89c2 --- /dev/null +++ b/tools/curate-etl/src/parquet_publish.rs @@ -0,0 +1,579 @@ +//! Shared internal helpers for streaming Zstd Parquet writers (`bars_1d`, `shorts`, ...). +//! +//! Covers per-dataset locking, exclusive staging/backup files, rollback accounting, +//! low-cardinality string interning, and typed Parquet column-chunk writes. + +use std::collections::HashMap; +use std::fmt; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; +use std::thread; +use std::time::{Duration, Instant}; + +use parquet::column::writer::ColumnWriter; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::writer::{SerializedColumnWriter, SerializedRowGroupWriter}; + +/// Default maximum number of rows buffered per Parquet row group. +pub const DEFAULT_ROW_GROUP_ROWS: usize = 1_000_000; + +/// Default Zstd compression level for curated Parquet files. +pub const DEFAULT_ZSTD_LEVEL: i32 = 3; + +pub(crate) const STRING_WRITE_BATCH_ROWS: usize = 4_096; +pub(crate) const FILE_BUF_CAPACITY_BYTES: usize = 64 * 1024; +const LINEAR_INTERN_LIMIT: usize = 8; +pub(crate) const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30); + +/// Single failure encountered while rolling back a partial publication. +#[derive(Debug)] +pub struct RollbackFailure { + pub final_path: PathBuf, + pub backup_path: Option, + pub source: io::Error, +} + +impl fmt::Display for RollbackFailure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.backup_path { + Some(bak) => write!( + f, + "partition '{}' (backup '{}'): {}", + self.final_path.display(), + bak.display(), + self.source + ), + None => write!( + f, + "partition '{}': {}", + self.final_path.display(), + self.source + ), + } + } +} + +/// Internal I/O or lock-acquisition error returned by publish helpers. +#[derive(Debug)] +pub(crate) enum PublishIoError { + LockTimeout { path: PathBuf, waited: Duration }, + Io { path: PathBuf, source: io::Error }, +} + +#[derive(Default)] +pub(crate) struct StringInterner { + values: Vec, + index: HashMap, +} + +impl StringInterner { + pub(crate) fn intern(&mut self, s: &str) -> u32 { + if self.values.len() <= LINEAR_INTERN_LIMIT { + let bytes = s.as_bytes(); + for (idx, existing) in self.values.iter().enumerate() { + if existing.data() == bytes { + return idx as u32; + } + } + let id = self.values.len() as u32; + self.values.push(ByteArray::from(s)); + if self.values.len() > LINEAR_INTERN_LIMIT { + self.index.reserve(self.values.len()); + for (i, val) in self.values.iter().enumerate() { + if let Ok(text) = std::str::from_utf8(val.data()) { + self.index.insert(text.to_owned(), i as u32); + } + } + } + return id; + } + + if let Some(&id) = self.index.get(s) { + return id; + } + let id = self.values.len() as u32; + self.values.push(ByteArray::from(s)); + self.index.insert(s.to_owned(), id); + id + } + + #[inline] + pub(crate) fn get(&self, id: u32) -> &ByteArray { + &self.values[id as usize] + } + + pub(crate) fn clear(&mut self) { + self.values.clear(); + self.index.clear(); + } +} + +static DATASET_LOCKS: OnceLock>>>> = OnceLock::new(); +static WRITE_RUN_SEQ: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn dataset_mutex(dataset_dir: &Path) -> Arc> { + let key = fs::canonicalize(dataset_dir).unwrap_or_else(|_| dataset_dir.to_path_buf()); + let map_mutex = DATASET_LOCKS.get_or_init(|| Mutex::new(HashMap::new())); + let mut map = map_mutex.lock().unwrap_or_else(|err| err.into_inner()); + map.retain(|_, weak| weak.strong_count() > 0); + if let Some(existing) = map.get(&key).and_then(Weak::upgrade) { + return existing; + } + let lock = Arc::new(Mutex::new(())); + map.insert(key, Arc::downgrade(&lock)); + lock +} + +pub(crate) struct DatasetFileLock { + path: PathBuf, +} + +impl DatasetFileLock { + pub(crate) fn acquire_with_timeout( + dataset_dir: &Path, + timeout: Duration, + ) -> Result { + let lock_path = dataset_dir.join(".write.lock"); + let start = Instant::now(); + let mut backoff_ms = 2u64; + loop { + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&lock_path) + { + Ok(mut file) => { + let _ = writeln!(file, "{}", std::process::id()); + let _ = file.sync_all(); + return Ok(Self { path: lock_path }); + } + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => { + let elapsed = start.elapsed(); + if elapsed >= timeout { + return Err(PublishIoError::LockTimeout { + path: lock_path, + waited: elapsed, + }); + } + let remaining = timeout.saturating_sub(elapsed); + thread::sleep(Duration::from_millis(backoff_ms).min(remaining)); + backoff_ms = (backoff_ms * 2).min(25); + } + Err(source) => { + return Err(PublishIoError::Io { + path: lock_path, + source, + }); + } + } + } + } +} + +impl Drop for DatasetFileLock { + fn drop(&mut self) { + let _ = fs::remove_file(&self.path); + } +} + +pub(crate) fn next_run_id() -> String { + let seq = WRITE_RUN_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + format!("{}-{seq}", std::process::id()) +} + +pub(crate) fn create_exclusive_tmp_file( + dir: &Path, + run_id: &str, +) -> Result<(PathBuf, File), PublishIoError> { + for attempt in 0..1024u32 { + let file_name = if attempt == 0 { + format!("part.parquet.{run_id}.tmp") + } else { + format!("part.parquet.{run_id}.{attempt}.tmp") + }; + let tmp_path = dir.join(file_name); + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path) + { + Ok(file) => return Ok((tmp_path, file)), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(PublishIoError::Io { + path: tmp_path, + source, + }); + } + } + } + Err(PublishIoError::Io { + path: dir.join(format!("part.parquet.{run_id}.tmp")), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique staging file names", + ), + }) +} + +fn is_hard_link_unsupported(err: &io::Error) -> bool { + matches!( + err.kind(), + io::ErrorKind::Unsupported | io::ErrorKind::PermissionDenied + ) +} + +fn copy_to_exclusive_backup(src: &Path, dst: &Path) -> io::Result<()> { + let mut dst_file = OpenOptions::new().write(true).create_new(true).open(dst)?; + let copy_res = (|| -> io::Result<()> { + let mut src_file = File::open(src)?; + io::copy(&mut src_file, &mut dst_file)?; + dst_file.sync_all()?; + Ok(()) + })(); + if let Err(err) = copy_res { + drop(dst_file); + let _ = fs::remove_file(dst); + return Err(err); + } + Ok(()) +} + +/// Creates a per-run rollback backup of `final_path` while keeping `final_path` intact on disk. +/// Uses an atomic hard link in the same directory when supported, falling back to an exclusive +/// file copy so readers never observe a missing `part.parquet` before replacement. +pub(crate) fn create_backup_preserving_live( + final_path: &Path, + run_id: &str, +) -> Result { + let parent = final_path.parent().unwrap_or_else(|| Path::new(".")); + for attempt in 0..1024u32 { + let file_name = if attempt == 0 { + format!("part.parquet.{run_id}.bak") + } else { + format!("part.parquet.{run_id}.{attempt}.bak") + }; + let bak_path = parent.join(file_name); + match fs::hard_link(final_path, &bak_path) { + Ok(()) => return Ok(bak_path), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(err) if is_hard_link_unsupported(&err) => { + match copy_to_exclusive_backup(final_path, &bak_path) { + Ok(()) => return Ok(bak_path), + Err(copy_err) if copy_err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(PublishIoError::Io { + path: bak_path, + source, + }); + } + } + } + Err(source) => { + return Err(PublishIoError::Io { + path: bak_path, + source, + }); + } + } + } + Err(PublishIoError::Io { + path: parent.join(format!("part.parquet.{run_id}.bak")), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique backup file names", + ), + }) +} + +pub(crate) fn cleanup_owned_files(owned_paths: &[PathBuf]) { + for path in owned_paths { + let _ = fs::remove_file(path); + } +} + +/// Drop guard that removes an exclusively created staging file unless disarmed +/// after successful publication. +pub(crate) struct StagingFileGuard { + path: Option, +} + +impl StagingFileGuard { + pub(crate) fn new(path: PathBuf) -> Self { + Self { path: Some(path) } + } + + pub(crate) fn disarm(&mut self) { + self.path = None; + } +} + +impl Drop for StagingFileGuard { + fn drop(&mut self) { + if let Some(path) = self.path.take() { + let _ = fs::remove_file(path); + } + } +} + +pub(crate) struct PublishedPartition { + pub(crate) final_path: PathBuf, + pub(crate) backup_path: Option, +} + +pub(crate) fn rollback_published(published: &[PublishedPartition]) -> Vec { + let mut failures = Vec::new(); + for part in published.iter().rev() { + match &part.backup_path { + Some(bak) => { + if let Err(source) = fs::rename(bak, &part.final_path) { + failures.push(RollbackFailure { + final_path: part.final_path.clone(), + backup_path: Some(bak.clone()), + source, + }); + } + } + None => { + if let Err(source) = fs::remove_file(&part.final_path) { + failures.push(RollbackFailure { + final_path: part.final_path.clone(), + backup_path: None, + source, + }); + } + } + } + } + failures +} + +fn next_column<'a>( + rg_writer: &'a mut SerializedRowGroupWriter<'_, BufWriter>, +) -> Result, ParquetError> { + match rg_writer.next_column()? { + Some(col) => Ok(col), + None => Err(ParquetError::General( + "unexpected end of Parquet schema columns".to_string(), + )), + } +} + +pub(crate) fn write_i32_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[i32], +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::Int32ColumnWriter(typed) => { + typed.write_batch(values, None, None)?; + } + _ => { + return Err(ParquetError::General( + "expected INT32 column writer".to_string(), + )); + } + } + col.close() +} + +pub(crate) fn write_optional_i32_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[i32], + def_levels: &[i16], +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::Int32ColumnWriter(typed) => { + typed.write_batch(values, Some(def_levels), None)?; + } + _ => { + return Err(ParquetError::General( + "expected INT32 column writer".to_string(), + )); + } + } + col.close() +} + +pub(crate) fn write_i64_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[i64], +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::Int64ColumnWriter(typed) => { + typed.write_batch(values, None, None)?; + } + _ => { + return Err(ParquetError::General( + "expected INT64 column writer".to_string(), + )); + } + } + col.close() +} + +pub(crate) fn write_f64_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[f64], + def_levels: Option<&[i16]>, +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::DoubleColumnWriter(typed) => { + typed.write_batch(values, def_levels, None)?; + } + _ => { + return Err(ParquetError::General( + "expected DOUBLE column writer".to_string(), + )); + } + } + col.close() +} + +pub(crate) fn write_optional_f64_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[f64], + def_levels: &[i16], +) -> Result<(), ParquetError> { + write_f64_col(rg_writer, values, Some(def_levels)) +} + +pub(crate) fn write_interned_str_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + ids: &[u32], + interner: &StringInterner, + scratch: &mut Vec, +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::ByteArrayColumnWriter(typed) => { + for chunk in ids.chunks(STRING_WRITE_BATCH_ROWS) { + scratch.clear(); + for &id in chunk { + scratch.push(interner.get(id).clone()); + } + typed.write_batch(scratch, None, None)?; + } + } + _ => { + return Err(ParquetError::General( + "expected BYTE_ARRAY column writer".to_string(), + )); + } + } + col.close() +} + +pub(crate) fn write_optional_interned_str_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + ids: &[u32], + def_levels: &[i16], + interner: &StringInterner, + scratch: &mut Vec, +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::ByteArrayColumnWriter(typed) => { + let mut val_idx = 0usize; + for def_chunk in def_levels.chunks(STRING_WRITE_BATCH_ROWS) { + scratch.clear(); + for &def in def_chunk { + match def { + 0 => {} + 1 => { + let &id = ids.get(val_idx).ok_or_else(|| { + ParquetError::General( + "optional string definition levels exceed value count" + .to_string(), + ) + })?; + scratch.push(interner.get(id).clone()); + val_idx += 1; + } + other => { + return Err(ParquetError::General(format!( + "invalid optional string definition level: {other}" + ))); + } + } + } + typed.write_batch(scratch, Some(def_chunk), None)?; + } + if val_idx != ids.len() { + return Err(ParquetError::General(format!( + "optional string value count mismatch: consumed {val_idx} of {}", + ids.len() + ))); + } + } + _ => { + return Err(ParquetError::General( + "expected BYTE_ARRAY column writer".to_string(), + )); + } + } + col.close() +} + +pub(crate) fn write_byte_array_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[ByteArray], +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::ByteArrayColumnWriter(typed) => { + for chunk in values.chunks(STRING_WRITE_BATCH_ROWS) { + typed.write_batch(chunk, None, None)?; + } + } + _ => { + return Err(ParquetError::General( + "expected BYTE_ARRAY column writer".to_string(), + )); + } + } + col.close() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dataset_mutex_shares_active_lock_and_prunes_expired_entries() { + let dir_a = PathBuf::from(format!( + "/tmp/curate-etl-weak-lock-a-{}-{}", + std::process::id(), + next_run_id() + )); + let dir_b = PathBuf::from(format!( + "/tmp/curate-etl-weak-lock-b-{}-{}", + std::process::id(), + next_run_id() + )); + + let lock_a1 = dataset_mutex(&dir_a); + let lock_a2 = dataset_mutex(&dir_a); + assert!(Arc::ptr_eq(&lock_a1, &lock_a2)); + + drop(lock_a1); + drop(lock_a2); + + // Next acquisition prunes the expired entry for `dir_a`. + let _lock_b = dataset_mutex(&dir_b); + let map = DATASET_LOCKS + .get() + .expect("registry initialized") + .lock() + .unwrap_or_else(|err| err.into_inner()); + assert!(!map.contains_key(&dir_a)); + assert!(map.contains_key(&dir_b)); + } +} diff --git a/tools/curate-etl/src/parquet_shorts.rs b/tools/curate-etl/src/parquet_shorts.rs new file mode 100644 index 00000000..342509cc --- /dev/null +++ b/tools/curate-etl/src/parquet_shorts.rs @@ -0,0 +1,1172 @@ +//! Streaming, atomic Zstd Parquet writer for `shorts`. +//! +//! Writes `/shorts/part.parquet` matching the 7-column contract schema in +//! `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `report_date` (`INT32`, `REQUIRED`, `DATE`) +//! 3. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 4. `shares_short` (`DOUBLE`, `REQUIRED`) +//! 5. `net_change` (`DOUBLE`, `OPTIONAL`) +//! 6. `pct_float` (`DOUBLE`, `OPTIONAL`) +//! 7. `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::parquet_publish::{ + create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, + write_f64_col, write_i32_col, write_i64_col, write_interned_str_col, DatasetFileLock, + PublishIoError, StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, + FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, +}; +pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; +use crate::shorts::ShortRow; + +const MICROS_PER_DAY: i128 = 86_400_000_000; + +/// Single `shorts` row matching the `design/DATA-CONTRACTS.md` Parquet schema. +#[derive(Debug, Clone, PartialEq)] +pub struct ShortsParquetRow { + pub listing_id: i32, + pub report_date: i32, + pub known_at_micros: i64, + pub shares_short: f64, + pub net_change: Option, + pub pct_float: Option, + pub source: Cow<'static, str>, +} + +impl From<&ShortRow> for ShortsParquetRow { + fn from(row: &ShortRow) -> Self { + Self { + listing_id: row.key, + report_date: row.report_date, + known_at_micros: row.known_at_utc_micros, + shares_short: row.shares_short, + net_change: row.net_change, + pct_float: row.pct_float, + source: Cow::Borrowed(row.source), + } + } +} + +impl From> for ShortsParquetRow { + fn from(row: ShortRow) -> Self { + Self::from(&row) + } +} + +/// Configuration for [`write_shorts_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ShortsWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for ShortsWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_shorts_dataset`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ShortsWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, +} + +/// Typed error returned by [`write_shorts_dataset`]. +#[derive(Debug)] +pub enum ParquetShortsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + UnsortedInput { + prev_listing_id: i32, + prev_report_date: i32, + listing_id: i32, + report_date: i32, + }, + DuplicateKey { + listing_id: i32, + report_date: i32, + }, + InvalidSharesShort { + listing_id: i32, + report_date: i32, + value: f64, + }, + InvalidNetChange { + listing_id: i32, + report_date: i32, + value: f64, + }, + InvalidPctFloat { + listing_id: i32, + report_date: i32, + value: f64, + }, + KnownAtNotAfterReportDate { + listing_id: i32, + report_date: i32, + known_at_micros: i64, + }, + EmptySource { + listing_id: i32, + report_date: i32, + }, + LockTimeout { + path: PathBuf, + waited: Duration, + }, + RollbackFailed { + cause: Box, + failures: Vec, + }, + Io { + path: PathBuf, + source: io::Error, + }, + Parquet { + path: PathBuf, + source: ParquetError, + }, +} + +impl fmt::Display for ParquetShortsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidRowGroupRows => { + write!(f, "invalid row_group_rows: must be greater than 0") + } + Self::InvalidZstdLevel { level } => { + write!(f, "invalid Zstd compression level: {level}") + } + Self::UnsortedInput { + prev_listing_id, + prev_report_date, + listing_id, + report_date, + } => write!( + f, + "unsorted input: ({listing_id}, {report_date}) follows ({prev_listing_id}, {prev_report_date})" + ), + Self::DuplicateKey { + listing_id, + report_date, + } => write!( + f, + "duplicate (listing_id, report_date) key: ({listing_id}, {report_date})" + ), + Self::InvalidSharesShort { + listing_id, + report_date, + value, + } => write!( + f, + "invalid shares_short {value} for ({listing_id}, {report_date}): must be finite and >= 0" + ), + Self::InvalidNetChange { + listing_id, + report_date, + value, + } => write!( + f, + "invalid net_change {value} for ({listing_id}, {report_date}): must be finite when present" + ), + Self::InvalidPctFloat { + listing_id, + report_date, + value, + } => write!( + f, + "invalid pct_float {value} for ({listing_id}, {report_date}): must be finite when present" + ), + Self::KnownAtNotAfterReportDate { + listing_id, + report_date, + known_at_micros, + } => write!( + f, + "known_at {known_at_micros} is not strictly after report_date {report_date} 00:00 UTC for listing_id {listing_id}" + ), + Self::EmptySource { + listing_id, + report_date, + } => write!( + f, + "empty source for ({listing_id}, {report_date}): must be non-empty" + ), + Self::LockTimeout { path, waited } => write!( + f, + "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", + waited.as_millis(), + path.display() + ), + Self::RollbackFailed { cause, failures } => { + write!( + f, + "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", + failures.len() + )?; + for failure in failures { + write!(f, " [{failure}]")?; + } + Ok(()) + } + Self::Io { path, source } => { + write!(f, "I/O error at '{}': {source}", path.display()) + } + Self::Parquet { path, source } => { + write!(f, "Parquet error at '{}': {source}", path.display()) + } + } + } +} + +impl Error for ParquetShortsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::Io { source, .. } => Some(source), + Self::Parquet { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for ParquetShortsError { + fn from(err: PublishIoError) -> Self { + match err { + PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, + PublishIoError::Io { path, source } => Self::Io { path, source }, + } + } +} + +/// Builds the exact 7-column Parquet schema for `shorts` per `design/DATA-CONTRACTS.md`. +pub fn shorts_parquet_schema() -> Result { + let fields: Vec = vec![ + Arc::new( + Type::primitive_type_builder("listing_id", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("report_date", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("shares_short", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("net_change", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("pct_float", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("shorts") + .with_fields(fields) + .build()?, + )) +} + +fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { + Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(zstd_level)) + .set_column_dictionary_enabled(ColumnPath::from("source"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn validate_row(row: &ShortsParquetRow) -> Result<(), ParquetShortsError> { + if !row.shares_short.is_finite() || row.shares_short < 0.0 { + return Err(ParquetShortsError::InvalidSharesShort { + listing_id: row.listing_id, + report_date: row.report_date, + value: row.shares_short, + }); + } + if let Some(value) = row.net_change { + if !value.is_finite() { + return Err(ParquetShortsError::InvalidNetChange { + listing_id: row.listing_id, + report_date: row.report_date, + value, + }); + } + } + if let Some(value) = row.pct_float { + if !value.is_finite() { + return Err(ParquetShortsError::InvalidPctFloat { + listing_id: row.listing_id, + report_date: row.report_date, + value, + }); + } + } + let report_midnight_micros = i128::from(row.report_date) * MICROS_PER_DAY; + if i128::from(row.known_at_micros) <= report_midnight_micros { + return Err(ParquetShortsError::KnownAtNotAfterReportDate { + listing_id: row.listing_id, + report_date: row.report_date, + known_at_micros: row.known_at_micros, + }); + } + if row.source.trim().is_empty() { + return Err(ParquetShortsError::EmptySource { + listing_id: row.listing_id, + report_date: row.report_date, + }); + } + Ok(()) +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + report_date: Vec, + known_at_micros: Vec, + shares_short: Vec, + net_change_values: Vec, + net_change_def_levels: Vec, + pct_float_values: Vec, + pct_float_def_levels: Vec, + source_ids: Vec, + source_interner: StringInterner, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &ShortsParquetRow) { + self.listing_id.push(row.listing_id); + self.report_date.push(row.report_date); + self.known_at_micros.push(row.known_at_micros); + self.shares_short.push(row.shares_short); + match row.net_change { + Some(v) => { + self.net_change_values.push(v); + self.net_change_def_levels.push(1); + } + None => { + self.net_change_def_levels.push(0); + } + } + match row.pct_float { + Some(v) => { + self.pct_float_values.push(v); + self.pct_float_def_levels.push(1); + } + None => { + self.pct_float_def_levels.push(0); + } + } + let source_id = self.source_interner.intern(row.source.as_ref()); + self.source_ids.push(source_id); + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.report_date.clear(); + self.known_at_micros.clear(); + self.shares_short.clear(); + self.net_change_values.clear(); + self.net_change_def_levels.clear(); + self.pct_float_values.clear(); + self.pct_float_def_levels.clear(); + self.source_ids.clear(); + self.source_interner.clear(); + } +} + +struct ShortsFileWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl ShortsFileWriter { + fn from_file( + tmp_path: PathBuf, + final_path: PathBuf, + file: File, + schema: &TypePtr, + props: &WriterPropertiesPtr, + ) -> Result { + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetShortsError::Parquet { + path: tmp_path.clone(), + source, + }, + )?; + + Ok(Self { + tmp_path, + final_path, + writer, + buf: RowGroupBuffer::default(), + rows_written: 0, + row_groups_written: 0, + }) + } + + fn flush_row_group(&mut self, scratch: &mut Vec) -> Result<(), ParquetShortsError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetShortsError::Parquet { + path: self.tmp_path.clone(), + source, + }; + + let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; + + // 1. listing_id (INT32, REQUIRED) + write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; + // 2. report_date (INT32, REQUIRED, DATE) + write_i32_col(&mut rg_writer, &self.buf.report_date).map_err(map_pq)?; + // 3. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; + // 4. shares_short (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.shares_short, None).map_err(map_pq)?; + // 5. net_change (DOUBLE, OPTIONAL) + write_f64_col( + &mut rg_writer, + &self.buf.net_change_values, + Some(&self.buf.net_change_def_levels), + ) + .map_err(map_pq)?; + // 6. pct_float (DOUBLE, OPTIONAL) + write_f64_col( + &mut rg_writer, + &self.buf.pct_float_values, + Some(&self.buf.pct_float_def_levels), + ) + .map_err(map_pq)?; + // 7. source (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.source_ids, + &self.buf.source_interner, + scratch, + ) + .map_err(map_pq)?; + + rg_writer.close().map_err(map_pq)?; + + self.rows_written += row_count; + self.row_groups_written += 1; + self.buf.clear(); + Ok(()) + } + + fn finish_and_sync( + mut self, + scratch: &mut Vec, + ) -> Result { + self.flush_row_group(scratch)?; + + let mut buf_writer = + self.writer + .into_inner() + .map_err(|source| ParquetShortsError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer.flush().map_err(|source| ParquetShortsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetShortsError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all().map_err(|source| ParquetShortsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetShortsError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedShortsFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedShortsFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +/// Streams strictly ascending `(listing_id, report_date)` rows into a single Zstd Parquet file +/// at `/shorts/part.parquet`. +/// +/// # Empty Input +/// Empty input returns `Ok(ShortsWriteStats::default())` without creating `/shorts` +/// and without modifying or removing any pre-existing `part.parquet`. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/shorts` directory are serialized via an +/// in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. The file is +/// written to an exclusively created per-run staging file (`part.parquet..tmp`), flushed, +/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists, +/// a live-preserving backup (`part.parquet..bak`) is created via hard link (or exclusive +/// copy fallback) so readers never observe a missing `part.parquet` before replacement by a +/// single atomic `rename`. On any error, the writer is dropped, any backup created by this run +/// is cleaned up (reporting cleanup failures via [`ParquetShortsError::RollbackFailed`]), and +/// only staging files owned by this run are unlinked. +pub fn write_shorts_dataset( + out_dir: P, + rows: I, + options: ShortsWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_shorts_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _| {}, + ) +} + +fn write_shorts_dataset_with_hooks( + out_dir: P, + rows: I, + options: ShortsWriteOptions, + lock_timeout: Duration, + mut on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(&Path, Option<&Path>), +{ + if options.row_group_rows == 0 { + return Err(ParquetShortsError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetShortsError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(ShortsWriteStats::default()); + }; + validate_row(first_item.borrow())?; + + let out_dir = out_dir.as_ref(); + let shorts_dir = out_dir.join("shorts"); + let schema = shorts_parquet_schema().map_err(|source| ParquetShortsError::Parquet { + path: shorts_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&shorts_dir).map_err(|source| ParquetShortsError::Io { + path: shorts_dir.clone(), + source, + })?; + + // Serialize writers targeting the same dataset directory across threads and processes. + // Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held, + // and only after all staging/publication/rollback work has finished. + let dataset_mu = dataset_mutex(&shorts_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire_with_timeout(&shorts_dir, lock_timeout)?; + + let run_id = next_run_id(); + let (tmp_path, tmp_file) = create_exclusive_tmp_file(&shorts_dir, &run_id)?; + // Declared before `file_writer` so Rust's reverse drop order closes the file handle + // before the guard unlinks the staging file on error or panic unwind, while `_file_lock` + // and `_in_process_guard` are still held. + let mut staging_guard = StagingFileGuard::new(tmp_path.clone()); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let mut file_writer = Some(ShortsFileWriter::from_file( + tmp_path, + shorts_dir.join("part.parquet"), + tmp_file, + &schema, + &props, + )?); + + let synced = { + let mut prev_key: Option<(i32, i32)> = None; + let writer = file_writer.as_mut().expect("writer initialized"); + + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + if let Some((prev_listing_id, prev_report_date)) = prev_key { + match (row.listing_id, row.report_date).cmp(&(prev_listing_id, prev_report_date)) { + Ordering::Equal => { + return Err(ParquetShortsError::DuplicateKey { + listing_id: row.listing_id, + report_date: row.report_date, + }); + } + Ordering::Less => { + return Err(ParquetShortsError::UnsortedInput { + prev_listing_id, + prev_report_date, + listing_id: row.listing_id, + report_date: row.report_date, + }); + } + Ordering::Greater => {} + } + } + validate_row(row)?; + prev_key = Some((row.listing_id, row.report_date)); + + writer.buf.push(row); + if writer.buf.len() == options.row_group_rows { + writer.flush_row_group(&mut scratch)?; + } + } + + let writer = file_writer.take().expect("writer still present"); + writer.finish_and_sync(&mut scratch)? + }; + + let backup_path = match fs::symlink_metadata(&synced.final_path) { + Ok(meta) if !meta.is_dir() => { + Some(create_backup_preserving_live(&synced.final_path, &run_id)?) + } + // Directory occupying final_path: leave it in place so the rename below fails cleanly. + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + return Err(ParquetShortsError::Io { + path: synced.final_path, + source, + }); + } + }; + + on_after_backup(&synced.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&synced.tmp_path, &synced.final_path) { + // `synced.final_path` was never moved during backup creation, so it remains intact; + // remove the backup created for this run. `staging_guard` unlinks our staging file on drop. + let backup_remove_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: synced.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let cause = ParquetShortsError::Io { + path: synced.final_path, + source, + }; + return match backup_remove_failure { + Some(failure) => Err(ParquetShortsError::RollbackFailed { + cause: Box::new(cause), + failures: vec![failure], + }), + None => Err(cause), + }; + } + + staging_guard.disarm(); + + if let Some(bak) = backup_path { + let _ = fs::remove_file(bak); + } + + Ok(ShortsWriteStats { + rows_written: synced.rows_written, + files_written: 1, + row_groups_written: synced.row_groups_written, + bytes_written: synced.bytes, + }) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + + use parquet::basic::ConvertedType; + use parquet::column::reader::ColumnReader; + use parquet::file::reader::{FileReader, SerializedFileReader}; + + use super::*; + use crate::shorts::{build_shorts, CeoShortReport, SHORTS_SOURCE_CEO}; + use crate::split::ymd_to_epoch_days; + + static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + + pub(super) struct TempDirGuard { + path: PathBuf, + } + + impl TempDirGuard { + pub(super) fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-pq-shorts-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + pub(super) fn path(&self) -> &Path { + &self.path + } + } + + impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + pub(super) fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") + } + + pub(super) fn make_row( + listing_id: i32, + report_date: i32, + shares_short: f64, + net_change: Option, + pct_float: Option, + ) -> ShortsParquetRow { + let known_at_micros = i64::from(report_date + 6) * 86_400_000_000 + 21 * 3_600_000_000; + ShortsParquetRow { + listing_id, + report_date, + known_at_micros, + shares_short, + net_change, + pct_float, + source: Cow::Borrowed(SHORTS_SOURCE_CEO), + } + } + + pub(super) fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let read_i32 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i32"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + let read_i64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + let read_f64_req = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read f64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + vals + }; + let read_f64_opt = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(num_rows); + let mut defs = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, Some(&mut defs), None, &mut vals) + .expect("read optional f64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + assert_eq!(defs.len(), num_rows); + let mut iter = vals.into_iter(); + defs.into_iter() + .map(|d| if d == 1 { Some(iter.next().unwrap()) } else { None }) + .collect() + }; + let read_str = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read utf8"); + assert_eq!(read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + vals.into_iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_owned()) + .collect() + }; + + let listing_id = read_i32(0); + let report_date = read_i32(1); + let known_at_micros = read_i64(2); + let shares_short = read_f64_req(3); + let net_change = read_f64_opt(4); + let pct_float = read_f64_opt(5); + let source = read_str(6); + + for i in 0..num_rows { + out.push(ShortsParquetRow { + listing_id: listing_id[i], + report_date: report_date[i], + known_at_micros: known_at_micros[i], + shares_short: shares_short[i], + net_change: net_change[i], + pct_float: pct_float[i], + source: Cow::Owned(source[i].clone()), + }); + } + } + out + } + + pub(super) fn assert_row_bitwise_eq(actual: &ShortsParquetRow, expected: &ShortsParquetRow) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.report_date, expected.report_date); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits()); + assert_eq!( + actual.net_change.map(f64::to_bits), + expected.net_change.map(f64::to_bits) + ); + assert_eq!( + actual.pct_float.map(f64::to_bits), + expected.pct_float.map(f64::to_bits) + ); + assert_eq!(actual.source, expected.source); + } + + pub(super) fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + for entry in fs::read_dir(dir).expect("read dir") { + let entry = entry.expect("dir entry"); + let name = entry.file_name().to_string_lossy().into_owned(); + assert!( + !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", + "unexpected transient file remaining: {}", + entry.path().display() + ); + } + } + + #[test] + fn schema_matches_contract_names_types_nullability_and_order() { + let schema = shorts_parquet_schema().expect("build schema"); + assert_eq!(schema.name(), "shorts"); + let fields = schema.get_fields(); + assert_eq!(fields.len(), 7); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 7] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "report_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "shares_short", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "net_change", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "pct_float", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + let f = &fields[idx]; + assert_eq!(f.name(), name, "field {idx} name"); + assert_eq!(f.get_physical_type(), phys, "field {name} physical type"); + assert_eq!( + f.get_basic_info().repetition(), + rep, + "field {name} repetition" + ); + assert_eq!( + f.get_basic_info().logical_type_ref().cloned(), + logical, + "field {name} logical type" + ); + assert_eq!( + f.get_basic_info().converted_type(), + converted, + "field {name} converted type" + ); + } + } + + #[test] + fn build_shorts_round_trip_bitwise_and_zstd_on_every_column_chunk() { + let tmp = TempDirGuard::new("round-trip"); + let built = build_shorts(vec![ + CeoShortReport { + key: 101_i32, + report_date: day(2024, 3, 15), + shares_short: 125_000.0, + net_change: Some(-4_500.0), + pct_float: Some(3.25), + }, + CeoShortReport { + key: 101_i32, + report_date: day(2024, 3, 31), + shares_short: 0.0, + net_change: None, + pct_float: None, + }, + CeoShortReport { + key: 202_i32, + report_date: day(2023, 12, 29), + shares_short: 88_500.5, + net_change: Some(1_250.25), + pct_float: None, + }, + ]) + .expect("build_shorts"); + + let rows: Vec = built.rows.iter().map(ShortsParquetRow::from).collect(); + let stats = + write_shorts_dataset(tmp.path(), &rows, ShortsWriteOptions::default()).unwrap(); + + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 1); + assert!(stats.bytes_written > 0); + + let path = tmp.path().join("shorts/part.parquet"); + assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written); + + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().num_rows(), 3); + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} expected ZSTD, got {:?}", + col.column_path(), + col.compression() + ); + } + } + + let actual = read_parquet_rows(&path); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("shorts")); + } + + #[test] + fn empty_input_creates_nothing_and_preserves_existing_part_parquet() { + let tmp = TempDirGuard::new("empty"); + let fresh = tmp.path().join("fresh"); + let stats = write_shorts_dataset( + &fresh, + std::iter::empty::(), + ShortsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats, ShortsWriteStats::default()); + assert!(!fresh.exists(), "empty input must not create out_dir"); + + let seeded = tmp.path().join("seeded"); + let seed_rows = vec![make_row(1, day(2024, 3, 15), 1_000.0, Some(50.0), Some(1.5))]; + write_shorts_dataset(&seeded, &seed_rows, ShortsWriteOptions::default()).unwrap(); + let part = seeded.join("shorts/part.parquet"); + let before = fs::read(&part).unwrap(); + + let empty_stats = write_shorts_dataset( + &seeded, + std::iter::empty::(), + ShortsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_stats, ShortsWriteStats::default()); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&seeded.join("shorts")); + } + + #[test] + fn determinism_identical_rows_produce_byte_identical_files() { + let tmp = TempDirGuard::new("determinism"); + let rows = vec![ + make_row(1, day(2024, 1, 15), 10_000.0, Some(250.0), Some(0.75)), + make_row(1, day(2024, 1, 31), 9_500.0, Some(-500.0), None), + make_row(2, day(2024, 2, 15), 0.0, None, Some(0.0)), + ]; + + let out_a = tmp.path().join("a"); + let out_b = tmp.path().join("b"); + let opts = ShortsWriteOptions { + row_group_rows: 2, + ..ShortsWriteOptions::default() + }; + write_shorts_dataset(&out_a, &rows, opts).unwrap(); + write_shorts_dataset(&out_b, &rows, opts).unwrap(); + + let bytes_a = fs::read(out_a.join("shorts/part.parquet")).unwrap(); + let bytes_b = fs::read(out_b.join("shorts/part.parquet")).unwrap(); + assert_eq!(bytes_a, bytes_b); + } +} + +#[cfg(test)] +#[path = "parquet_shorts_tests.rs"] +mod edge_case_tests; diff --git a/tools/curate-etl/src/parquet_shorts_tests.rs b/tools/curate-etl/src/parquet_shorts_tests.rs new file mode 100644 index 00000000..ea38a936 --- /dev/null +++ b/tools/curate-etl/src/parquet_shorts_tests.rs @@ -0,0 +1,571 @@ +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use parquet::basic::Encoding; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::tests::{ + assert_no_transient_files, assert_row_bitwise_eq, day, make_row, read_parquet_rows, + TempDirGuard, +}; +use super::{ + write_shorts_dataset, write_shorts_dataset_with_hooks, ParquetShortsError, ShortsParquetRow, + ShortsWriteOptions, +}; +use crate::shorts::SHORTS_SOURCE_CEO; + +fn seed_existing(out_dir: &std::path::Path) -> (std::path::PathBuf, Vec) { + let seed = vec![ + make_row(1, day(2024, 1, 15), 5_000.0, Some(100.0), Some(1.25)), + make_row(2, day(2024, 1, 31), 8_000.0, None, Some(2.5)), + ]; + write_shorts_dataset(out_dir, &seed, ShortsWriteOptions::default()).unwrap(); + let part = out_dir.join("shorts/part.parquet"); + let before = fs::read(&part).unwrap(); + (part, before) +} + +#[test] +fn single_row_and_row_group_boundary_counts_and_optional_patterns() { + let tmp = TempDirGuard::new("rg-boundaries"); + + // 1 row + let out_1 = tmp.path().join("one"); + let single = vec![make_row(7, day(2024, 2, 15), 42.0, None, None)]; + let stats_1 = write_shorts_dataset(&out_1, &single, ShortsWriteOptions::default()).unwrap(); + assert_eq!(stats_1.rows_written, 1); + assert_eq!(stats_1.files_written, 1); + assert_eq!(stats_1.row_groups_written, 1); + let actual_1 = read_parquet_rows(&out_1.join("shorts/part.parquet")); + assert_eq!(actual_1.len(), 1); + assert_row_bitwise_eq(&actual_1[0], &single[0]); + + // Exactly row_group_rows (4 rows, row_group_rows = 4 => 1 row group) + let base = day(2024, 1, 1); + let rows_exact: Vec = (0..4_i32) + .map(|i| make_row(1, base + i * 15, f64::from(i) * 100.0, None, None)) + .collect(); + let out_exact = tmp.path().join("exact"); + let opts = ShortsWriteOptions { + row_group_rows: 4, + ..ShortsWriteOptions::default() + }; + let stats_exact = write_shorts_dataset(&out_exact, &rows_exact, opts).unwrap(); + assert_eq!(stats_exact.rows_written, 4); + assert_eq!(stats_exact.row_groups_written, 1); + let reader_exact = + SerializedFileReader::new(File::open(out_exact.join("shorts/part.parquet")).unwrap()) + .unwrap(); + assert_eq!(reader_exact.metadata().num_row_groups(), 1); + assert_eq!(reader_exact.metadata().row_group(0).num_rows(), 4); + + // row_group_rows + 1 (5 rows, row_group_rows = 4 => 2 row groups: [4, 1]) + // Exercises all-None, all-Some, and mixed optional columns across row groups. + let rows_plus_one = vec![ + make_row(1, base, 10.0, None, None), + make_row(1, base + 15, 20.0, Some(10.0), Some(0.5)), + make_row(1, base + 30, 30.0, Some(-5.0), None), + make_row(1, base + 45, 40.0, None, Some(1.25)), + make_row(2, base, 50.0, Some(50.0), Some(2.0)), + ]; + let out_plus = tmp.path().join("plus-one"); + let stats_plus = write_shorts_dataset(&out_plus, &rows_plus_one, opts).unwrap(); + assert_eq!(stats_plus.rows_written, 5); + assert_eq!(stats_plus.row_groups_written, 2); + let p_plus = out_plus.join("shorts/part.parquet"); + let reader_plus = SerializedFileReader::new(File::open(&p_plus).unwrap()).unwrap(); + let rg_sizes: Vec = (0..reader_plus.metadata().num_row_groups()) + .map(|i| reader_plus.metadata().row_group(i).num_rows()) + .collect(); + assert_eq!(rg_sizes, vec![4, 1]); + let actual_plus = read_parquet_rows(&p_plus); + assert_eq!(actual_plus.len(), rows_plus_one.len()); + for (a, e) in actual_plus.iter().zip(&rows_plus_one) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&out_plus.join("shorts")); +} + +#[test] +fn source_column_uses_dictionary_encoding_and_zstd_levels_work() { + let tmp = TempDirGuard::new("dict-zstd"); + let base = day(2024, 1, 15); + let rows: Vec = (0..64_i32) + .map(|i| make_row(1 + i / 8, base + (i % 8) * 15, 1_000.0 + f64::from(i), Some(5.0), Some(1.0))) + .collect(); + + let out_ok = tmp.path().join("lvl-3"); + write_shorts_dataset(&out_ok, &rows, ShortsWriteOptions::default()).unwrap(); + let p = out_ok.join("shorts/part.parquet"); + let reader = SerializedFileReader::new(File::open(&p).unwrap()).unwrap(); + let source_col = reader.metadata().row_group(0).column(6); + assert!( + source_col.encodings().any(|e| { + matches!( + e, + Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY + ) + }), + "expected dictionary encoding on source column, got {:?}", + source_col.encodings().collect::>() + ); + + // Invalid Zstd level and invalid row_group_rows + let out_bad = tmp.path().join("bad-opts"); + assert!(matches!( + write_shorts_dataset( + &out_bad, + &rows, + ShortsWriteOptions { + row_group_rows: 0, + ..ShortsWriteOptions::default() + } + ), + Err(ParquetShortsError::InvalidRowGroupRows) + )); + assert!(matches!( + write_shorts_dataset( + &out_bad, + &rows, + ShortsWriteOptions { + zstd_level: 23, + ..ShortsWriteOptions::default() + } + ), + Err(ParquetShortsError::InvalidZstdLevel { level: 23 }) + )); + assert!(matches!( + write_shorts_dataset( + &out_bad, + &rows, + ShortsWriteOptions { + zstd_level: 99, + ..ShortsWriteOptions::default() + } + ), + Err(ParquetShortsError::InvalidZstdLevel { level: 99 }) + )); + assert!(!out_bad.exists(), "invalid options must not create out_dir"); +} + +#[test] +fn overwrite_replaces_existing_part_parquet_and_leaves_no_transients() { + let tmp = TempDirGuard::new("overwrite"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![ + make_row(10, day(2025, 4, 15), 99_999.0, Some(-123.5), Some(4.5)), + make_row(11, day(2025, 4, 30), 0.0, None, None), + ]; + let stats = write_shorts_dataset(tmp.path(), &replacement, ShortsWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 2); + assert_eq!(stats.files_written, 1); + + let after = fs::read(&part).unwrap(); + assert_ne!(after, before); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), replacement.len()); + for (a, e) in actual.iter().zip(&replacement) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("shorts")); +} + +#[test] +fn invalid_inputs_return_typed_errors_and_preserve_existing_part_parquet() { + let tmp = TempDirGuard::new("invalid-inputs"); + let (part, before) = seed_existing(tmp.path()); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 3, 31); + + // 1. Unsorted (listing_id goes backwards) + let unsorted_listing = vec![ + make_row(2, d1, 100.0, None, None), + make_row(1, d2, 200.0, None, None), + ]; + let err = write_shorts_dataset(tmp.path(), &unsorted_listing, ShortsWriteOptions::default()) + .unwrap_err(); + assert!(matches!( + err, + ParquetShortsError::UnsortedInput { + prev_listing_id: 2, + prev_report_date, + listing_id: 1, + report_date, + } if prev_report_date == d1 && report_date == d2 + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + + // 2. Unsorted (report_date goes backwards for same listing) + let unsorted_date = vec![ + make_row(1, d2, 100.0, None, None), + make_row(1, d1, 200.0, None, None), + ]; + let err = + write_shorts_dataset(tmp.path(), &unsorted_date, ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!( + err, + ParquetShortsError::UnsortedInput { + prev_listing_id: 1, + prev_report_date, + listing_id: 1, + report_date, + } if prev_report_date == d2 && report_date == d1 + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + + // 3. Duplicate (listing_id, report_date) + let duplicate = vec![ + make_row(1, d1, 100.0, None, None), + make_row(1, d1, 100.0, None, None), + ]; + let err = + write_shorts_dataset(tmp.path(), &duplicate, ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!( + err, + ParquetShortsError::DuplicateKey { + listing_id: 1, + report_date, + } if report_date == d1 + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + + // 4. Invalid shares_short: NaN, +inf, -inf, negative + for bad_shares in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.0001] { + let rows = vec![make_row(1, d1, bad_shares, None, None)]; + let err = + write_shorts_dataset(tmp.path(), &rows, ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::InvalidSharesShort { + listing_id: 1, + report_date, + .. + } if report_date == d1 + ), + "expected InvalidSharesShort for {bad_shares}, got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + } + + // 5. Invalid net_change: NaN, +inf, -inf + for bad_net in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let rows = vec![make_row(1, d1, 100.0, Some(bad_net), None)]; + let err = + write_shorts_dataset(tmp.path(), &rows, ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::InvalidNetChange { + listing_id: 1, + report_date, + .. + } if report_date == d1 + ), + "expected InvalidNetChange for {bad_net}, got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + } + + // 6. Invalid pct_float: NaN, +inf, -inf + for bad_pct in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let rows = vec![make_row(1, d1, 100.0, None, Some(bad_pct))]; + let err = + write_shorts_dataset(tmp.path(), &rows, ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::InvalidPctFloat { + listing_id: 1, + report_date, + .. + } if report_date == d1 + ), + "expected InvalidPctFloat for {bad_pct}, got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + } + + // 7. known_at not strictly after report_date 00:00 UTC (equal, before, and extreme report_date = i32::MAX) + let midnight = i64::from(d1) * 86_400_000_000; + for (report_date, known_at_micros) in [ + (d1, midnight), + (d1, midnight - 1), + (i32::MAX, i64::MAX), + ] { + let mut r = make_row(1, d1, 100.0, None, None); + r.report_date = report_date; + r.known_at_micros = known_at_micros; + let err = write_shorts_dataset(tmp.path(), &[r], ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::KnownAtNotAfterReportDate { + listing_id: 1, + report_date: rd, + known_at_micros: ka, + } if rd == report_date && ka == known_at_micros + ), + "expected KnownAtNotAfterReportDate for ({report_date}, {known_at_micros}), got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + } + + // 8. Empty and whitespace-only source + for bad_source in ["", " ", "\t\n"] { + let mut r = make_row(1, d1, 100.0, None, None); + r.source = Cow::Owned(bad_source.to_string()); + let err = write_shorts_dataset(tmp.path(), &[r], ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::EmptySource { + listing_id: 1, + report_date, + } if report_date == d1 + ), + "expected EmptySource for {bad_source:?}, got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + } +} + +#[test] +fn mid_stream_failure_after_flushed_row_groups_preserves_existing_part_parquet() { + let tmp = TempDirGuard::new("mid-stream-fail"); + let (part, before) = seed_existing(tmp.path()); + let base = day(2024, 1, 1); + + let mut rows = vec![ + make_row(1, base, 100.0, Some(1.0), Some(0.1)), + make_row(1, base + 15, 200.0, Some(2.0), Some(0.2)), + make_row(1, base + 30, 300.0, Some(3.0), Some(0.3)), + make_row(1, base + 45, 400.0, Some(4.0), Some(0.4)), + ]; + // 5th row fails after 2 row groups of size 2 have already been flushed to staging. + rows.push(make_row(1, base + 60, -1.0, None, None)); + + let err = write_shorts_dataset( + tmp.path(), + &rows, + ShortsWriteOptions { + row_group_rows: 2, + ..ShortsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetShortsError::InvalidSharesShort { .. })); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); +} + +#[test] +fn out_dir_or_shorts_occupied_by_regular_file_returns_io_error() { + let tmp = TempDirGuard::new("io-blocker"); + let rows = vec![make_row(1, day(2024, 3, 15), 100.0, None, None)]; + + let file_as_out = tmp.path().join("not-a-dir"); + fs::write(&file_as_out, b"sentinel").unwrap(); + let err = write_shorts_dataset(&file_as_out, &rows, ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetShortsError::Io { .. })); + assert!(StdError::source(&err).is_some()); + assert_eq!(fs::read(&file_as_out).unwrap(), b"sentinel"); + + let out_with_file_shorts = tmp.path().join("shorts-is-file"); + fs::create_dir_all(&out_with_file_shorts).unwrap(); + let shorts_file = out_with_file_shorts.join("shorts"); + fs::write(&shorts_file, b"file-not-dir").unwrap(); + let err2 = + write_shorts_dataset(&out_with_file_shorts, &rows, ShortsWriteOptions::default()) + .unwrap_err(); + assert!(matches!(err2, ParquetShortsError::Io { .. })); + assert_eq!(fs::read(&shorts_file).unwrap(), b"file-not-dir"); +} + +#[test] +fn stale_lock_times_out_leaving_lock_and_existing_part_intact() { + let tmp = TempDirGuard::new("stale-lock"); + let (part, before) = seed_existing(tmp.path()); + let lock_path = tmp.path().join("shorts/.write.lock"); + fs::write(&lock_path, b"999999\n").unwrap(); + + let rows = vec![make_row(9, day(2024, 6, 15), 500.0, None, None)]; + let err = write_shorts_dataset_with_hooks( + tmp.path(), + &rows, + ShortsWriteOptions::default(), + Duration::from_millis(30), + |_, _| {}, + ) + .unwrap_err(); + + assert!( + matches!(err, ParquetShortsError::LockTimeout { ref path, .. } if path == &lock_path), + "expected LockTimeout, got {err:?}" + ); + assert!(lock_path.exists(), "stale lock must not be deleted by timed-out writer"); + assert_eq!(fs::read(&part).unwrap(), before); +} + +#[test] +fn live_part_parquet_stays_readable_between_backup_and_rename() { + let tmp = TempDirGuard::new("live-readable"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![make_row(5, day(2024, 9, 15), 777.0, Some(7.0), Some(0.7))]; + let observed_live = Arc::new(Mutex::new(false)); + let observed_clone = Arc::clone(&observed_live); + + write_shorts_dataset_with_hooks( + tmp.path(), + &replacement, + ShortsWriteOptions::default(), + Duration::from_secs(5), + move |final_path, backup_path| { + assert!(backup_path.is_some(), "expected backup path for existing file"); + assert_eq!(fs::read(final_path).unwrap(), before); + assert_eq!(fs::read(backup_path.unwrap()).unwrap(), before); + *observed_clone.lock().unwrap() = true; + }, + ) + .unwrap(); + + assert!(*observed_live.lock().unwrap()); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), 1); + assert_row_bitwise_eq(&actual[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("shorts")); +} + +#[test] +fn rename_failure_over_directory_blocker_cleans_up_staging_and_unowned_tmp_is_preserved() { + let tmp = TempDirGuard::new("rename-blocker"); + let shorts_dir = tmp.path().join("shorts"); + let blocking_dir = shorts_dir.join("part.parquet"); + fs::create_dir_all(&blocking_dir).unwrap(); + + let unowned_tmp = shorts_dir.join("part.parquet.unowned-other-run.tmp"); + fs::write(&unowned_tmp, b"keep-me").unwrap(); + + let rows = vec![make_row(1, day(2024, 3, 15), 100.0, None, None)]; + let err = write_shorts_dataset(tmp.path(), &rows, ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetShortsError::Io { .. }), "got {err:?}"); + assert!(blocking_dir.is_dir(), "directory blocker must remain intact"); + assert_eq!( + fs::read(&unowned_tmp).unwrap(), + b"keep-me", + "unowned .tmp file must be preserved" + ); + + // Only the unowned .tmp file and the blocking directory may remain. + let mut entries: Vec = fs::read_dir(&shorts_dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + entries.sort(); + assert_eq!( + entries, + vec![ + "part.parquet".to_string(), + "part.parquet.unowned-other-run.tmp".to_string(), + ] + ); +} + +#[test] +fn concurrent_in_process_writers_serialize_cleanly() { + let tmp = TempDirGuard::new("concurrent-unit"); + let out = Arc::new(tmp.path().to_path_buf()); + let events = Arc::new(Mutex::new(Vec::<&'static str>::new())); + + let out_1 = Arc::clone(&out); + let events_1 = Arc::clone(&events); + let handle_1 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + if i == 1 { + events_1.lock().unwrap().push("t1_mid"); + thread::sleep(Duration::from_millis(30)); + } + make_row(1, day(2024, 1, 15) + i * 16, 100.0 + f64::from(i), None, None) + }); + write_shorts_dataset(out_1.as_path(), iter, ShortsWriteOptions::default()) + }); + + thread::sleep(Duration::from_millis(5)); + let out_2 = Arc::clone(&out); + let events_2 = Arc::clone(&events); + let handle_2 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + if i == 1 { + events_2.lock().unwrap().push("t2_mid"); + } + make_row(2, day(2024, 2, 15) + i * 14, 500.0 + f64::from(i), Some(10.0), None) + }); + write_shorts_dataset(out_2.as_path(), iter, ShortsWriteOptions::default()) + }); + + let s1 = handle_1.join().unwrap().unwrap(); + let s2 = handle_2.join().unwrap().unwrap(); + assert_eq!(s1.rows_written, 2); + assert_eq!(s2.rows_written, 2); + + let got = read_parquet_rows(&tmp.path().join("shorts/part.parquet")); + assert_eq!(got.len(), 2); + assert!( + got.iter().all(|r| r.listing_id == 1) || got.iter().all(|r| r.listing_id == 2), + "output must come entirely from one writer generation" + ); + assert!(got.iter().all(|r| r.source == SHORTS_SOURCE_CEO)); + assert_no_transient_files(&tmp.path().join("shorts")); +} + +#[test] +fn panicking_iterator_cleans_up_staging_file_and_releases_lock() { + let tmp = TempDirGuard::new("panic-unwind"); + let (part, before) = seed_existing(tmp.path()); + + let out = tmp.path().to_path_buf(); + let opts = ShortsWriteOptions { + row_group_rows: 2, + ..ShortsWriteOptions::default() + }; + let result = std::panic::catch_unwind(move || { + let base = day(2024, 3, 15); + let iter = (0..5_i32).map(move |i| { + if i == 3 { + panic!("simulated iterator panic after row-group flush"); + } + make_row(10, base + i * 15, 1_000.0 + f64::from(i), Some(1.0), None) + }); + let _ = write_shorts_dataset(&out, iter, opts); + }); + assert!(result.is_err(), "iterator must have panicked"); + + // Pre-existing live file stays byte-identical and both staging `.tmp` and `.write.lock` + // are removed during unwind. + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + + // Subsequent writer succeeds immediately without hanging on a stale lock. + let replacement = vec![make_row(99, day(2024, 6, 15), 250.0, None, Some(0.5))]; + let stats = write_shorts_dataset(tmp.path(), &replacement, ShortsWriteOptions::default()) + .unwrap(); + assert_eq!(stats.rows_written, 1); + let got = read_parquet_rows(&part); + assert_eq!(got.len(), 1); + assert_row_bitwise_eq(&got[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("shorts")); +} diff --git a/tools/curate-etl/src/session_close.rs b/tools/curate-etl/src/session_close.rs new file mode 100644 index 00000000..49630836 --- /dev/null +++ b/tools/curate-etl/src/session_close.rs @@ -0,0 +1,310 @@ +//! Pure `std`-only North American Eastern Time (`16:00:00 ET`) session-close timestamp converter +//! covering `1976-01-01..=2030-12-31`. +//! +//! # DST Schedule (`America/New_York` == `America/Toronto` over `1976..=2030`) +//! Across the entire `1976..=2030` window, `America/New_York` and `America/Toronto` observed +//! identical Daylight Saving Time rules across three eras: +//! - **`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 (Energy Policy Act of +//! 2005 / matching Canadian provincial adoption). +//! +//! During EDT (`UTC-4`), `16:00:00 ET` is `20:00:00 UTC`. During EST (`UTC-5`), `16:00:00 ET` is +//! `21:00:00 UTC`. Because `16:00` is strictly after the `02:00` wall-clock transition, the spring +//! transition Sunday is already EDT (`20:00 UTC`) and the fall transition Sunday is already EST +//! (`21:00 UTC`). +//! +//! # Conservative Early-Close & Lower-Bound Policy +//! - **Early-close half days** (e.g., `13:00 ET` on Christmas Eve or the day after US +//! Thanksgiving) still map to `16:00:00 ET`, which is strictly later than the actual close and +//! therefore never introduces look-ahead bias for daily bar `known_at`. +//! - **Why the lower bound is `1976-01-01`**: in `1974–1975` the US Emergency Daylight Saving Time +//! Energy Conservation Act moved US clocks onto winter DST while Ontario/Toronto stayed on +//! standard rules, so `America/New_York` and `America/Toronto` diverged. Earlier dates return +//! [`SessionCloseError::DateOutOfRange`] rather than guessing exchange-specific historical rules. + +use std::error::Error; +use std::fmt; +use std::sync::OnceLock; + +use crate::shorts::epoch_days_to_ymd; +use crate::split::ymd_to_epoch_days; + +/// First Gregorian year covered by [`et_session_close_utc_micros`] (`1976-01-01`). +pub const SESSION_CLOSE_MIN_SUPPORTED_YEAR: i32 = 1976; + +/// Last Gregorian year covered by [`et_session_close_utc_micros`] (`2030-12-31`). +pub const SESSION_CLOSE_MAX_SUPPORTED_YEAR: i32 = 2030; + +/// Epoch day for `1976-01-01` (inclusive lower bound of [`et_session_close_utc_micros`]). +pub const SESSION_CLOSE_MIN_SUPPORTED_DATE: i32 = 2_191; + +/// Epoch day for `2030-12-31` (inclusive upper bound of [`et_session_close_utc_micros`]). +pub const SESSION_CLOSE_MAX_SUPPORTED_DATE: i32 = 22_279; + +const SUPPORTED_YEAR_COUNT: usize = + (SESSION_CLOSE_MAX_SUPPORTED_YEAR - SESSION_CLOSE_MIN_SUPPORTED_YEAR + 1) as usize; + +/// Typed error returned by [`et_session_close_utc_micros`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SessionCloseError { + /// The requested epoch day fell outside `[SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]`. + DateOutOfRange { + epoch_day: i32, + min_supported: i32, + max_supported: i32, + }, +} + +impl fmt::Display for SessionCloseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::DateOutOfRange { + epoch_day, + min_supported, + max_supported, + } => write!( + f, + "epoch day {epoch_day} is outside supported session-close range [{min_supported}, {max_supported}] ({SESSION_CLOSE_MIN_SUPPORTED_YEAR}-01-01..={SESSION_CLOSE_MAX_SUPPORTED_YEAR}-12-31)" + ), + } + } +} + +impl Error for SessionCloseError {} + +/// ISO-8601 weekday for an epoch day: `1 = Monday`, ..., `6 = Saturday`, `7 = Sunday`. +#[inline] +fn iso_weekday(epoch_day: i32) -> u8 { + // 1970-01-01 (epoch_day == 0) was Thursday (ISO 4). + ((i64::from(epoch_day) + 3).rem_euclid(7) + 1) as u8 +} + +/// Returns the epoch day of the `nth` Sunday (`1`-indexed) in `(year, month)`. +fn nth_sunday_of_month(year: i32, month: u32, nth: u32) -> i32 { + let first = ymd_to_epoch_days(year, month, 1).expect("valid first of month"); + let first_wd = iso_weekday(first); + let delta = (7 - i32::from(first_wd)).rem_euclid(7); + first + delta + (nth as i32 - 1) * 7 +} + +/// Returns the epoch day of the last Sunday in `(year, month)`. +fn last_sunday_of_month(year: i32, month: u32) -> i32 { + let (next_year, next_month) = if month == 12 { + (year + 1, 1) + } else { + (year, month + 1) + }; + let last = ymd_to_epoch_days(next_year, next_month, 1).expect("valid first of next month") - 1; + let last_wd = iso_weekday(last); + last - (i32::from(last_wd) % 7) +} + +fn build_dst_bounds() -> [(i32, i32); SUPPORTED_YEAR_COUNT] { + let mut table = [(0i32, 0i32); SUPPORTED_YEAR_COUNT]; + for year in SESSION_CLOSE_MIN_SUPPORTED_YEAR..=SESSION_CLOSE_MAX_SUPPORTED_YEAR { + let (dst_start, dst_end) = match year { + 1976..=1986 => ( + last_sunday_of_month(year, 4), + last_sunday_of_month(year, 10), + ), + 1987..=2006 => ( + nth_sunday_of_month(year, 4, 1), + last_sunday_of_month(year, 10), + ), + 2007..=2030 => ( + nth_sunday_of_month(year, 3, 2), + nth_sunday_of_month(year, 11, 1), + ), + _ => unreachable!("year is bounded by supported range"), + }; + table[(year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize] = (dst_start, dst_end); + } + table +} + +#[inline] +fn dst_bounds() -> &'static [(i32, i32); SUPPORTED_YEAR_COUNT] { + static TABLE: OnceLock<[(i32, i32); SUPPORTED_YEAR_COUNT]> = OnceLock::new(); + TABLE.get_or_init(build_dst_bounds) +} + +/// Converts `epoch_day` at `16:00:00` Eastern wall-clock (`America/New_York` / `America/Toronto`) +/// to UTC microseconds since the Unix epoch. +/// +/// Covers `1976-01-01..=2030-12-31` across all three North American DST eras (`1976–1986`, +/// `1987–2006`, `2007–2030`). Returns [`SessionCloseError::DateOutOfRange`] for any date outside +/// `[SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]`. +#[inline] +pub fn et_session_close_utc_micros(epoch_day: i32) -> Result { + if !(SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE).contains(&epoch_day) { + return Err(SessionCloseError::DateOutOfRange { + epoch_day, + min_supported: SESSION_CLOSE_MIN_SUPPORTED_DATE, + max_supported: SESSION_CLOSE_MAX_SUPPORTED_DATE, + }); + } + + let (year, _, _) = epoch_days_to_ymd(epoch_day); + let (dst_start, dst_end) = dst_bounds()[(year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize]; + let is_edt = epoch_day >= dst_start && epoch_day < dst_end; + let utc_hour_secs: i64 = if is_edt { 20 * 3_600 } else { 21 * 3_600 }; + Ok((i64::from(epoch_day) * 86_400 + utc_hour_secs) * 1_000_000) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::shorts::{et_to_utc_micros, MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE}; + + fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") + } + + fn expected_utc_micros(epoch_day: i32, utc_hour: i64) -> i64 { + (i64::from(epoch_day) * 86_400 + utc_hour * 3_600) * 1_000_000 + } + + #[test] + fn supported_date_constants_match_ymd_to_epoch_days() { + assert_eq!(SESSION_CLOSE_MIN_SUPPORTED_DATE, day(1976, 1, 1)); + assert_eq!(SESSION_CLOSE_MAX_SUPPORTED_DATE, day(2030, 12, 31)); + assert_eq!(SUPPORTED_YEAR_COUNT, 55); + } + + #[test] + fn known_vectors_cover_all_three_dst_eras_and_transitions() { + let cases = [ + // Era 1 (1976..=1986): last Sunday of April -> last Sunday of October + (1976, 4, 24, 21), // Saturday before spring-forward (EST) + (1976, 4, 25, 20), // Last Sunday of April (EDT) + (1976, 10, 30, 20), // Saturday before fall-back (EDT) + (1976, 10, 31, 21), // Last Sunday of October (EST) + (1980, 1, 15, 21), // Era 1 mid-winter (EST) + (1980, 7, 15, 20), // Era 1 mid-summer (EDT) + (1986, 4, 26, 21), // Saturday before spring-forward (EST) + (1986, 4, 27, 20), // Last Sunday of April (EDT) + // Era 2 (1987..=2006): first Sunday of April -> last Sunday of October + (1987, 4, 4, 21), // Saturday before spring-forward (EST) + (1987, 4, 5, 20), // First Sunday of April (EDT) + (1987, 10, 24, 20), // Saturday before fall-back (EDT) + (1987, 10, 25, 21), // Last Sunday of October (EST) + (1999, 1, 15, 21), // Era 2 mid-winter (EST) + (1999, 7, 15, 20), // Era 2 mid-summer (EDT) + (2006, 4, 1, 21), // Saturday before spring-forward (EST) + (2006, 4, 2, 20), // First Sunday of April (EDT) + (2006, 10, 28, 20), // Saturday before fall-back (EDT) + (2006, 10, 29, 21), // Last Sunday of October (EST) + // Era 3 (2007..=2030): second Sunday of March -> first Sunday of November + (2007, 3, 10, 21), // Saturday before spring-forward (EST) + (2007, 3, 11, 20), // Second Sunday of March (EDT) + (2007, 11, 3, 20), // Saturday before fall-back (EDT) + (2007, 11, 4, 21), // First Sunday of November (EST) + (2024, 1, 15, 21), // Era 3 mid-winter (EST) + (2024, 7, 15, 20), // Era 3 mid-summer (EDT) + ]; + + for (y, m, d, expected_hour) in cases { + let epoch_day = day(y, m, d); + let actual = et_session_close_utc_micros(epoch_day).expect("in-range date"); + let expected = expected_utc_micros(epoch_day, expected_hour); + assert_eq!( + actual, expected, + "micros mismatch on {y:04}-{m:02}-{d:02} (expected {expected_hour}:00 UTC)" + ); + let hour_of_day = (actual / 1_000_000 - i64::from(epoch_day) * 86_400) / 3_600; + assert_eq!( + hour_of_day, expected_hour, + "UTC hour mismatch on {y:04}-{m:02}-{d:02}" + ); + } + } + + #[test] + fn bit_exact_parity_with_shorts_et_to_utc_micros_for_2008_to_2030() { + for d in MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE { + let expected = et_to_utc_micros(d, 16, 0, 0).expect("shorts 2008..=2030 date"); + let actual = et_session_close_utc_micros(d).expect("session_close 2008..=2030 date"); + assert_eq!( + actual, expected, + "parity mismatch against shorts::et_to_utc_micros on epoch_day={d}" + ); + } + } + + #[test] + fn full_window_sweep_has_only_20_or_21_utc_and_two_sunday_flips_per_year() { + let mut spring_flips_by_year = [0u32; SUPPORTED_YEAR_COUNT]; + let mut fall_flips_by_year = [0u32; SUPPORTED_YEAR_COUNT]; + + let mut prev_hour: Option = None; + for d in SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE { + let micros = et_session_close_utc_micros(d).expect("in-range date"); + let offset_micros = micros - i64::from(d) * 86_400 * 1_000_000; + let utc_hour = match offset_micros { + 72_000_000_000 => 20, // 20 * 3600 * 1e6 + 75_600_000_000 => 21, // 21 * 3600 * 1e6 + other => panic!( + "unexpected UTC offset micros {other} on epoch_day={d} (expected 20h or 21h)" + ), + }; + + if let Some(prev) = prev_hour { + if prev != utc_hour { + assert_eq!( + iso_weekday(d), + 7, + "DST flip on epoch_day={d} must occur on a Sunday" + ); + let (year, _, _) = epoch_days_to_ymd(d); + let idx = (year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize; + match (prev, utc_hour) { + (21, 20) => spring_flips_by_year[idx] += 1, + (20, 21) => fall_flips_by_year[idx] += 1, + _ => unreachable!(), + } + } + } + prev_hour = Some(utc_hour); + } + + for year in SESSION_CLOSE_MIN_SUPPORTED_YEAR..=SESSION_CLOSE_MAX_SUPPORTED_YEAR { + let idx = (year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize; + assert_eq!( + spring_flips_by_year[idx], 1, + "year {year} must have exactly one EST->EDT flip" + ); + assert_eq!( + fall_flips_by_year[idx], 1, + "year {year} must have exactly one EDT->EST flip" + ); + } + } + + #[test] + fn out_of_range_dates_return_typed_error_without_panicking() { + let bad_days = [ + day(1975, 12, 31), + day(2031, 1, 1), + i32::MIN, + i32::MAX, + ]; + for bad_day in bad_days { + let err = et_session_close_utc_micros(bad_day).unwrap_err(); + assert_eq!( + err, + SessionCloseError::DateOutOfRange { + epoch_day: bad_day, + min_supported: SESSION_CLOSE_MIN_SUPPORTED_DATE, + max_supported: SESSION_CLOSE_MAX_SUPPORTED_DATE, + } + ); + assert!(err.source().is_none()); + let msg = err.to_string(); + assert!( + msg.contains(&bad_day.to_string()) && msg.contains("1976-01-01..=2030-12-31"), + "unexpected Display message: {msg}" + ); + } + } +} diff --git a/tools/curate-etl/tests/bson_eod_prices_qa_contract.rs b/tools/curate-etl/tests/bson_eod_prices_qa_contract.rs new file mode 100644 index 00000000..e8b8c63f --- /dev/null +++ b/tools/curate-etl/tests/bson_eod_prices_qa_contract.rs @@ -0,0 +1,477 @@ +//! QA contract tests for the public `eodPrices` raw BSON decoder (T-97 / M1.2o). +//! +//! Covers gaps left by the in-crate `bson_eod_prices_tests.rs`, using only the public API: +//! - zero-copy: decoded `eod_search_code` borrows from the input buffer; +//! - field-order independence, case-sensitive keys, nested look-alike keys ignored; +//! - `DateTime` day boundaries (last ms of a day, -1 ms before epoch); +//! - error callbacks receive the exact byte offset of the rejected document; +//! - empty buffer, truncated tail after good docs, `i32::MAX` declared length, trailing bytes; +//! - seeded byte-mutation fuzz: never panics and `decoded + rejected == docs_in` always holds, +//! and every decoded bar is identical to the single-document decode of the same bytes; +//! - `bench-bson-eod-prices` binary: identical checksum across two runs, invalid args exit 1. + +use std::process::{Command, Output}; + +use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; +use bson::DateTime; +use curate_etl::{ + decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs, + ymd_to_epoch_days, BsonEodPriceError, RawEodDailyBar, +}; + +const MILLIS_PER_DAY: i64 = 86_400_000; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).unwrap() +} + +fn valid_doc(code: &str, date: &str, close: f64, volume: i64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("_id"), "ignored"); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("open"), close - 1.0); + doc.append(cstr!("high"), close + 1.0); + doc.append(cstr!("low"), close - 2.0); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc +} + +#[test] +fn decoded_search_code_borrows_from_input_buffer_without_copying() { + let doc = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000); + let bytes = doc.as_bytes(); + let bar = decode_eod_price_bytes(bytes).unwrap(); + + let start = bytes.as_ptr() as usize; + let end = start + bytes.len(); + let code_ptr = bar.eod_search_code.as_ptr() as usize; + assert!( + code_ptr >= start && code_ptr + bar.eod_search_code.len() <= end, + "eod_search_code must point into the input bytes" + ); + assert_eq!(bar.eod_search_code, "RY.TO"); +} + +#[test] +fn field_order_does_not_change_the_decoded_bar() { + let mut reversed = RawDocumentBuf::new(); + reversed.append(cstr!("volume"), 1_000_i64); + reversed.append(cstr!("close"), 130.0_f64); + reversed.append(cstr!("low"), 128.0_f64); + reversed.append(cstr!("high"), 131.0_f64); + reversed.append(cstr!("open"), 129.0_f64); + reversed.append(cstr!("date"), "2024-06-07"); + reversed.append(cstr!("eodSearchCode"), "RY.TO"); + + let forward = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000); + assert_eq!( + decode_eod_price_doc(&reversed).unwrap(), + decode_eod_price_doc(&forward).unwrap() + ); +} + +#[test] +fn keys_are_case_sensitive_and_nested_lookalikes_are_ignored() { + // `Volume` (capitalised) and a nested `volume` must not satisfy the top-level field. + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("volume"), 5_i64); + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "RY.TO"); + doc.append(cstr!("date"), "2024-06-07"); + doc.append(cstr!("open"), 1.0_f64); + doc.append(cstr!("high"), 1.0_f64); + doc.append(cstr!("low"), 1.0_f64); + doc.append(cstr!("close"), 1.0_f64); + doc.append(cstr!("Volume"), 5_i64); + doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + + assert_eq!( + decode_eod_price_doc(&doc).unwrap_err(), + BsonEodPriceError::MissingField { field: "volume" } + ); +} + +#[test] +fn unknown_fields_with_unusual_types_are_ignored() { + // Only known keys are type-checked; the writer's optional `adjustedClose` may be null. + let mut doc = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000); + doc.append(cstr!("adjustedClose"), RawBsonRef::Null); + doc.append(cstr!("adjusted_close"), "n/a"); + doc.append(cstr!("updated_at"), true); + + let bar = decode_eod_price_bytes(doc.as_bytes()).unwrap(); + assert_eq!(bar.close, 130.0); + assert_eq!(bar.adj_volume, 1_000.0); +} + +#[test] +fn datetime_maps_to_utc_calendar_day_at_both_boundaries() { + let d = day(2024, 6, 7); + let cases = [ + (i64::from(d) * MILLIS_PER_DAY, d), + (i64::from(d) * MILLIS_PER_DAY + MILLIS_PER_DAY - 1, d), + (i64::from(d + 1) * MILLIS_PER_DAY, d + 1), + (-1, -1), + (0, 0), + ]; + for (ms, expected) in cases { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "RY.TO"); + doc.append(cstr!("date"), DateTime::from_millis(ms)); + doc.append(cstr!("open"), 1.0_f64); + doc.append(cstr!("high"), 1.0_f64); + doc.append(cstr!("low"), 1.0_f64); + doc.append(cstr!("close"), 1.0_f64); + doc.append(cstr!("volume"), 1_i32); + assert_eq!( + decode_eod_price_doc(&doc).unwrap().session_date, + expected, + "ms={ms}" + ); + } +} + +#[test] +fn key_mapper_receives_search_code_and_session_date() { + let doc = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000); + let raw: RawEodDailyBar<'_> = decode_eod_price_doc(&doc).unwrap(); + + let mut seen = None; + let bar = raw.into_eod_daily_bar(|code, date| { + seen = Some((code.len(), date)); + 7_u32 + }); + assert_eq!(seen, Some((5, day(2024, 6, 7)))); + assert_eq!(bar.key, 7); + assert_eq!(bar.session_date, day(2024, 6, 7)); + assert_eq!(bar.adj_volume, 1_000.0); + + assert!(raw.try_into_eod_daily_bar(|_, _| None::).is_none()); +} + +#[test] +fn error_callback_reports_exact_byte_offset_of_each_rejected_doc() { + let good = valid_doc("A.US", "2024-06-07", 10.0, 1); + let bad_date = valid_doc("B.US", "2024-02-30", 10.0, 1); + let bad_vol = valid_doc("C.US", "2024-06-07", 10.0, -1); + + let mut buf = Vec::new(); + buf.extend_from_slice(good.as_bytes()); + let off_bad_date = buf.len(); + buf.extend_from_slice(bad_date.as_bytes()); + buf.extend_from_slice(good.as_bytes()); + let off_bad_vol = buf.len(); + buf.extend_from_slice(bad_vol.as_bytes()); + + let mut errors = Vec::new(); + let mut decoded = 0; + let stats = decode_eod_price_buffer(&buf, |_| decoded += 1, |o, e| errors.push((o, e))); + + assert_eq!(decoded, 2); + assert_eq!( + errors, + vec![ + ( + off_bad_date, + BsonEodPriceError::MalformedDate { field: "date" } + ), + ( + off_bad_vol, + BsonEodPriceError::InvalidNumber { + field: "volume", + value: -1.0 + } + ), + ] + ); + assert_eq!(stats.docs_in, 4); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); +} + +#[test] +fn empty_buffer_yields_no_docs_and_no_callbacks() { + let stats = decode_eod_price_buffer( + &[], + |_| panic!("no bar expected"), + |_, _| panic!("no error expected"), + ); + assert_eq!(stats.docs_in, 0); + assert_eq!(stats.rejected_total(), 0); + assert!(iter_raw_bson_docs(&[]).next().is_none()); +} + +#[test] +fn truncated_tail_after_good_docs_counts_one_corrupt_reject() { + let good = valid_doc("A.US", "2024-06-07", 10.0, 1); + let mut buf = Vec::new(); + buf.extend_from_slice(good.as_bytes()); + buf.extend_from_slice(good.as_bytes()); + let tail_offset = buf.len(); + buf.extend_from_slice(&good.as_bytes()[..10]); + + let mut errors = Vec::new(); + let stats = decode_eod_price_buffer(&buf, |_| {}, |o, e| errors.push((o, e))); + + assert_eq!(stats.docs_in, 3); + assert_eq!(stats.decoded, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].0, tail_offset); + assert!(matches!( + errors[0].1, + BsonEodPriceError::TruncatedDocument { + remaining: 10, + declared_len: Some(_), + .. + } + )); +} + +#[test] +fn huge_declared_length_is_truncation_not_a_panic() { + let mut buf = i32::MAX.to_le_bytes().to_vec(); + buf.extend_from_slice(&[0u8; 16]); + assert_eq!( + decode_eod_price_bytes(&buf).unwrap_err(), + BsonEodPriceError::TruncatedDocument { + offset: 0, + remaining: 20, + declared_len: Some(i32::MAX), + } + ); + let stats = decode_eod_price_buffer(&buf, |_| {}, |_, _| {}); + assert_eq!(stats.docs_in, 1); + assert_eq!(stats.rejected_corrupt_document, 1); +} + +#[test] +fn single_doc_decode_rejects_trailing_bytes() { + let mut bytes = valid_doc("A.US", "2024-06-07", 10.0, 1).as_bytes().to_vec(); + let declared = bytes.len() as i32; + bytes.push(0); + assert_eq!( + decode_eod_price_bytes(&bytes).unwrap_err(), + BsonEodPriceError::CorruptDocumentLength { + offset: 0, + declared_len: declared, + } + ); +} + +/// `std`-only SplitMix64 so the fuzz corpus is fixed across runs. +struct SplitMix64(u64); + +impl SplitMix64 { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } +} + +#[test] +fn seeded_byte_mutation_fuzz_never_panics_and_always_reconciles() { + let mut base = Vec::new(); + for i in 0..8 { + let code = format!("S{i}.US"); + base.extend_from_slice(valid_doc(&code, "2024-06-07", 10.0 + i as f64, 100).as_bytes()); + } + + let mut rng = SplitMix64(0x0B50_7E57_F022_0097); + for _ in 0..3_000 { + let mut buf = base.clone(); + let flips = 1 + (rng.next() % 4) as usize; + for _ in 0..flips { + let pos = (rng.next() as usize) % buf.len(); + buf[pos] = rng.next() as u8; + } + if rng.next() % 4 == 0 { + let cut = (rng.next() as usize) % buf.len(); + buf.truncate(cut); + } + + // Every bar emitted by the stream must equal the single-doc decode of its framed bytes. + let mut offsets = Vec::new(); + let mut iter = iter_raw_bson_docs(&buf); + while let Some(item) = iter.next_with_offset() { + if let Ok((off, doc)) = item { + offsets.push((off, doc.as_bytes().len())); + } + } + + let mut bars = Vec::new(); + let stats = decode_eod_price_buffer(&buf, |b| bars.push(b), |_, _| {}); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + assert_eq!(stats.decoded, bars.len()); + + let mut expected = Vec::new(); + for (off, len) in offsets { + if let Ok(b) = decode_eod_price_bytes(&buf[off..off + len]) { + expected.push(b); + } + } + // Compare bit patterns so a NaN can never hide a mismatch (decoder rejects NaN anyway). + let key = |b: &RawEodDailyBar<'_>| { + ( + b.eod_search_code.to_string(), + b.session_date, + [b.open, b.high, b.low, b.close, b.adj_volume].map(f64::to_bits), + ) + }; + assert_eq!( + bars.iter().map(key).collect::>(), + expected.iter().map(key).collect::>() + ); + for b in &bars { + for v in [b.open, b.high, b.low, b.close, b.adj_volume] { + assert!(v.is_finite() && v >= 0.0); + } + } + } +} + +fn run_bin(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(args) + .output() + .expect("spawn curate-etl binary") +} + +fn checksum_line(out: &Output) -> String { + let text = String::from_utf8_lossy(&out.stdout); + let checksum = text + .split_whitespace() + .find(|t| t.starts_with("checksum=0x")) + .unwrap_or_else(|| panic!("no checksum in output: {text}")); + let decode = text + .lines() + .find(|l| l.trim_start().starts_with("decode:")) + .unwrap_or_else(|| panic!("no decode line in output: {text}")); + format!("{checksum} {}", decode.trim()) +} + +#[test] +fn bench_binary_prints_identical_checksum_across_runs() { + let a = run_bin(&["bench-bson-eod-prices", "5000"]); + let b = run_bin(&["bench-bson-eod-prices", "5000"]); + assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr)); + assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr)); + + let text = String::from_utf8_lossy(&a.stdout); + assert!(text.contains("rows=5000"), "{text}"); + for needle in ["elapsed=", "rows/s", "MB/s", "checksum=0x"] { + assert!(text.contains(needle), "missing {needle}: {text}"); + } + assert_eq!(checksum_line(&a), checksum_line(&b)); +} + +#[test] +fn bench_binary_rejects_invalid_row_counts() { + for args in [ + &["bench-bson-eod-prices", "0"][..], + &["bench-bson-eod-prices", "-5"][..], + &["bench-bson-eod-prices", "abc"][..], + &["bench-bson-eod-prices", "10", "20"][..], + ] { + let out = run_bin(args); + assert_eq!(out.status.code(), Some(1), "{args:?}"); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("error:"), "{args:?}: {err}"); + assert!(out.stdout.is_empty(), "{args:?} wrote to stdout"); + } +} + +#[test] +fn binary_usage_lists_bson_bench_alongside_merged_curate_benches() { + let out = run_bin(&["--help"]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let text = String::from_utf8_lossy(&out.stdout); + for needle in [ + "bench-bson-eod-prices", + "bench-curate-bars", + "bench-curate-shorts", + ] { + assert!(text.contains(needle), "usage missing {needle}: {text}"); + } +} + +#[test] +fn reused_search_code_resolves_listing_by_decoded_session_date() { + use curate_etl::{ProviderMappingRow, ProviderMappingTable}; + + // Arrange: one ticker reused by two listings with a one-day gap between them. + let mapping = ProviderMappingTable::from_rows([ + ProviderMappingRow { + source: "eod".to_string(), + source_id: "REUSE.US".to_string(), + valid_from: day(2015, 1, 2), + valid_to: Some(day(2020, 1, 30)), + listing_id: 1, + }, + ProviderMappingRow { + source: "eod".to_string(), + source_id: "REUSE.US".to_string(), + valid_from: day(2020, 2, 1), + valid_to: None, + listing_id: 2, + }, + ]) + .unwrap(); + + let mut buf = Vec::new(); + buf.extend_from_slice(valid_doc("REUSE.US", "2020-01-30", 10.0, 100).as_bytes()); + buf.extend_from_slice(valid_doc("REUSE.US", "2020-01-31", 10.0, 100).as_bytes()); + // First day of the successor listing, stored as a mid-day BSON DateTime. + let mut dt_doc = RawDocumentBuf::new(); + dt_doc.append(cstr!("eodSearchCode"), "REUSE.US"); + dt_doc.append( + cstr!("date"), + DateTime::from_millis(i64::from(day(2020, 2, 1)) * MILLIS_PER_DAY + 43_200_000), + ); + dt_doc.append(cstr!("open"), 9.0); + dt_doc.append(cstr!("high"), 11.0); + dt_doc.append(cstr!("low"), 8.0); + dt_doc.append(cstr!("close"), 10.0); + dt_doc.append(cstr!("volume"), 100_i32); + buf.extend_from_slice(dt_doc.as_bytes()); + + // Act + let mut resolved: Vec<(i32, Option)> = Vec::new(); + let stats = decode_eod_price_buffer( + &buf, + |raw| { + let key = raw + .try_into_eod_daily_bar(|code, d| mapping.resolve("eod", code, d)) + .map(|b| b.key); + resolved.push((raw.session_date, key)); + }, + |offset, err| panic!("unexpected reject at {offset}: {err}"), + ); + + // Assert: each bar maps to the listing valid on its own date; the gap day maps to none. + assert_eq!(stats.decoded, 3); + assert_eq!( + resolved, + vec![ + (day(2020, 1, 30), Some(1)), + (day(2020, 1, 31), None), + (day(2020, 2, 1), Some(2)), + ] + ); +} + +#[test] +fn int64_volume_beyond_i32_range_decodes_exactly() { + let doc = valid_doc("BIG.US", "2024-06-07", 10.0, 3_000_000_123); + let bar = decode_eod_price_doc(&doc).unwrap(); + assert_eq!(bar.adj_volume.to_bits(), 3_000_000_123.0_f64.to_bits()); +} diff --git a/tools/curate-etl/tests/cli.rs b/tools/curate-etl/tests/cli.rs index 21a9d720..109e9e42 100644 --- a/tools/curate-etl/tests/cli.rs +++ b/tools/curate-etl/tests/cli.rs @@ -28,6 +28,7 @@ fn no_args_and_help_print_usage_and_succeed() { assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}"); assert!(text.contains("bench-fx"), "{args:?}: {text}"); assert!(text.contains("bench-events"), "{args:?}: {text}"); + assert!(text.contains("bench-curate-fx"), "{args:?}: {text}"); } } @@ -64,6 +65,10 @@ fn invalid_invocations_exit_nonzero_with_usage_on_stderr() { &["bench-events", "0"][..], &["bench-events", "-5"][..], &["bench-events", "10", "20"][..], + &["bench-curate-fx", "abc"][..], + &["bench-curate-fx", "0"][..], + &["bench-curate-fx", "-5"][..], + &["bench-curate-fx", "10", "20"][..], &["--unknown"][..], &["export"][..], ] { @@ -199,3 +204,37 @@ fn bench_events_small_run_is_headless_deterministic_and_reports_rates() { assert_eq!(checksum_a, checksum_b); assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); } + +#[test] +fn bench_curate_fx_small_run_is_headless_deterministic_and_reports_rates() { + let a = run(&["bench-curate-fx", "2000"]); + let b = run(&["bench-curate-fx", "2000"]); + assert!(a.status.success(), "{}", stderr(&a)); + assert!(b.status.success(), "{}", stderr(&b)); + assert!(stderr(&a).is_empty(), "unexpected stderr: {}", stderr(&a)); + assert!(stderr(&b).is_empty(), "unexpected stderr: {}", stderr(&b)); + + let text_a = stdout(&a); + let text_b = stdout(&b); + assert!(text_a.contains("curate-etl bench-curate-fx"), "{text_a}"); + assert!(text_a.contains("rows=2000 "), "{text_a}"); + assert!(text_a.contains("stage:"), "{text_a}"); + assert!(text_a.contains("parquet:"), "{text_a}"); + assert!(text_a.contains("total:"), "{text_a}"); + assert!(text_a.contains("overlap:"), "{text_a}"); + assert!(text_a.contains("rows/s"), "{text_a}"); + assert!(text_a.contains("bytes="), "{text_a}"); + assert!(text_a.contains("checksum=0x"), "{text_a}"); + + let field = |s: &str, prefix: &str| { + s.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(str::to_owned) + }; + let checksum_a = field(&text_a, "checksum="); + let checksum_b = field(&text_b, "checksum="); + assert!(checksum_a.is_some(), "{text_a}"); + assert_eq!(checksum_a, checksum_b); + assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); + assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes=")); +} diff --git a/tools/curate-etl/tests/curate_bars_qa_contract.rs b/tools/curate-etl/tests/curate_bars_qa_contract.rs new file mode 100644 index 00000000..4407c877 --- /dev/null +++ b/tools/curate-etl/tests/curate_bars_qa_contract.rs @@ -0,0 +1,571 @@ +//! QA contract tests for the public `bars_1d` curation stage (T-98 / M1.2p, T-99 / M1.2q). +//! +//! Covers gaps left by the in-crate `curate_bars_tests.rs`, checking against independent +//! references rather than the stage's own logic: +//! - session-close timestamps for every calendar day in `1976-01-01..=2030-12-31` against a +//! hand-written 3-era US/Canada DST rule (no look-ahead, never earlier than 16:00 ET); +//! - seeded randomized differential test against a naive reference (non-cursor mapping lookup, +//! `BTreeMap` grouping) plus permutation invariance; +//! - `mapping_source` isolation, split-on-one-alias collisions, builder-vs-stage duplicate +//! counters, owned currency pass-through, and an all-dropped write creating no partitions. + +use std::borrow::Cow; +use std::collections::{BTreeMap, HashMap}; +use std::fs; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + build_bars_1d, curate_and_write_bars_1d, curate_bars_1d, Bars1dParquetRow, + Bars1dWriteOptions, CurateBars1dOutput, EodDailyBar, ProviderMappingRow, + ProviderMappingTable, QmRawVolume, SplitEvent, SplitTable, BARS_1D_SOURCE_EOD, + SESSION_CLOSE_MAX_SUPPORTED_DATE, SESSION_CLOSE_MIN_SUPPORTED_DATE, +}; + +const MICROS_PER_HOUR: i64 = 3_600_000_000; +const MICROS_PER_DAY: i64 = 86_400_000_000; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-bars-qa-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// Deterministic SplitMix64 (fixed seed per test). +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next_u64() % n + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + curate_etl::ymd_to_epoch_days(y, m, d).expect("valid date") +} + +/// 0 = Sunday. 1970-01-01 was a Thursday. +fn weekday(epoch_day: i32) -> i32 { + (epoch_day + 4).rem_euclid(7) +} + +fn nth_sunday(year: i32, month: u32, n: i32) -> i32 { + let first = day(year, month, 1); + let to_sunday = (7 - weekday(first)) % 7; + first + to_sunday + 7 * (n - 1) +} + +fn last_sunday(year: i32, month: u32) -> i32 { + let last = if month == 12 { + day(year + 1, 1, 1) - 1 + } else { + day(year, month + 1, 1) - 1 + }; + last - weekday(last) +} + +/// Independent reference: 16:00 ET in UTC micros across all three US/Canada DST eras +/// (`1976..=1986` last Sun Apr -> last Sun Oct; `1987..=2006` 1st Sun Apr -> last Sun Oct; +/// `2007..=2030` 2nd Sun Mar -> 1st Sun Nov). +fn reference_close_utc(epoch_day: i32) -> i64 { + let (y, _, _) = curate_etl::epoch_days_to_ymd(epoch_day); + let (start, end) = if y <= 1986 { + (last_sunday(y, 4), last_sunday(y, 10)) + } else if y <= 2006 { + (nth_sunday(y, 4, 1), last_sunday(y, 10)) + } else { + (nth_sunday(y, 3, 2), nth_sunday(y, 11, 1)) + }; + let edt = epoch_day >= start && epoch_day < end; + let utc_hour = if edt { 20 } else { 21 }; + i64::from(epoch_day) * MICROS_PER_DAY + utc_hour * MICROS_PER_HOUR +} + +fn bar(key: &str, d: i32, o: f64, h: f64, l: f64, c: f64, v: f64) -> EodDailyBar { + EodDailyBar { + key: key.to_string(), + session_date: d, + open: o, + high: h, + low: l, + close: c, + adj_volume: v, + } +} + +fn map_row(source: &str, id: &str, from: i32, to: Option, lid: i32) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: id.to_string(), + valid_from: from, + valid_to: to, + listing_id: lid, + } +} + +fn usd(ids: &[i32]) -> HashMap> { + ids.iter().map(|&id| (id, Cow::Borrowed("USD"))).collect() +} + +fn no_qm() -> std::iter::Empty> { + std::iter::empty() +} + +fn assert_conservation(out: &CurateBars1dOutput) { + let s = &out.stats; + assert_eq!(s.rows_in, s.builder.rows_out, "{s:?}"); + assert_eq!(s.rows_out, out.rows.len(), "{s:?}"); + assert_eq!( + s.rows_in, + s.rows_out + + s.dropped_unmapped + + s.dropped_missing_currency + + s.dropped_ts_out_of_range + + s.listing_collision_collapsed + + s.listing_collision_dropped, + "{s:?}" + ); + for w in out.rows.windows(2) { + assert!((w[0].listing_id, w[0].session_date) < (w[1].listing_id, w[1].session_date)); + } +} + +fn row_bits(r: &Bars1dParquetRow) -> (i32, i64, i32, [u64; 5], Option, String, String, i64) { + ( + r.listing_id, + r.ts_micros, + r.session_date, + [ + r.open.to_bits(), + r.high.to_bits(), + r.low.to_bits(), + r.close.to_bits(), + r.volume.to_bits(), + ], + r.vwap.map(f64::to_bits), + r.currency.to_string(), + r.source.to_string(), + r.known_at_micros, + ) +} + +#[test] +fn every_supported_day_closes_at_1600_et_per_independent_dst_rule_and_never_earlier() { + // One mapped source id, one bar per calendar day across the whole supported window plus + // one day on each side. + let mapping = + ProviderMappingTable::from_rows([map_row("eod", "SPY.US", i32::MIN, None, 1)]).unwrap(); + let bars: Vec<_> = (SESSION_CLOSE_MIN_SUPPORTED_DATE - 1..=SESSION_CLOSE_MAX_SUPPORTED_DATE + 1) + .map(|d| bar("SPY.US", d, 10.0, 11.0, 9.0, 10.5, 100.0)) + .collect(); + let total = bars.len(); + + let out = curate_bars_1d( + bars, + &SplitTable::::default(), + no_qm(), + 0.01, + &mapping, + "eod", + &usd(&[1]), + ) + .unwrap(); + + assert_conservation(&out); + assert_eq!(out.stats.dropped_ts_out_of_range, 2); + assert_eq!(out.rows.len(), total - 2); + assert_eq!( + out.rows.first().unwrap().session_date, + SESSION_CLOSE_MIN_SUPPORTED_DATE + ); + assert_eq!( + out.rows.last().unwrap().session_date, + SESSION_CLOSE_MAX_SUPPORTED_DATE + ); + + for r in &out.rows { + let expected = reference_close_utc(r.session_date); + assert_eq!(r.ts_micros, expected, "session_date={}", r.session_date); + assert_eq!(r.known_at_micros, r.ts_micros); + // Never earlier than 16:00 EDT (the earliest possible UTC instant of a 16:00 ET close) + // and never rolled into the next UTC day. + let day_start = i64::from(r.session_date) * MICROS_PER_DAY; + assert!(r.ts_micros >= day_start + 20 * MICROS_PER_HOUR); + assert!(r.ts_micros < day_start + MICROS_PER_DAY); + } +} + +/// Naive reference: same builder (unchanged dependency), then a non-cursor `resolve`, a direct +/// currency lookup, the independent close rule, and `BTreeMap` grouping. +fn reference_curate( + bars: Vec>, + splits: &SplitTable, + qm: Vec>, + mapping: &ProviderMappingTable, + source: &str, + currencies: &HashMap>, +) -> (Vec, [usize; 5]) { + let built = build_bars_1d(bars, splits, qm, 0.01).unwrap(); + let mut unmapped = 0; + let mut no_curr = 0; + let mut oor = 0; + let mut groups: BTreeMap<(i32, i32), Vec> = BTreeMap::new(); + for b in built.rows { + let Some(lid) = mapping.resolve(source, &b.key, b.session_date) else { + unmapped += 1; + continue; + }; + let Some(curr) = currencies.get(&lid).filter(|c| !c.trim().is_empty()) else { + no_curr += 1; + continue; + }; + if b.session_date < SESSION_CLOSE_MIN_SUPPORTED_DATE + || b.session_date > SESSION_CLOSE_MAX_SUPPORTED_DATE + { + oor += 1; + continue; + } + let ts = reference_close_utc(b.session_date); + groups + .entry((lid, b.session_date)) + .or_default() + .push(Bars1dParquetRow { + listing_id: lid, + ts_micros: ts, + session_date: b.session_date, + open: b.open, + high: b.high, + low: b.low, + close: b.close, + volume: b.volume, + vwap: None, + currency: curr.clone(), + source: Cow::Borrowed(BARS_1D_SOURCE_EOD), + known_at_micros: ts, + }); + } + let mut collapsed = 0; + let mut dropped = 0; + let mut rows = Vec::new(); + for (_, g) in groups { + let first = row_bits(&g[0]).3; + if g.iter().all(|r| row_bits(r).3 == first) { + collapsed += g.len() - 1; + rows.push(g.into_iter().next().unwrap()); + } else { + dropped += g.len(); + } + } + (rows, [unmapped, no_curr, oor, collapsed, dropped]) +} + +#[test] +fn seeded_random_fixtures_match_naive_reference_and_are_permutation_invariant() { + let mut hit = [0usize; 5]; + for seed in 0..12u64 { + let mut rng = Rng(0xC0FF_EE00 ^ seed.wrapping_mul(0x9E37_79B9)); + let keys: Vec = (0..8).map(|i| format!("K{i}.US")).collect(); + let base = day(1975, 11, 1); + let span = 120u64; // straddles 1976-01-01 so some bars are out of range + + // Mapping: K0..K5 date-ranged (with gaps) onto listings 1..=4 so several ids alias the + // same listing; K6 maps to listing 9 (no currency); K7 is unmapped. A decoy source + // maps K7 too and must be ignored. + let mut rows = vec![map_row("other", "K7.US", i32::MIN, None, 1)]; + for (i, k) in keys.iter().enumerate().take(6) { + let cut = base + 30 + rng.below(60) as i32; + rows.push(map_row("eod", k, base + rng.below(10) as i32, Some(cut), (i % 4) as i32 + 1)); + rows.push(map_row("eod", k, cut + 1 + rng.below(5) as i32, None, (i % 3) as i32 + 1)); + } + rows.push(map_row("eod", "K6.US", i32::MIN, None, 9)); + let mapping = ProviderMappingTable::from_rows(rows).unwrap(); + let mut currencies = usd(&[1, 2, 3, 4]); + currencies.insert(2, Cow::Owned("CAD".to_string())); + + let splits = SplitTable::from_events([( + keys[rng.below(6) as usize].clone(), + SplitEvent { + ex_date: base + 60, + ratio: 4.0, + }, + )]) + .unwrap(); + + // Small price lattice so identical cross-id bars occur by chance. + let mut bars = Vec::new(); + let mut qm = Vec::new(); + for _ in 0..400 { + let k = &keys[rng.below(8) as usize]; + let d = base + rng.below(span) as i32; + let lo = 10.0 + rng.below(2) as f64; + let b = bar(k, d, lo + 0.5, lo + 1.0, lo, lo + 0.5, 100.0 * (1 + rng.below(2)) as f64); + if rng.below(3) == 0 { + qm.push(QmRawVolume { + key: k.clone(), + session_date: d, + share_volume: 100.0, + }); + } + bars.push(b); + } + // A few invalid bars for builder drops. + bars.push(bar("K0.US", base + 70, f64::NAN, 1.0, 1.0, 1.0, 1.0)); + bars.push(bar("K1.US", base + 71, 5.0, 4.0, 6.0, 5.0, 1.0)); + + let (ref_rows, ref_counts) = reference_curate( + bars.clone(), + &splits, + qm.clone(), + &mapping, + "eod", + ¤cies, + ); + + let out = curate_bars_1d( + bars.clone(), + &splits, + qm.clone(), + 0.01, + &mapping, + "eod", + ¤cies, + ) + .unwrap(); + assert_conservation(&out); + let s = &out.stats; + assert_eq!( + [ + s.dropped_unmapped, + s.dropped_missing_currency, + s.dropped_ts_out_of_range, + s.listing_collision_collapsed, + s.listing_collision_dropped + ], + ref_counts, + "seed {seed}" + ); + let got: Vec<_> = out.rows.iter().map(row_bits).collect(); + let want: Vec<_> = ref_rows.iter().map(row_bits).collect(); + assert_eq!(got, want, "seed {seed}"); + assert_eq!( + s.builder, + build_bars_1d(bars.clone(), &splits, qm.clone(), 0.01).unwrap().stats, + "builder stats must pass through untouched" + ); + for (h, c) in hit.iter_mut().zip(ref_counts) { + *h += c; + } + + // Fisher-Yates shuffle of both inputs: output and counters are identical. + let mut shuffled = bars; + for i in (1..shuffled.len()).rev() { + shuffled.swap(i, rng.below(i as u64 + 1) as usize); + } + let mut qm_shuffled = qm; + qm_shuffled.reverse(); + let out2 = curate_bars_1d( + shuffled, + &splits, + qm_shuffled, + 0.01, + &mapping, + "eod", + ¤cies, + ) + .unwrap(); + assert_eq!(out2.stats, out.stats, "seed {seed}"); + assert_eq!(out2.rows.iter().map(row_bits).collect::>(), got); + } + assert!( + hit.iter().all(|&c| c > 0), + "every drop/collision path must be exercised across seeds: {hit:?}" + ); +} + +#[test] +fn mapping_lookups_use_only_the_requested_source() { + let d = day(2024, 2, 1); + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "ABC.US", i32::MIN, None, 1), + map_row("qm", "ABC.US", i32::MIN, None, 2), + ]) + .unwrap(); + let currencies = usd(&[1, 2]); + let bars = vec![bar("ABC.US", d, 10.0, 11.0, 9.0, 10.0, 5.0)]; + let splits = SplitTable::::default(); + + let eod = curate_bars_1d(bars.clone(), &splits, no_qm(), 0.0, &mapping, "eod", ¤cies) + .unwrap(); + assert_eq!(eod.rows.len(), 1); + assert_eq!(eod.rows[0].listing_id, 1); + + let qm = curate_bars_1d(bars.clone(), &splits, no_qm(), 0.0, &mapping, "qm", ¤cies) + .unwrap(); + assert_eq!(qm.rows[0].listing_id, 2); + + let unknown = + curate_bars_1d(bars, &splits, no_qm(), 0.0, &mapping, "ibkr", ¤cies).unwrap(); + assert_conservation(&unknown); + assert!(unknown.rows.is_empty()); + assert_eq!(unknown.stats.dropped_unmapped, 1); +} + +#[test] +fn split_on_one_alias_conflicts_before_ex_date_and_collapses_after() { + // A.US and B.US both map to listing 7 with identical adjusted bars, but only A.US has a + // 2:1 split. Before the ex-date their un-adjusted volumes differ -> group dropped. + let ex = day(2024, 6, 10); + let pre = ex - 3; + let post = ex + 1; + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "A.US", i32::MIN, None, 7), + map_row("eod", "B.US", i32::MIN, None, 7), + ]) + .unwrap(); + let splits = SplitTable::from_events([( + "A.US".to_string(), + SplitEvent { + ex_date: ex, + ratio: 2.0, + }, + )]) + .unwrap(); + let mut bars = Vec::new(); + for k in ["A.US", "B.US"] { + bars.push(bar(k, pre, 10.0, 11.0, 9.0, 10.0, 1_000.0)); + bars.push(bar(k, post, 10.0, 11.0, 9.0, 10.0, 1_000.0)); + } + let out = curate_bars_1d(bars, &splits, no_qm(), 0.01, &mapping, "eod", &usd(&[7])).unwrap(); + assert_conservation(&out); + assert_eq!(out.stats.listing_collision_dropped, 2); + assert_eq!(out.stats.listing_collision_collapsed, 1); + assert_eq!(out.rows.len(), 1); + assert_eq!(out.rows[0].session_date, post); + assert_eq!(out.rows[0].volume.to_bits(), 1_000.0_f64.to_bits()); +} + +#[test] +fn same_source_duplicates_counted_by_builder_and_cross_source_collisions_by_stage() { + let d = day(2024, 3, 1); + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "A.US", i32::MIN, None, 1), + map_row("eod", "B.US", i32::MIN, None, 1), + ]) + .unwrap(); + let same = bar("A.US", d, 10.0, 11.0, 9.0, 10.0, 5.0); + let bars = vec![ + same.clone(), + same, // builder collapse + bar("B.US", d, 10.0, 11.0, 9.0, 10.0, 5.0), // stage collapse + ]; + let out = curate_bars_1d( + bars, + &SplitTable::::default(), + no_qm(), + 0.01, + &mapping, + "eod", + &usd(&[1]), + ) + .unwrap(); + assert_conservation(&out); + assert_eq!(out.stats.builder.duplicate_collapsed, 1); + assert_eq!(out.stats.builder.duplicate_conflict_dropped, 0); + assert_eq!(out.stats.listing_collision_collapsed, 1); + assert_eq!(out.stats.listing_collision_dropped, 0); + assert_eq!(out.rows.len(), 1); +} + +#[test] +fn ticker_rename_without_overlap_never_collides_and_owned_currency_passes_through() { + // OLD.US -> listing 5 until 2023-12-31, NEW.US -> listing 5 from 2024-01-01 (rename). + // Both feeds carry overlapping dates, but the mapping windows keep them disjoint. + let cut = day(2023, 12, 31); + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "OLD.US", i32::MIN, Some(cut), 5), + map_row("eod", "NEW.US", cut + 1, None, 5), + ]) + .unwrap(); + let mut currencies = HashMap::new(); + currencies.insert(5, Cow::Owned::<'static, str>("CAD".to_string())); + let mut bars = Vec::new(); + for d in cut - 2..=cut + 2 { + bars.push(bar("OLD.US", d, 10.0, 11.0, 9.0, 10.0, 5.0)); + bars.push(bar("NEW.US", d, 20.0, 21.0, 19.0, 20.0, 6.0)); + } + let out = curate_bars_1d( + bars, + &SplitTable::::default(), + no_qm(), + 0.01, + &mapping, + "eod", + ¤cies, + ) + .unwrap(); + assert_conservation(&out); + assert_eq!(out.stats.listing_collision_collapsed, 0); + assert_eq!(out.stats.listing_collision_dropped, 0); + assert_eq!(out.stats.dropped_unmapped, 5); + assert_eq!(out.rows.len(), 5); + assert_eq!(out.stats.listings_out, 1); + for r in &out.rows { + let expected_open = if r.session_date <= cut { 10.0 } else { 20.0 }; + assert_eq!(r.open.to_bits(), f64::to_bits(expected_open)); + assert_eq!(r.currency.as_ref(), "CAD"); + } +} + +#[test] +fn write_wrapper_with_everything_dropped_publishes_no_partitions() { + let tmp = TempDir::new("all-dropped"); + let report = curate_and_write_bars_1d( + &tmp.0, + vec![bar("ZZZ.US", day(2024, 1, 2), 1.0, 1.0, 1.0, 1.0, 1.0)], + &SplitTable::::default(), + no_qm(), + 0.01, + &ProviderMappingTable::default(), + "eod", + &HashMap::new(), + Bars1dWriteOptions::default(), + ) + .unwrap(); + assert_eq!(report.curate_stats.dropped_unmapped, 1); + assert_eq!(report.write_stats.rows_written, 0); + assert_eq!(report.write_stats.files_written, 0); + assert!(report.write_stats.rows_by_year.is_empty()); + let year_dirs = fs::read_dir(tmp.0.join("bars_1d")) + .map(|it| { + it.filter_map(Result::ok) + .filter(|e| e.file_name().to_string_lossy().starts_with("year=")) + .count() + }) + .unwrap_or(0); + assert_eq!(year_dirs, 0); +} diff --git a/tools/curate-etl/tests/curate_fx_qa_contract.rs b/tools/curate-etl/tests/curate_fx_qa_contract.rs new file mode 100644 index 00000000..52b9c56b --- /dev/null +++ b/tools/curate-etl/tests/curate_fx_qa_contract.rs @@ -0,0 +1,407 @@ +//! QA contract tests for the public `fx_1d` curation stage (T-102 / M1.2t). +//! +//! Covers gaps left by the in-crate `curate_fx_tests.rs`, checking against independent +//! references rather than the stage's own logic: +//! - seeded differential test against a naive `BTreeMap` merge (EOD wins, TE fills) on clean, +//! shuffled inputs, with `ts`/`known_at` recomputed in `i128`; +//! - point-in-time join: an as-of lookup by `known_at <= t` at a `16:00 ET` equity close on day +//! `d` (both DST regimes) resolves to day `d-1`'s bar, never day `d`'s; +//! - poison look-ahead: appending absurd future EOD/TE rows leaves every earlier row bit-identical; +//! - multi-row-group round trip and re-publish replacing a larger `part.parquet` with a smaller one; +//! - `bench-curate-fx` binary run: checksum and bytes pinned to the README values, temp dir cleaned. + +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + curate_and_write_fx_1d, curate_fx_1d, fx_1d_parquet_schema, ymd_to_epoch_days, Fx1dParquetRow, + Fx1dWriteOptions, FxDailyBar, FX_PAIR_USDCAD, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_HOUR: i64 = 3_600_000_000; +const MICROS_PER_DAY: i64 = 86_400_000_000; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-fx-qa-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// Deterministic SplitMix64 (fixed seed per test). +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next_u64() % n + } + + fn unit(&mut self) -> f64 { + (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64 + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn bar(session_date: i32, open: f64, high: f64, low: f64, close: f64) -> FxDailyBar { + FxDailyBar { + session_date, + open, + high, + low, + close, + } +} + +/// Clean OHLC bar (`low <= open, close <= high`, all positive and finite). +fn clean_bar(rng: &mut Rng, session_date: i32) -> FxDailyBar { + let mid = 0.9 + rng.unit() * 0.7; + let open = mid * (1.0 + (rng.unit() - 0.5) * 0.004); + let close = mid * (1.0 + (rng.unit() - 0.5) * 0.004); + let high = open.max(close) * (1.0 + rng.unit() * 0.003); + let low = open.min(close) * (1.0 - rng.unit() * 0.003); + bar(session_date, open, high, low, close) +} + +fn shuffle(v: &mut [T], rng: &mut Rng) { + for i in (1..v.len()).rev() { + let j = rng.below(i as u64 + 1) as usize; + v.swap(i, j); + } +} + +fn day_end_reference(session_date: i32) -> i64 { + let wide = (i128::from(session_date) + 1) * i128::from(MICROS_PER_DAY) - 1; + i64::try_from(wide).expect("test dates fit in i64 micros") +} + +fn assert_row_bits(actual: &Fx1dParquetRow, expected: &Fx1dParquetRow) { + assert_eq!(actual.pair.as_ref(), expected.pair.as_ref()); + assert_eq!(actual.session_date, expected.session_date); + assert_eq!(actual.ts_micros, expected.ts_micros); + assert_eq!(actual.open.to_bits(), expected.open.to_bits()); + assert_eq!(actual.high.to_bits(), expected.high.to_bits()); + assert_eq!(actual.low.to_bits(), expected.low.to_bits()); + assert_eq!(actual.close.to_bits(), expected.close.to_bits()); + assert_eq!(actual.source.as_ref(), expected.source.as_ref()); + assert_eq!(actual.known_at_micros, expected.known_at_micros); +} + +fn read_back(path: &Path) -> (usize, Vec) { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + assert_eq!( + meta.file_metadata().schema_descr().root_schema_ptr(), + fx_1d_parquet_schema().expect("schema") + ); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let rgr = reader.get_row_group(rg).expect("row group"); + let n = meta.row_group(rg).num_rows() as usize; + let strs = |i: usize| -> Vec { + let mut v = Vec::new(); + match rgr.get_column_reader(i).unwrap() { + ColumnReader::ByteArrayColumnReader(mut r) => { + r.read_records(n, None, None, &mut v).unwrap(); + } + _ => panic!("expected byte array column {i}"), + } + v.into_iter() + .map(|b| String::from_utf8(b.data().to_vec()).unwrap()) + .collect() + }; + let i64s = |i: usize| -> Vec { + let mut v = Vec::new(); + match rgr.get_column_reader(i).unwrap() { + ColumnReader::Int64ColumnReader(mut r) => { + r.read_records(n, None, None, &mut v).unwrap(); + } + _ => panic!("expected i64 column {i}"), + } + v + }; + let f64s = |i: usize| -> Vec { + let mut v = Vec::new(); + match rgr.get_column_reader(i).unwrap() { + ColumnReader::DoubleColumnReader(mut r) => { + r.read_records(n, None, None, &mut v).unwrap(); + } + _ => panic!("expected f64 column {i}"), + } + v + }; + let mut dates = Vec::new(); + match rgr.get_column_reader(1).unwrap() { + ColumnReader::Int32ColumnReader(mut r) => { + r.read_records(n, None, None, &mut dates).unwrap(); + } + _ => panic!("expected i32 session_date"), + } + let (pair, ts, o, h, l, c, src, ka) = ( + strs(0), + i64s(2), + f64s(3), + f64s(4), + f64s(5), + f64s(6), + strs(7), + i64s(8), + ); + assert_eq!(dates.len(), n); + for i in 0..n { + out.push(Fx1dParquetRow { + pair: Cow::Owned(pair[i].clone()), + session_date: dates[i], + ts_micros: ts[i], + open: o[i], + high: h[i], + low: l[i], + close: c[i], + source: Cow::Owned(src[i].clone()), + known_at_micros: ka[i], + }); + } + } + (meta.file_metadata().num_rows() as usize, out) +} + +#[test] +fn seeded_differential_matches_naive_eod_precedence_union_merge() { + for seed in [0x1u64, 0xF00D, 0xC0FF_EE11, 0x5EED_0102_0304] { + let mut rng = Rng(seed); + let start = day(1969, 6, 2); + let span = 4_000; + let mut eod = Vec::new(); + let mut te = Vec::new(); + for d in start..start + span { + // ~70% EOD, ~45% TE, independent: gives overlap, interior gaps, head and tail. + if rng.below(100) < 70 && d < start + span - 300 { + eod.push(clean_bar(&mut rng, d)); + } + if rng.below(100) < 45 { + te.push(clean_bar(&mut rng, d)); + } + } + shuffle(&mut eod, &mut rng); + shuffle(&mut te, &mut rng); + + let mut reference: BTreeMap = BTreeMap::new(); + for b in &te { + reference.insert(b.session_date, (*b, "te_usdcad")); + } + for b in &eod { + reference.insert(b.session_date, (*b, "eod_cad_forex")); + } + + let out = curate_fx_1d(&eod, &te).expect("clean input curates"); + assert_eq!(out.rows.len(), reference.len(), "seed {seed:#x}"); + assert_eq!(out.stats.rows_in, out.stats.builder.rows_out); + assert_eq!(out.stats.rows_out, out.rows.len()); + assert_eq!( + out.stats.builder.eod_rows_out + out.stats.builder.te_rows_out, + out.rows.len() + ); + + for (row, (date, (b, src))) in out.rows.iter().zip(reference.iter()) { + let ts = day_end_reference(*date); + let expected = Fx1dParquetRow { + pair: Cow::Borrowed(FX_PAIR_USDCAD), + session_date: *date, + ts_micros: ts, + open: b.open, + high: b.high, + low: b.low, + close: b.close, + source: Cow::Borrowed(src), + known_at_micros: ts, + }; + assert_row_bits(row, &expected); + } + } +} + +#[test] +fn as_of_join_at_same_day_equity_close_never_sees_that_days_fx_bar() { + // 16:00 America/Toronto = 21:00 UTC in EST and 20:00 UTC in EDT. + let cases = [ + (day(2025, 1, 15), 21), // EST + (day(2025, 7, 15), 20), // EDT + (day(1972, 2, 15), 21), // pre-session_close.rs range, EST + (day(1969, 12, 31), 21), // negative session_date + ]; + for (d, close_hour_utc) in cases { + let eod = [ + bar(d - 1, 1.30, 1.31, 1.29, 1.305), + bar(d, 1.40, 1.41, 1.39, 1.405), + bar(d + 1, 1.50, 1.51, 1.49, 1.505), + ]; + let out = curate_fx_1d(&eod, &[]).unwrap(); + let close_ts = i64::from(d) * MICROS_PER_DAY + close_hour_utc * MICROS_PER_HOUR; + + let visible: Vec<&Fx1dParquetRow> = out + .rows + .iter() + .filter(|r| r.known_at_micros <= close_ts) + .collect(); + let latest = visible.last().expect("prior day bar is visible"); + assert_eq!(latest.session_date, d - 1, "date {d}"); + assert_eq!(latest.close.to_bits(), 1.305f64.to_bits()); + + // Day d's bar becomes visible exactly at its last UTC microsecond, not one before. + let row_d = out.rows.iter().find(|r| r.session_date == d).unwrap(); + let next_midnight = (i64::from(d) + 1) * MICROS_PER_DAY; + assert_eq!(row_d.known_at_micros, next_midnight - 1); + assert!(row_d.known_at_micros > close_ts); + } +} + +#[test] +fn poison_future_rows_leave_every_earlier_row_bit_identical() { + let mut rng = Rng(0xBAD_F00D); + let base = day(2024, 1, 1); + let eod: Vec = (0..200).map(|i| clean_bar(&mut rng, base + i)).collect(); + let te: Vec = (150..260).map(|i| clean_bar(&mut rng, base + i)).collect(); + let baseline = curate_fx_1d(&eod, &te).unwrap(); + + for cutoff in [base + 50, base + 199, base + 259] { + let mut eod_p = eod.clone(); + let mut te_p = te.clone(); + // Absurd but valid future rows after the cutoff, including overlap conflicts. + eod_p.push(bar(cutoff + 1, 99.0, 100.0, 98.0, 99.5)); + te_p.push(bar(cutoff + 1, 0.01, 0.02, 0.005, 0.015)); + te_p.push(bar(cutoff + 400, 50.0, 51.0, 49.0, 50.5)); + eod_p.reverse(); + let poisoned = curate_fx_1d(&eod_p, &te_p).unwrap(); + + let keep = baseline + .rows + .iter() + .take_while(|r| r.session_date <= cutoff) + .count(); + assert!(keep > 0); + for (a, b) in poisoned.rows[..keep].iter().zip(&baseline.rows[..keep]) { + assert_row_bits(a, b); + } + } +} + +#[test] +fn multi_row_group_round_trip_and_republish_smaller_dataset() { + let tmp = TempDir::new("multi-rg"); + let mut rng = Rng(0x0123_4567); + let base = day(1971, 1, 4); + let eod: Vec = (0..1_000).map(|i| clean_bar(&mut rng, base + i)).collect(); + let te: Vec = (900..1_037) + .map(|i| clean_bar(&mut rng, base + i)) + .collect(); + let options = Fx1dWriteOptions { + row_group_rows: 128, + ..Fx1dWriteOptions::default() + }; + + let expected = curate_fx_1d(&eod, &te).unwrap(); + let report = curate_and_write_fx_1d(&tmp.0, &eod, &te, options).unwrap(); + assert_eq!(report.write_stats.rows_written, 1_037); + assert_eq!( + report.write_stats.row_groups_written, + 1_037usize.div_ceil(128) + ); + let part = tmp.0.join("fx_1d/part.parquet"); + let (footer, rows) = read_back(&part); + assert_eq!(footer, expected.rows.len()); + assert_eq!(rows.len(), expected.rows.len()); + for (a, b) in rows.iter().zip(&expected.rows) { + assert_row_bits(a, b); + } + let large_len = fs::metadata(&part).unwrap().len(); + + // Re-publish a much smaller dataset: no stale tail rows from the larger file survive. + let small = [bar(base + 5_000, 1.2, 1.25, 1.18, 1.22)]; + let report2 = curate_and_write_fx_1d(&tmp.0, &small, &[], options).unwrap(); + assert_eq!(report2.write_stats.rows_written, 1); + assert!(fs::metadata(&part).unwrap().len() < large_len); + let (footer2, rows2) = read_back(&part); + assert_eq!(footer2, 1); + assert_eq!(rows2[0].session_date, base + 5_000); + assert_eq!(rows2[0].ts_micros, day_end_reference(base + 5_000)); + assert_eq!(rows2[0].source.as_ref(), "eod_cad_forex"); + let names: Vec = fs::read_dir(tmp.0.join("fx_1d")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names, vec!["part.parquet".to_string()]); +} + +fn field<'a>(text: &'a str, prefix: &str) -> Option<&'a str> { + text.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(|t| &t[prefix.len()..]) +} + +#[test] +fn bench_curate_fx_default_run_matches_readme_checksum_and_cleans_temp_dir() { + let tmp = TempDir::new("bench-tmpdir"); + let output = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .arg("bench-curate-fx") + .env("TMPDIR", &tmp.0) + .output() + .expect("run curate-etl"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + + // Values recorded in tools/curate-etl/README.md (`bench-curate-fx`, default 20,000 rows). + assert_eq!(field(&stdout, "rows="), Some("20000"), "{stdout}"); + assert_eq!( + field(&stdout, "checksum="), + Some("0x298f47e68cdf7022"), + "{stdout}" + ); + assert_eq!(field(&stdout, "bytes="), Some("714498"), "{stdout}"); + assert_eq!(field(&stdout, "read_back_rows="), Some("17180"), "{stdout}"); + assert_eq!(field(&stdout, "rows_out="), Some("17180"), "{stdout}"); + + let leftovers: Vec<_> = fs::read_dir(&tmp.0) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert!( + leftovers.is_empty(), + "bench left temp entries: {leftovers:?}" + ); +} diff --git a/tools/curate-etl/tests/curate_shorts_qa_contract.rs b/tools/curate-etl/tests/curate_shorts_qa_contract.rs new file mode 100644 index 00000000..4ab0dfa7 --- /dev/null +++ b/tools/curate-etl/tests/curate_shorts_qa_contract.rs @@ -0,0 +1,509 @@ +//! QA contract tests for the public `shorts` curation stage (T-100 / M1.2r). +//! +//! Covers gaps left by the in-crate `curate_shorts_tests.rs`, checking against independent +//! references rather than the stage's own logic: +//! - `known_at_micros` pinned to hand-computed `+4` TSX business-day `17:00 ET` instants across +//! holidays and both DST regimes; +//! - seeded differential test against a naive reference that resolves `provider_mapping` by +//! linear scan over the raw mapping rows on `report_date` (never through the table/cursor); +//! - truncation and poison look-ahead tests at several cutoffs with non-empty baselines; +//! - ticker change (two keys → one listing over disjoint ranges) kept without collisions; +//! - successful re-publish replaces a larger `part.parquet`, multi-row-group round trip; +//! - `bench-curate-shorts` binary run: deterministic checksum and `read_back_rows == rows_out`. + +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + curate_and_write_shorts, curate_shorts, CeoShortReport, CurateShortsOutput, + ProviderMappingRow, ProviderMappingTable, ShortsParquetRow, ShortsWriteOptions, + SHORTS_SOURCE_CEO, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_HOUR: i64 = 3_600_000_000; +const MICROS_PER_DAY: i64 = 86_400_000_000; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-shorts-qa-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// Deterministic SplitMix64 (fixed seed per test). +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next_u64() % n + } +} + +/// Independent civil-from-days (Howard Hinnant), not the crate's `ymd_to_epoch_days`. +fn day(y: i32, m: u32, d: u32) -> i32 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m as i32 + 9) % 12; + let doy = (153 * mp + 2) / 5 + d as i32 - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +fn report(key: &str, report_date: i32, shares: f64, net: Option, pct: Option) -> CeoShortReport { + CeoShortReport { + key: key.to_string(), + report_date, + shares_short: shares, + net_change: net, + pct_float: pct, + } +} + +fn map_row(source: &str, id: &str, from: i32, to: Option, listing_id: i32) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: id.to_string(), + valid_from: from, + valid_to: to, + listing_id, + } +} + +fn assert_rows_bitwise(actual: &[ShortsParquetRow], expected: &[ShortsParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count mismatch"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!( + (a.listing_id, a.report_date, a.known_at_micros, a.shares_short.to_bits()), + (e.listing_id, e.report_date, e.known_at_micros, e.shares_short.to_bits()), + "row {i}" + ); + assert_eq!(a.net_change.map(f64::to_bits), e.net_change.map(f64::to_bits), "row {i}"); + assert_eq!(a.pct_float.map(f64::to_bits), e.pct_float.map(f64::to_bits), "row {i}"); + assert_eq!(a.source, e.source, "row {i}"); + } +} + +fn assert_invariants(out: &CurateShortsOutput) { + let s = out.stats; + assert_eq!(s.rows_in, s.builder.rows_out, "{s:?}"); + assert_eq!(s.rows_out, out.rows.len(), "{s:?}"); + assert_eq!( + s.rows_in, + s.rows_out + s.dropped_unmapped + s.listing_collision_collapsed + s.listing_collision_dropped, + "{s:?}" + ); + for w in out.rows.windows(2) { + assert!((w[0].listing_id, w[0].report_date) < (w[1].listing_id, w[1].report_date)); + } + let mut listings: Vec = out.rows.iter().map(|r| r.listing_id).collect(); + listings.dedup(); + assert_eq!(s.listings_out, listings.len()); +} + +#[test] +fn known_at_matches_hand_computed_tsx_plus_four_business_days_at_17_et() { + // (report_date, expected known_at date, UTC offset hours of 17:00 ET on that date) + let cases = [ + // Fri before Canada Day (Mon Jul 1): Jul 2,3,4,5 -> Fri Jul 5, EDT (21:00Z). + (day(2024, 6, 28), day(2024, 7, 5), 21), + // Tue Dec 31, New Year's Day Wed: Jan 2,3,6,7 -> Tue Jan 7 2025, EST (22:00Z). + (day(2024, 12, 31), day(2025, 1, 7), 22), + // Fri Dec 15 2023, ordinary: Dec 18..21 -> Thu Dec 21, EST. + (day(2023, 12, 15), day(2023, 12, 21), 22), + // Fri Dec 22 2023? not a report date; use Sun Dec 31 2023: Jan 1 holiday, Jan 2,3,4,5. + (day(2023, 12, 31), day(2024, 1, 5), 22), + // Fri Mar 15 2024 (DST began Mar 10): Mar 18..21, EDT. + (day(2024, 3, 15), day(2024, 3, 21), 21), + // Fri Mar 29 2024 is Good Friday; Sun Mar 31 report: Apr 1(open),2,3,4 -> Apr 4. + (day(2024, 3, 31), day(2024, 4, 4), 21), + // Thu Oct 31 2024 (DST ends Nov 3): Nov 1, 4, 5, 6 -> Wed Nov 6, EST. + (day(2024, 10, 31), day(2024, 11, 6), 22), + // Mon Nov 11 2024 Remembrance Day is a TSX trading day; Fri Nov 15: 18..21. + (day(2024, 11, 15), day(2024, 11, 21), 22), + // Thu Jul 31 2025: Aug 1, (Aug 4 Civic Holiday), 5, 6, 7 -> Thu Aug 7, EDT. + (day(2025, 7, 31), day(2025, 8, 7), 21), + ]; + let mapping = ProviderMappingTable::from_rows([map_row("ceo", "RY", day(2010, 1, 1), None, 7)]).unwrap(); + let reports: Vec<_> = cases.iter().map(|&(d, _, _)| report("RY", d, 1_000.0, None, None)).collect(); + + let out = curate_shorts(reports, "ceo", &mapping).unwrap(); + assert_invariants(&out); + assert_eq!(out.rows.len(), cases.len()); + + let mut sorted = cases; + sorted.sort_by_key(|c| c.0); + for (row, &(rd, known_day, utc_hour)) in out.rows.iter().zip(&sorted) { + assert_eq!(row.report_date, rd); + let expected = i64::from(known_day) * MICROS_PER_DAY + utc_hour * MICROS_PER_HOUR; + assert_eq!( + row.known_at_micros, expected, + "report_date {rd}: known_at off by {} h", + (row.known_at_micros - expected) / MICROS_PER_HOUR + ); + assert_eq!(row.source.as_ref(), SHORTS_SOURCE_CEO); + } +} + +/// Random universe: plain keys, ticker reuse with a gap, ticker change (two keys sharing one +/// listing over disjoint ranges), aliases (overlapping ranges -> collisions), unmapped keys, +/// plus decoy rows under a different mapping source. +fn random_universe() -> (Vec, Vec) { + let mut rows = Vec::new(); + let mut keys = Vec::new(); + for i in 0..8 { + let k = format!("P{i}"); + rows.push(map_row("ceo", &k, day(2018, 1, 1), None, 10 + i)); + rows.push(map_row("other", &k, day(2018, 1, 1), None, 900 + i)); + keys.push(k); + } + for i in 0..3 { + let k = format!("R{i}"); + rows.push(map_row("ceo", &k, day(2018, 1, 1), Some(day(2020, 6, 15)), 40 + i)); + rows.push(map_row("ceo", &k, day(2020, 9, 1), None, 50 + i)); + keys.push(k); + } + for i in 0..3 { + // Ticker change: OLD{i} until 2021-03-31, NEW{i} from 2021-04-01, same listing. + let (old, new) = (format!("OLD{i}"), format!("NEW{i}")); + rows.push(map_row("ceo", &old, day(2018, 1, 1), Some(day(2021, 3, 31)), 60 + i)); + rows.push(map_row("ceo", &new, day(2021, 4, 1), None, 60 + i)); + keys.push(old); + keys.push(new); + } + for i in 0..3 { + let k = format!("A{i}"); + rows.push(map_row("ceo", &k, day(2019, 1, 1), Some(day(2023, 12, 31)), 10 + i)); + keys.push(k); + } + for i in 0..3 { + keys.push(format!("U{i}")); + } + (rows, keys) +} + +fn report_dates() -> Vec { + let mut v = Vec::new(); + for y in 2017..=2025 { + for m in 1..=12u32 { + v.push(day(y, m, 15)); + let next = if m == 12 { day(y + 1, 1, 1) } else { day(y, m + 1, 1) }; + v.push(next - 1); + } + } + v +} + +fn random_reports(seed: u64, n: usize, keys: &[String], dates: &[i32]) -> Vec> { + let mut rng = Rng(seed); + let mut out: Vec> = Vec::with_capacity(n); + while out.len() < n { + // Echo the previous plain-key report under its alias key (`P{i}` -> `A{i}`), identical + // or conflicting, so cross-key collisions are hit deterministically. + let echo = rng.below(10); + if echo < 2 { + if let Some(prev) = out.last() { + if let Some(i) = prev.key.strip_prefix('P').filter(|i| ["0", "1", "2"].contains(i)) { + let mut copy = report(&format!("A{i}"), prev.report_date, prev.shares_short, prev.net_change, prev.pct_float); + if echo == 1 { + copy.shares_short += 1.0; + } + out.push(copy); + continue; + } + } + } + out.push({ + let key = &keys[rng.below(keys.len() as u64) as usize]; + let d = dates[rng.below(dates.len() as u64) as usize]; + let shares = match rng.below(50) { + 0 => -5.0, + 1 => f64::NAN, + _ => (rng.below(3) * 500) as f64, + }; + let net = match rng.below(4) { + 0 => None, + 1 => Some(f64::NEG_INFINITY), + v => Some(v as f64 * 10.0), + }; + let pct = match rng.below(3) { + 0 => None, + v => Some(v as f64 * 0.5), + }; + report(key, d, shares, net, pct) + }); + } + out +} + +/// Naive reference built directly from `build_shorts` output and the raw mapping rows. +fn reference( + reports: Vec>, + source: &str, + mapping_rows: &[ProviderMappingRow], +) -> (Vec, usize, usize, usize) { + let built = curate_etl::build_shorts(reports).unwrap(); + let mut groups: BTreeMap<(i32, i32), Vec> = BTreeMap::new(); + let mut unmapped = 0; + for r in built.rows { + let hit = mapping_rows.iter().find(|m| { + m.source == source + && m.source_id == r.key + && m.valid_from <= r.report_date + && m.valid_to.is_none_or(|to| r.report_date <= to) + }); + match hit { + Some(m) => groups.entry((m.listing_id, r.report_date)).or_default().push(ShortsParquetRow { + listing_id: m.listing_id, + report_date: r.report_date, + known_at_micros: r.known_at_utc_micros, + shares_short: r.shares_short, + net_change: r.net_change, + pct_float: r.pct_float, + source: Cow::Borrowed(r.source), + }), + None => unmapped += 1, + } + } + let key = |r: &ShortsParquetRow| { + (r.known_at_micros, r.shares_short.to_bits(), r.net_change.map(f64::to_bits), r.pct_float.map(f64::to_bits)) + }; + let (mut out, mut collapsed, mut dropped) = (Vec::new(), 0, 0); + for (_, g) in groups { + if g.iter().all(|r| key(r) == key(&g[0])) { + collapsed += g.len() - 1; + out.push(g.into_iter().next().unwrap()); + } else { + dropped += g.len(); + } + } + (out, unmapped, collapsed, dropped) +} + +#[test] +fn seeded_stage_matches_linear_scan_reference_resolving_on_report_date() { + let (mapping_rows, keys) = random_universe(); + let mapping = ProviderMappingTable::from_rows(mapping_rows.clone()).unwrap(); + let dates = report_dates(); + + for seed in [0xC0FF_EE00_0000_0001u64, 0xC0FF_EE00_0000_0002, 0xC0FF_EE00_0000_0003] { + let reports = random_reports(seed, 4_000, &keys, &dates); + let out = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + assert_invariants(&out); + let (exp, unmapped, collapsed, dropped) = reference(reports, "ceo", &mapping_rows); + assert_eq!(out.stats.dropped_unmapped, unmapped, "seed {seed:#x}"); + assert_eq!(out.stats.listing_collision_collapsed, collapsed, "seed {seed:#x}"); + assert_eq!(out.stats.listing_collision_dropped, dropped, "seed {seed:#x}"); + assert!(unmapped > 0 && collapsed > 0 && dropped > 0, "fixture must hit every path: {:?}", out.stats); + assert_rows_bitwise(&out.rows, &exp); + // No row may come from the decoy "other" source listings. + assert!(out.rows.iter().all(|r| r.listing_id < 900)); + } +} + +#[test] +fn ticker_change_keys_share_one_listing_without_collisions() { + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "OLD", day(2018, 1, 1), Some(day(2021, 3, 31)), 60), + map_row("ceo", "NEW", day(2021, 4, 1), None, 60), + ]) + .unwrap(); + let reports = vec![ + report("OLD", day(2021, 2, 28), 100.0, None, None), + report("OLD", day(2021, 3, 31), 200.0, None, None), + report("NEW", day(2021, 4, 15), 300.0, None, None), + // Stale feed: OLD keeps reporting after the change -> unmapped, not a collision. + report("OLD", day(2021, 4, 15), 999.0, None, None), + // NEW backfilled before its range -> unmapped. + report("NEW", day(2021, 3, 15), 888.0, None, None), + ]; + let out = curate_shorts(reports, "ceo", &mapping).unwrap(); + assert_invariants(&out); + assert_eq!(out.stats.dropped_unmapped, 2); + assert_eq!(out.stats.listing_collision_collapsed + out.stats.listing_collision_dropped, 0); + assert_eq!(out.stats.listings_out, 1); + let got: Vec<(i32, f64)> = out.rows.iter().map(|r| (r.report_date, r.shares_short)).collect(); + assert_eq!(got, vec![(day(2021, 2, 28), 100.0), (day(2021, 3, 31), 200.0), (day(2021, 4, 15), 300.0)]); +} + +#[test] +fn truncation_and_poison_leave_earlier_rows_unchanged_at_every_cutoff() { + let (mapping_rows, keys) = random_universe(); + let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); + let dates = report_dates(); + let reports = random_reports(0x7E57_0000_1234_5678, 3_000, &keys, &dates); + let full = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + + for cutoff in [day(2019, 1, 1), day(2020, 7, 1), day(2021, 4, 1), day(2023, 1, 1), day(2025, 6, 1)] { + let truncated: Vec<_> = reports.iter().filter(|r| r.report_date < cutoff).cloned().collect(); + let base = curate_shorts(truncated.clone(), "ceo", &mapping).unwrap(); + assert_invariants(&base); + assert!(base.rows.len() > 10, "cutoff {cutoff}: baseline must not be empty"); + + // Truncation: rebuilding from history alone equals the full run's history. + let prefix: Vec<_> = full.rows.iter().filter(|r| r.report_date < cutoff).cloned().collect(); + assert_rows_bitwise(&base.rows, &prefix); + + // Poison: absurd future reports on every key, conflicting aliases included. + let mut poisoned = truncated; + for (i, k) in keys.iter().enumerate() { + poisoned.push(report(k, day(2026, 1, 15), 1e12 + i as f64, Some(-1e9), Some(99.0))); + poisoned.push(report(k, cutoff, 7e11 + i as f64, None, Some(50.0))); + } + let pois = curate_shorts(poisoned, "ceo", &mapping).unwrap(); + assert_invariants(&pois); + let pois_prefix: Vec<_> = pois.rows.into_iter().filter(|r| r.report_date < cutoff).collect(); + assert_rows_bitwise(&pois_prefix, &base.rows); + + // Every row is published strictly after its report date ends (>= 4 days later). + for r in &base.rows { + assert!(r.known_at_micros >= (i64::from(r.report_date) + 4) * MICROS_PER_DAY); + } + } +} + +fn read_parquet(path: &Path) -> (usize, usize, Vec) { + let reader = SerializedFileReader::new(File::open(path).unwrap()).unwrap(); + let md = reader.metadata(); + let footer = md.file_metadata().num_rows() as usize; + let mut out = Vec::new(); + for g in 0..md.num_row_groups() { + let rg = reader.get_row_group(g).unwrap(); + let n = md.row_group(g).num_rows() as usize; + let mut lid = Vec::new(); + let mut rd = Vec::new(); + let mut ka = Vec::new(); + let mut ss = Vec::new(); + let mut src = Vec::new(); + if let ColumnReader::Int32ColumnReader(mut r) = rg.get_column_reader(0).unwrap() { + r.read_records(n, None, None, &mut lid).unwrap(); + } + if let ColumnReader::Int32ColumnReader(mut r) = rg.get_column_reader(1).unwrap() { + r.read_records(n, None, None, &mut rd).unwrap(); + } + if let ColumnReader::Int64ColumnReader(mut r) = rg.get_column_reader(2).unwrap() { + r.read_records(n, None, None, &mut ka).unwrap(); + } + if let ColumnReader::DoubleColumnReader(mut r) = rg.get_column_reader(3).unwrap() { + r.read_records(n, None, None, &mut ss).unwrap(); + } + let opt = |idx: usize| -> Vec> { + let (mut vals, mut defs) = (Vec::new(), Vec::new()); + if let ColumnReader::DoubleColumnReader(mut r) = rg.get_column_reader(idx).unwrap() { + r.read_records(n, Some(&mut defs), None, &mut vals).unwrap(); + } + let mut it = vals.into_iter(); + defs.into_iter().map(|d| if d == 1 { it.next() } else { None }).collect() + }; + let (net, pct) = (opt(4), opt(5)); + if let ColumnReader::ByteArrayColumnReader(mut r) = rg.get_column_reader(6).unwrap() { + r.read_records(n, None, None, &mut src).unwrap(); + } + assert_eq!((lid.len(), rd.len(), ka.len(), ss.len(), src.len()), (n, n, n, n, n)); + for i in 0..n { + out.push(ShortsParquetRow { + listing_id: lid[i], + report_date: rd[i], + known_at_micros: ka[i], + shares_short: ss[i], + net_change: net[i], + pct_float: pct[i], + source: Cow::Owned(String::from_utf8(src[i].data().to_vec()).unwrap()), + }); + } + } + (footer, md.num_row_groups(), out) +} + +#[test] +fn republish_replaces_larger_file_and_multi_row_group_round_trips() { + let (mapping_rows, keys) = random_universe(); + let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); + let dates = report_dates(); + let tmp = TempDir::new("republish"); + let part = tmp.0.join("shorts").join("part.parquet"); + let opts = ShortsWriteOptions { row_group_rows: 97, ..ShortsWriteOptions::default() }; + + let big = random_reports(0xB16_0000_0000_0001, 2_000, &keys, &dates); + let first = curate_and_write_shorts(&tmp.0, big.clone(), "ceo", &mapping, opts).unwrap(); + let expected_big = curate_shorts(big, "ceo", &mapping).unwrap(); + let (footer, groups, rows) = read_parquet(&part); + assert_eq!(footer, first.curate_stats.rows_out); + assert_eq!(groups, first.write_stats.row_groups_written); + assert_eq!(groups, footer.div_ceil(97)); + assert!(groups > 1); + assert_rows_bitwise(&rows, &expected_big.rows); + + let small = random_reports(0x5A1_0000_0000_0002, 50, &keys, &dates); + let second = curate_and_write_shorts(&tmp.0, small.clone(), "ceo", &mapping, opts).unwrap(); + assert!(second.curate_stats.rows_out > 0 && second.curate_stats.rows_out < first.curate_stats.rows_out); + let (footer, _, rows) = read_parquet(&part); + assert_eq!(footer, second.curate_stats.rows_out); + assert_rows_bitwise(&rows, &curate_shorts(small, "ceo", &mapping).unwrap().rows); + + let leftovers: Vec<_> = fs::read_dir(tmp.0.join("shorts")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(leftovers, vec!["part.parquet".to_string()]); +} + +fn field<'a>(text: &'a str, name: &str) -> &'a str { + text.split_whitespace() + .find_map(|t| t.strip_prefix(name)) + .unwrap_or_else(|| panic!("missing {name} in:\n{text}")) +} + +#[test] +fn bench_curate_shorts_cli_is_deterministic_and_reads_back_all_rows() { + let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_curate-etl")).args(args).output().unwrap(); + let a = run(&["bench-curate-shorts", "30000"]); + let b = run(&["bench-curate-shorts", "30000"]); + assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr)); + assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr)); + let (ta, tb) = (String::from_utf8_lossy(&a.stdout), String::from_utf8_lossy(&b.stdout)); + + assert!(ta.contains("curate-etl bench-curate-shorts"), "{ta}"); + assert!(ta.contains("rows=30000 keys=12500"), "{ta}"); + assert_eq!(field(&ta, "checksum="), field(&tb, "checksum=")); + assert_ne!(field(&ta, "checksum="), "0x0000000000000000"); + // The builder line also has `rows_out=`, so compare against the stage line's value. + let stage_line = ta.lines().find(|l| l.trim_start().starts_with("stage:")).unwrap(); + assert_eq!(field(stage_line, "rows_out="), field(&ta, "read_back_rows=")); + + for bad in [&["bench-curate-shorts", "0"][..], &["bench-curate-shorts", "x"], &["bench-curate-shorts", "1", "2"]] { + let o = run(bad); + assert!(!o.status.success(), "{bad:?} should fail"); + assert!(String::from_utf8_lossy(&o.stderr).contains("bench-curate-shorts"), "{bad:?}"); + } +} diff --git a/tools/curate-etl/tests/parquet_adj_contract.rs b/tools/curate-etl/tests/parquet_adj_contract.rs new file mode 100644 index 00000000..3cefca42 --- /dev/null +++ b/tools/curate-etl/tests/parquet_adj_contract.rs @@ -0,0 +1,705 @@ +//! Contract tests for the public `adj_factors` Parquet writer API (T-95 / M1.2m). +//! +//! Uses only the crate's public surface (`build_adj_factors`, +//! `AdjFactorsParquetRow::from_adj_row`, `write_adj_factors_dataset`, +//! `adj_factors_parquet_schema`, the `curate-etl` binary) plus an independent +//! Parquet column reader, guarding the `design/DATA-CONTRACTS.md` §3A +//! `adj_factors/part.parquet` schema, atomic single-file publish semantics, +//! validation errors, concurrency serialization, determinism, and the +//! `bench-parquet-adj` CLI contract. + +use std::borrow::Cow; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Barrier}; +use std::thread; + +use curate_etl::{ + adj_factors_parquet_schema, build_adj_factors, write_adj_factors_dataset, ymd_to_epoch_days, + AdjFactorsParquetRow, AdjFactorsWriteOptions, AdjFactorsWriteStats, DividendEvent, + ParquetAdjError, SplitEvent, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, +}; +use parquet::basic::{ + Compression, ConvertedType, Encoding, LogicalType, Repetition, TimeUnit, Type as PhysicalType, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-adj-contract-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn part_path(out: &Path) -> PathBuf { + out.join("adj_factors/part.parquet") +} + +fn known_at_before(ex_date: i32) -> i64 { + i64::from(ex_date - 14) * 86_400_000_000 + 13 * 3_600_000_000 +} + +fn split_row( + listing_id: i32, + ex_date: i32, + split_factor: f64, + cum_split_factor: f64, + cum_total_factor: f64, +) -> AdjFactorsParquetRow { + AdjFactorsParquetRow { + listing_id, + ex_date, + split_factor, + div_cash: 0.0, + div_currency: None, + cum_split_factor, + cum_total_factor, + known_at_micros: known_at_before(ex_date), + } +} + +fn div_row( + listing_id: i32, + ex_date: i32, + div_cash: f64, + div_currency: &'static str, + cum_split_factor: f64, + cum_total_factor: f64, +) -> AdjFactorsParquetRow { + AdjFactorsParquetRow { + listing_id, + ex_date, + split_factor: 1.0, + div_cash, + div_currency: Some(Cow::Borrowed(div_currency)), + cum_split_factor, + cum_total_factor, + known_at_micros: known_at_before(ex_date), + } +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let n = meta.row_group(rg).num_rows() as usize; + let g = reader.get_row_group(rg).expect("row group"); + let col = |i: usize| g.get_column_reader(i).expect("column reader"); + + let i32s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::Int32ColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected INT32"), + } + v + }; + let i64s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::Int64ColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected INT64"), + } + v + }; + let f64s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::DoubleColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected DOUBLE"), + } + v + }; + let opt_strs = |c: ColumnReader| -> Vec> { + let mut vals = Vec::new(); + let mut defs = Vec::new(); + match c { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, levels_read) = + r.read_records(n, Some(&mut defs), None, &mut vals).unwrap(); + assert_eq!(read, n); + assert_eq!(levels_read, n); + } + _ => panic!("expected BYTE_ARRAY"), + } + let mut vi = 0usize; + let mut res = Vec::with_capacity(n); + for d in defs { + match d { + 0 => res.push(None), + 1 => { + let s = std::str::from_utf8(vals[vi].data()).expect("utf8").to_string(); + vi += 1; + res.push(Some(s)); + } + other => panic!("unexpected def level {other}"), + } + } + assert_eq!(vi, vals.len()); + res + }; + + let listing_ids = i32s(col(0)); + let ex_dates = i32s(col(1)); + let split_factors = f64s(col(2)); + let div_cashes = f64s(col(3)); + let div_currencies = opt_strs(col(4)); + let cum_split_factors = f64s(col(5)); + let cum_total_factors = f64s(col(6)); + let known_ats = i64s(col(7)); + + for i in 0..n { + out.push(AdjFactorsParquetRow { + listing_id: listing_ids[i], + ex_date: ex_dates[i], + split_factor: split_factors[i], + div_cash: div_cashes[i], + div_currency: div_currencies[i].clone().map(Cow::Owned), + cum_split_factor: cum_split_factors[i], + cum_total_factor: cum_total_factors[i], + known_at_micros: known_ats[i], + }); + } + } + out +} + +fn assert_rows_bitwise(actual: &[AdjFactorsParquetRow], expected: &[AdjFactorsParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id"); + assert_eq!(a.ex_date, e.ex_date, "row {i} ex_date"); + assert_eq!( + a.split_factor.to_bits(), + e.split_factor.to_bits(), + "row {i} split_factor" + ); + assert_eq!(a.div_cash.to_bits(), e.div_cash.to_bits(), "row {i} div_cash"); + assert_eq!(a.div_currency, e.div_currency, "row {i} div_currency"); + assert_eq!( + a.cum_split_factor.to_bits(), + e.cum_split_factor.to_bits(), + "row {i} cum_split_factor" + ); + assert_eq!( + a.cum_total_factor.to_bits(), + e.cum_total_factor.to_bits(), + "row {i} cum_total_factor" + ); + assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at"); + } +} + +fn list_files(dir: &Path) -> Vec { + fn walk(root: &Path, dir: &Path, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + for entry in entries { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(root, &path, out); + } else { + out.push(path.strip_prefix(root).unwrap().display().to_string()); + } + } + } + let mut out = Vec::new(); + walk(dir, dir, &mut out); + out.sort(); + out +} + +#[test] +fn build_adj_factors_round_trip_matches_contract_schema_zstd_dict_and_bitwise_values() { + let tmp = TempDir::new("contract"); + let splits = vec![ + ( + 10i32, + SplitEvent { + ex_date: day(1969, 12, 31), + ratio: 2.0, + }, + ), + ( + 10i32, + SplitEvent { + ex_date: day(2021, 7, 20), + ratio: 4.0, + }, + ), + ( + 10i32, + SplitEvent { + ex_date: day(2024, 6, 10), + ratio: 10.0, + }, + ), + ( + 20i32, + SplitEvent { + ex_date: day(2025, 6, 18), + ratio: 0.05, + }, + ), + ]; + let dividends = vec![ + ( + 10i32, + DividendEvent { + ex_date: day(2024, 3, 6), + cash: 0.04, + currency: "USD".to_string(), + prev_close: Some(850.0), + prev_close_currency: Some("USD".to_string()), + }, + ), + ( + 10i32, + DividendEvent { + ex_date: day(2024, 6, 10), // same-day split + dividend + cash: 0.10, + currency: "USD".to_string(), + prev_close: Some(1200.0), + prev_close_currency: Some("USD".to_string()), + }, + ), + ( + 20i32, + DividendEvent { + ex_date: day(2025, 1, 15), + cash: 0.85, + currency: "CAD".to_string(), + prev_close: Some(75.0), + prev_close_currency: Some("CAD".to_string()), + }, + ), + ]; + + let built = build_adj_factors(splits, dividends).unwrap(); + assert_eq!(built.rows.len(), 6); + let rows: Vec = built + .rows + .iter() + .map(|r| AdjFactorsParquetRow::from_adj_row(r, known_at_before(r.ex_date))) + .collect(); + + let opts = AdjFactorsWriteOptions { + row_group_rows: 2, + ..AdjFactorsWriteOptions::default() + }; + let stats = write_adj_factors_dataset(&tmp.0, &rows, opts).unwrap(); + assert_eq!(stats.rows_written, 6); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 3); + + let path = part_path(&tmp.0); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + let file_schema = meta.file_metadata().schema(); + let public_schema = adj_factors_parquet_schema().unwrap(); + assert_eq!(file_schema, public_schema.as_ref()); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 8] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "ex_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "split_factor", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "div_cash", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "div_currency", + PhysicalType::BYTE_ARRAY, + Repetition::OPTIONAL, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "cum_split_factor", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "cum_total_factor", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ]; + + let fields = file_schema.get_fields(); + assert_eq!(fields.len(), 8); + for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + let f = &fields[idx]; + assert_eq!(f.name(), name); + assert_eq!(f.get_physical_type(), phys); + assert_eq!(f.get_basic_info().repetition(), rep); + assert_eq!(f.get_basic_info().logical_type_ref().cloned(), logical); + assert_eq!(f.get_basic_info().converted_type(), converted); + } + + assert_eq!(meta.num_row_groups(), 3); + let mut dict_seen_on_div_currency = false; + for rg in meta.row_groups() { + assert_eq!(rg.num_rows(), 2); + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} expected ZSTD, got {:?}", + col.column_path(), + col.compression() + ); + } + if rg + .column(4) + .encodings() + .any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)) + { + dict_seen_on_div_currency = true; + } + } + assert!( + dict_seen_on_div_currency, + "expected dictionary encoding on non-null div_currency column chunks" + ); + + let actual = read_rows(&path); + assert_rows_bitwise(&actual, &rows); + assert!(actual[0].div_currency.is_none()); + assert!(actual[1].div_currency.is_none()); + assert_eq!(actual[2].div_currency.as_deref(), Some("USD")); + assert_eq!(actual[3].div_currency.as_deref(), Some("USD")); + assert_eq!(actual[4].div_currency.as_deref(), Some("CAD")); + assert!(actual[5].div_currency.is_none()); + assert_eq!(list_files(&tmp.0), vec!["adj_factors/part.parquet"]); +} + +#[test] +fn row_group_boundaries_overwrite_empty_input_and_determinism() { + let tmp = TempDir::new("lifecycle"); + + // Empty input creates nothing in a fresh directory. + let fresh = tmp.0.join("fresh"); + let empty_stats = write_adj_factors_dataset( + &fresh, + std::iter::empty::(), + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_stats, AdjFactorsWriteStats::default()); + assert!(!fresh.exists()); + + // Exact row_group_rows and row_group_rows + 1. + let base = day(2024, 1, 2); + let rows_a: Vec = (0..5_i32) + .map(|i| { + if i % 2 == 0 { + split_row(1, base + i * 20, 2.0, 2.0, 2.0) + } else { + div_row(1, base + i * 20, 0.25, "USD", 1.0, 1.01) + } + }) + .collect(); + let opts = AdjFactorsWriteOptions { + row_group_rows: 4, + ..AdjFactorsWriteOptions::default() + }; + + let out_a = tmp.0.join("run-a"); + let out_b = tmp.0.join("run-b"); + let stats_a = write_adj_factors_dataset(&out_a, &rows_a, opts).unwrap(); + let stats_b = write_adj_factors_dataset(&out_b, &rows_a, opts).unwrap(); + assert_eq!(stats_a, stats_b); + assert_eq!(stats_a.rows_written, 5); + assert_eq!(stats_a.row_groups_written, 2); + assert_eq!( + fs::read(part_path(&out_a)).unwrap(), + fs::read(part_path(&out_b)).unwrap() + ); + + // Empty input over existing dataset preserves part.parquet byte-for-byte. + let before = fs::read(part_path(&out_a)).unwrap(); + let empty_over = write_adj_factors_dataset( + &out_a, + std::iter::empty::(), + opts, + ) + .unwrap(); + assert_eq!(empty_over, AdjFactorsWriteStats::default()); + assert_eq!(fs::read(part_path(&out_a)).unwrap(), before); + + // Overwrite replaces existing part.parquet cleanly. + let rows_new = vec![div_row(99, day(2025, 2, 14), 0.75, "CAD", 1.0, 1.015)]; + let stats_new = write_adj_factors_dataset(&out_a, &rows_new, opts).unwrap(); + assert_eq!(stats_new.rows_written, 1); + assert_eq!(stats_new.row_groups_written, 1); + assert_rows_bitwise(&read_rows(&part_path(&out_a)), &rows_new); + assert_eq!(list_files(&out_a), vec!["adj_factors/part.parquet"]); +} + +#[test] +fn typed_validation_errors_preserve_fresh_and_seeded_directories() { + let tmp = TempDir::new("validation"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 6, 15); + + type ErrorCheck = fn(&ParquetAdjError) -> bool; + let cases: Vec<(&str, Vec, ErrorCheck)> = vec![ + ( + "unsorted-listing", + vec![ + div_row(2, d1, 0.25, "USD", 1.0, 1.01), + div_row(1, d1, 0.25, "USD", 1.0, 1.01), + ], + |e| matches!(e, ParquetAdjError::UnsortedInput { .. }), + ), + ( + "unsorted-date", + vec![ + div_row(1, d2, 0.25, "USD", 1.0, 1.01), + div_row(1, d1, 0.25, "USD", 1.0, 1.01), + ], + |e| matches!(e, ParquetAdjError::UnsortedInput { .. }), + ), + ( + "duplicate-key", + vec![ + div_row(1, d1, 0.25, "USD", 1.0, 1.01), + div_row(1, d1, 0.50, "USD", 1.0, 1.02), + ], + |e| matches!(e, ParquetAdjError::DuplicateKey { .. }), + ), + ( + "ex-date-out-of-range", + vec![split_row(1, day(1899, 12, 31), 2.0, 2.0, 2.0)], + |e| { + matches!( + e, + ParquetAdjError::ExDateOutOfRange { + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + ( + "invalid-split-factor", + vec![split_row(1, d1, 0.0, 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidSplitFactor { .. }), + ), + ( + "invalid-div-cash", + vec![div_row(1, d1, -0.05, "USD", 1.0, 1.0)], + |e| matches!(e, ParquetAdjError::InvalidDivCash { .. }), + ), + ( + "missing-div-currency", + vec![AdjFactorsParquetRow { + div_cash: 0.25, + div_currency: None, + ..split_row(1, d1, 1.0, 1.0, 1.0) + }], + |e| matches!(e, ParquetAdjError::InvalidDivCurrency { .. }), + ), + ( + "invalid-cum-split", + vec![split_row(1, d1, 2.0, f64::NAN, 2.0)], + |e| matches!(e, ParquetAdjError::InvalidCumSplitFactor { .. }), + ), + ( + "invalid-cum-total", + vec![split_row(1, d1, 2.0, 2.0, 0.0)], + |e| matches!(e, ParquetAdjError::InvalidCumTotalFactor { .. }), + ), + ]; + + for (name, bad_rows, check) in cases { + let fresh = tmp.0.join(format!("fresh-{name}")); + let err = write_adj_factors_dataset(&fresh, &bad_rows, AdjFactorsWriteOptions::default()) + .unwrap_err(); + assert!(check(&err), "fresh '{name}' unexpected err: {err:?}"); + assert!(!part_path(&fresh).exists()); + + let seeded = tmp.0.join(format!("seeded-{name}")); + let seed = vec![div_row(1, d1, 0.25, "USD", 1.0, 1.01)]; + write_adj_factors_dataset(&seeded, &seed, AdjFactorsWriteOptions::default()).unwrap(); + let before = fs::read(part_path(&seeded)).unwrap(); + + let err2 = + write_adj_factors_dataset(&seeded, &bad_rows, AdjFactorsWriteOptions::default()) + .unwrap_err(); + assert!(check(&err2), "seeded '{name}' unexpected err: {err2:?}"); + assert_eq!(fs::read(part_path(&seeded)).unwrap(), before); + assert_eq!(list_files(&seeded), vec!["adj_factors/part.parquet"]); + } +} + +#[test] +fn concurrent_writers_serialize_and_publish_consistent_generation() { + let tmp = TempDir::new("concurrent"); + let out = Arc::new(tmp.0.clone()); + let barrier = Arc::new(Barrier::new(3)); + let base = day(2024, 1, 2); + + let handles: Vec<_> = (1..=3_i32) + .map(|gen_id| { + let out = Arc::clone(&out); + let barrier = Arc::clone(&barrier); + thread::spawn(move || { + let rows: Vec = (0..16_i32) + .map(|i| { + if i % 4 == 0 { + split_row(gen_id * 100, base + i * 10, 2.0, 2.0, 2.0) + } else { + div_row(gen_id * 100, base + i * 10, 0.25, "USD", 1.0, 1.01) + } + }) + .collect(); + barrier.wait(); + write_adj_factors_dataset( + out.as_path(), + &rows, + AdjFactorsWriteOptions { + row_group_rows: 4, + ..AdjFactorsWriteOptions::default() + }, + ) + }) + }) + .collect(); + + for h in handles { + let stats = h.join().unwrap().unwrap(); + assert_eq!(stats.rows_written, 16); + assert_eq!(stats.files_written, 1); + } + + let got = read_rows(&part_path(&tmp.0)); + assert_eq!(got.len(), 16); + let first_listing = got[0].listing_id; + assert!(matches!(first_listing, 100 | 200 | 300)); + assert!(got.iter().all(|r| r.listing_id == first_listing)); + assert_eq!(list_files(&tmp.0), vec!["adj_factors/part.parquet"]); +} + +#[test] +fn cli_bench_parquet_adj_reports_metrics_cleans_tmpdir_and_validates_args() { + let bin = env!("CARGO_BIN_EXE_curate-etl"); + let isolated_tmp = TempDir::new("cli-tmpdir"); + + let out = Command::new(bin) + .args(["bench-parquet-adj", "2000"]) + .env("TMPDIR", &isolated_tmp.0) + .output() + .expect("run curate-etl bench-parquet-adj"); + assert!( + out.status.success(), + "bench-parquet-adj failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(stdout.contains("curate-etl bench-parquet-adj"), "{stdout}"); + assert!(stdout.contains("rows=2000"), "{stdout}"); + assert!(stdout.contains("read_back_rows=2000"), "{stdout}"); + assert!(stdout.contains("files=1"), "{stdout}"); + assert!(stdout.contains("rows/s"), "{stdout}"); + assert!(stdout.contains("MB/s"), "{stdout}"); + assert!(stdout.contains("bytes/row"), "{stdout}"); + assert!(stdout.contains("compression="), "{stdout}"); + assert!( + list_files(&isolated_tmp.0).is_empty(), + "bench-parquet-adj must clean up its temp dir, left: {:?}", + list_files(&isolated_tmp.0) + ); + + // Invalid CLI args must fail with usage on stderr. + for bad in [ + &["bench-parquet-adj", "0"][..], + &["bench-parquet-adj", "-5"][..], + &["bench-parquet-adj", "abc"][..], + &["bench-parquet-adj", "10", "20"][..], + ] { + let res = Command::new(bin) + .args(bad) + .output() + .expect("run invalid cli"); + assert!( + !res.status.success(), + "expected failure for args {bad:?}" + ); + let stderr = String::from_utf8_lossy(&res.stderr); + assert!( + stderr.contains("bench-parquet-adj"), + "stderr usage should mention bench-parquet-adj: {stderr}" + ); + } +} diff --git a/tools/curate-etl/tests/parquet_adj_edge_contract.rs b/tools/curate-etl/tests/parquet_adj_edge_contract.rs new file mode 100644 index 00000000..2aa3b4d3 --- /dev/null +++ b/tools/curate-etl/tests/parquet_adj_edge_contract.rs @@ -0,0 +1,520 @@ +//! Edge-case contract tests for the public `adj_factors` Parquet writer (T-95 / M1.2m). +//! +//! Complements `parquet_adj_contract.rs` through the public API only: `ex_date` year +//! boundaries, `known_at` before/on/after `ex_date` (incl. negative pre-1970 and `i64::MAX`), +//! all-null `div_currency` row groups and >4,096-row mixed-null batch boundaries, extreme +//! positive subnormal/`MIN_POSITIVE`/`MAX` factors and `0.0` `div_cash`, `Cow::Owned` / +//! non-ASCII currency labels across row groups, late-stream failure of every validation +//! variant after flushed row groups + lock release for a retry, `zstd_level` bounds and +//! option-before-row precedence, and `Display`/`Error::source()` checks. + +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + write_adj_factors_dataset, ymd_to_epoch_days, AdjFactorsParquetRow, AdjFactorsWriteOptions, + AdjFactorsWriteStats, ParquetAdjError, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, +}; +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_DAY: i64 = 86_400_000_000; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-adj-edge-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn part_path(out: &Path) -> PathBuf { + out.join("adj_factors/part.parquet") +} + +fn opts(row_group_rows: usize) -> AdjFactorsWriteOptions { + AdjFactorsWriteOptions { + row_group_rows, + ..AdjFactorsWriteOptions::default() + } +} + +fn split_row(listing_id: i32, ex_date: i32, ratio: f64) -> AdjFactorsParquetRow { + AdjFactorsParquetRow { + listing_id, + ex_date, + split_factor: ratio, + div_cash: 0.0, + div_currency: None, + cum_split_factor: ratio, + cum_total_factor: ratio, + known_at_micros: (i64::from(ex_date) - 14).saturating_mul(MICROS_PER_DAY), + } +} + +fn div_row(listing_id: i32, ex_date: i32, cash: f64, currency: &'static str) -> AdjFactorsParquetRow { + AdjFactorsParquetRow { + listing_id, + ex_date, + split_factor: 1.0, + div_cash: cash, + div_currency: Some(Cow::Borrowed(currency)), + cum_split_factor: 1.0, + cum_total_factor: 1.01, + known_at_micros: (i64::from(ex_date) - 14).saturating_mul(MICROS_PER_DAY), + } +} + +fn list_files(dir: &Path) -> Vec { + let Ok(entries) = fs::read_dir(dir) else { + return Vec::new(); + }; + let mut names: Vec = entries + .map(|e| { + e.expect("dir entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .collect(); + names.sort(); + names +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let rg_reader = reader.get_row_group(rg).expect("rg"); + let n = meta.row_group(rg).num_rows() as usize; + let i32s = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::Int32ColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected INT32 at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + v + }; + let i64s = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::Int64ColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected INT64 at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + v + }; + let f64s = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::DoubleColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected DOUBLE at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + v + }; + let opt_strs = |idx: usize| -> Vec> { + let mut vals = Vec::new(); + let mut defs = Vec::new(); + let ColumnReader::ByteArrayColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected BYTE_ARRAY at {idx}"); + }; + let (read, _, levels_read) = r + .read_records(n, Some(&mut defs), None, &mut vals) + .expect("read"); + assert_eq!(read, n); + assert_eq!(levels_read, n); + let mut vi = 0usize; + let mut res = Vec::with_capacity(n); + for d in defs { + match d { + 0 => res.push(None), + 1 => { + let s = String::from_utf8(vals[vi].data().to_vec()).expect("utf8"); + vi += 1; + res.push(Some(s)); + } + other => panic!("unexpected def level {other}"), + } + } + assert_eq!(vi, vals.len()); + res + }; + + let (lid, ed, sf, dc, dcur, csf, ctf, ka) = ( + i32s(0), + i32s(1), + f64s(2), + f64s(3), + opt_strs(4), + f64s(5), + f64s(6), + i64s(7), + ); + for i in 0..n { + out.push(AdjFactorsParquetRow { + listing_id: lid[i], + ex_date: ed[i], + split_factor: sf[i], + div_cash: dc[i], + div_currency: dcur[i].clone().map(Cow::Owned), + cum_split_factor: csf[i], + cum_total_factor: ctf[i], + known_at_micros: ka[i], + }); + } + } + out +} + +fn assert_bitwise(actual: &[AdjFactorsParquetRow], expected: &[AdjFactorsParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id"); + assert_eq!(a.ex_date, e.ex_date, "row {i} ex_date"); + assert_eq!( + a.split_factor.to_bits(), + e.split_factor.to_bits(), + "row {i} split_factor" + ); + assert_eq!(a.div_cash.to_bits(), e.div_cash.to_bits(), "row {i} div_cash"); + assert_eq!(a.div_currency, e.div_currency, "row {i} div_currency"); + assert_eq!( + a.cum_split_factor.to_bits(), + e.cum_split_factor.to_bits(), + "row {i} cum_split_factor" + ); + assert_eq!( + a.cum_total_factor.to_bits(), + e.cum_total_factor.to_bits(), + "row {i} cum_total_factor" + ); + assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at"); + } +} + +#[test] +fn ex_date_year_boundaries_accept_1900_to_2200_and_reject_outside() { + let tmp = TempDir::new("ex-date-bounds"); + let valid_rows = vec![ + split_row(1, day(1900, 1, 1), 2.0), + split_row(1, day(1969, 12, 31), 3.0), + div_row(1, day(2200, 12, 31), 0.50, "USD"), + ]; + let stats = write_adj_factors_dataset(tmp.0.as_path(), &valid_rows, opts(2)).unwrap(); + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.row_groups_written, 2); + assert_bitwise(&read_rows(&part_path(&tmp.0)), &valid_rows); + + for bad_date in [day(1899, 12, 31), day(2201, 1, 1), i32::MIN, i32::MAX] { + let bad = vec![split_row(1, bad_date, 2.0)]; + let err = write_adj_factors_dataset(tmp.0.join("bad"), &bad, opts(2)).unwrap_err(); + assert!( + matches!( + err, + ParquetAdjError::ExDateOutOfRange { + ex_date, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } if ex_date == bad_date + ), + "expected ExDateOutOfRange for {bad_date}, got {err:?}" + ); + } +} + +#[test] +fn known_at_before_on_and_after_ex_date_all_round_trip_bitwise() { + let tmp = TempDir::new("known-at-policy"); + let d_pre = day(1969, 6, 15); + let d_now = day(2024, 6, 10); + let rows = vec![ + AdjFactorsParquetRow { + known_at_micros: i64::from(d_pre - 21) * MICROS_PER_DAY, // negative pre-1970 declared date + ..split_row(1, d_pre, 2.0) + }, + AdjFactorsParquetRow { + known_at_micros: i64::from(d_now - 14) * MICROS_PER_DAY, // before ex_date + ..div_row(1, d_now, 0.25, "USD") + }, + AdjFactorsParquetRow { + known_at_micros: i64::from(d_now + 1) * MICROS_PER_DAY, // exactly on ex_date 00:00 UTC + ..div_row(1, d_now + 1, 0.25, "USD") + }, + AdjFactorsParquetRow { + known_at_micros: i64::MAX, // far after ex_date + ..div_row(1, d_now + 2, 0.25, "CAD") + }, + ]; + + let stats = write_adj_factors_dataset(tmp.0.as_path(), &rows, opts(2)).unwrap(); + assert_eq!(stats.rows_written, 4); + assert_bitwise(&read_rows(&part_path(&tmp.0)), &rows); +} + +#[test] +fn all_null_and_large_mixed_null_div_currency_batches_round_trip() { + let tmp = TempDir::new("large-opt-str"); + let base = day(2000, 1, 3); + + // 100% null row group + let all_null: Vec = (0..128_i32) + .map(|i| split_row(1, base + i, 2.0)) + .collect(); + let out_null = tmp.0.join("all-null"); + let stats_null = write_adj_factors_dataset(&out_null, &all_null, opts(64)).unwrap(); + assert_eq!(stats_null.rows_written, 128); + assert_eq!(stats_null.row_groups_written, 2); + assert_bitwise(&read_rows(&part_path(&out_null)), &all_null); + + // >4,096 rows with alternating None / USD / CAD crossing internal batch boundary + let mixed: Vec = (0..4_500_i32) + .map(|i| { + let lid = (i / 500) + 1; + let ed = base + (i % 500); + match i % 3 { + 0 => split_row(lid, ed, 2.0), + 1 => div_row(lid, ed, 0.20, "USD"), + _ => div_row(lid, ed, 0.35, "CAD"), + } + }) + .collect(); + let out_mixed = tmp.0.join("mixed"); + let stats_mixed = + write_adj_factors_dataset(&out_mixed, &mixed, AdjFactorsWriteOptions::default()).unwrap(); + assert_eq!(stats_mixed.rows_written, 4_500); + assert_eq!(stats_mixed.row_groups_written, 1); + assert_bitwise(&read_rows(&part_path(&out_mixed)), &mixed); +} + +#[test] +fn extreme_positive_factors_zero_div_cash_and_owned_non_ascii_currencies_round_trip() { + let tmp = TempDir::new("extreme-floats-owned"); + let d = day(2024, 6, 3); + let tiny = f64::from_bits(1); // smallest positive subnormal + let rows = vec![ + AdjFactorsParquetRow { + listing_id: 1, + ex_date: d, + split_factor: tiny, + div_cash: 0.0, + div_currency: None, + cum_split_factor: f64::MIN_POSITIVE, + cum_total_factor: f64::MAX, + known_at_micros: i64::from(d) * MICROS_PER_DAY, + }, + AdjFactorsParquetRow { + listing_id: 1, + ex_date: d + 1, + split_factor: f64::MAX, + div_cash: 0.0, + div_currency: Some(Cow::Owned("EUR-€".to_owned())), + cum_split_factor: f64::MAX, + cum_total_factor: tiny, + known_at_micros: i64::from(d + 1) * MICROS_PER_DAY, + }, + AdjFactorsParquetRow { + listing_id: 2, + ex_date: d, + split_factor: 1.0, + div_cash: 0.1 + 0.2, + div_currency: Some(Cow::Owned("JPY-¥".to_owned())), + cum_split_factor: 1.0, + cum_total_factor: 1.0030000000000001, + known_at_micros: i64::from(d - 7) * MICROS_PER_DAY, + }, + ]; + + let stats = write_adj_factors_dataset(tmp.0.as_path(), rows.clone(), opts(2)).unwrap(); + assert_eq!( + stats, + AdjFactorsWriteStats { + rows_written: 3, + files_written: 1, + row_groups_written: 2, + bytes_written: fs::metadata(part_path(&tmp.0)).unwrap().len(), + } + ); + assert_bitwise(&read_rows(&part_path(&tmp.0)), &rows); +} + +#[test] +fn every_validation_variant_late_in_stream_preserves_existing_file_and_releases_lock() { + let tmp = TempDir::new("late-stream"); + let base = day(2024, 1, 2); + let seed = vec![div_row(1, base, 0.50, "USD")]; + write_adj_factors_dataset(tmp.0.as_path(), &seed, opts(2)).unwrap(); + let before = fs::read(part_path(&tmp.0)).unwrap(); + + // 4 valid prefix rows => 2 flushed row groups at row_group_rows = 2. + let prefix = || { + vec![ + split_row(1, base, 2.0), + div_row(1, base + 10, 0.25, "USD"), + div_row(1, base + 20, 0.30, "CAD"), + split_row(1, base + 30, 1.5), + ] + }; + + type ErrorCheck = fn(&ParquetAdjError) -> bool; + let bad_tails: Vec<(&str, AdjFactorsParquetRow, ErrorCheck)> = vec![ + ( + "unsorted", + div_row(1, base + 25, 0.25, "USD"), + |e| matches!(e, ParquetAdjError::UnsortedInput { .. }), + ), + ( + "duplicate", + div_row(1, base + 30, 0.25, "USD"), + |e| matches!(e, ParquetAdjError::DuplicateKey { .. }), + ), + ( + "ex_date_oor", + split_row(1, day(2201, 1, 1), 2.0), + |e| matches!(e, ParquetAdjError::ExDateOutOfRange { .. }), + ), + ( + "split_factor", + split_row(1, base + 40, -1.0), + |e| matches!(e, ParquetAdjError::InvalidSplitFactor { .. }), + ), + ( + "div_cash", + div_row(1, base + 40, -0.01, "USD"), + |e| matches!(e, ParquetAdjError::InvalidDivCash { .. }), + ), + ( + "div_currency", + AdjFactorsParquetRow { + div_cash: 0.25, + div_currency: None, + ..split_row(1, base + 40, 1.0) + }, + |e| matches!(e, ParquetAdjError::InvalidDivCurrency { .. }), + ), + ( + "cum_split", + AdjFactorsParquetRow { + cum_split_factor: 0.0, + ..split_row(1, base + 40, 2.0) + }, + |e| matches!(e, ParquetAdjError::InvalidCumSplitFactor { .. }), + ), + ( + "cum_total", + AdjFactorsParquetRow { + cum_total_factor: f64::INFINITY, + ..split_row(1, base + 40, 2.0) + }, + |e| matches!(e, ParquetAdjError::InvalidCumTotalFactor { .. }), + ), + ]; + + for (label, tail, check) in bad_tails { + let mut rows = prefix(); + rows.push(tail); + let err = write_adj_factors_dataset(tmp.0.as_path(), &rows, opts(2)).unwrap_err(); + assert!(check(&err), "late case '{label}' got {err:?}"); + assert!(!err.to_string().is_empty()); + assert!(StdError::source(&err).is_none()); + assert_eq!(fs::read(part_path(&tmp.0)).unwrap(), before); + assert_eq!( + list_files(&tmp.0.join("adj_factors")), + vec!["part.parquet"] + ); + } + + // Lock was released cleanly, so a subsequent valid write succeeds. + let ok = vec![div_row(2, base + 100, 0.90, "CAD")]; + let stats = write_adj_factors_dataset(tmp.0.as_path(), &ok, opts(2)).unwrap(); + assert_eq!(stats.rows_written, 1); + assert_bitwise(&read_rows(&part_path(&tmp.0)), &ok); +} + +#[test] +fn zstd_level_bounds_and_option_before_row_precedence() { + let tmp = TempDir::new("zstd-bounds"); + let rows = vec![div_row(1, day(2024, 3, 15), 0.25, "USD")]; + + for level in [1, 22] { + let out = tmp.0.join(format!("lvl-{level}")); + let stats = write_adj_factors_dataset( + &out, + &rows, + AdjFactorsWriteOptions { + row_group_rows: 10, + zstd_level: level, + }, + ) + .unwrap(); + assert_eq!(stats.rows_written, 1); + let reader = SerializedFileReader::new(File::open(part_path(&out)).unwrap()).unwrap(); + for col in reader.metadata().row_group(0).columns() { + assert!(matches!(col.compression(), Compression::ZSTD(_))); + } + } + + // Option validation runs before row validation (even on a bad row). + let bad_row = vec![split_row(1, day(2024, 3, 15), -5.0)]; + for bad_level in [23, i32::MAX] { + let err = write_adj_factors_dataset( + tmp.0.join("bad"), + &bad_row, + AdjFactorsWriteOptions { + row_group_rows: 10, + zstd_level: bad_level, + }, + ) + .unwrap_err(); + assert!( + matches!(err, ParquetAdjError::InvalidZstdLevel { level } if level == bad_level), + "expected InvalidZstdLevel({bad_level}), got {err:?}" + ); + assert!(!err.to_string().is_empty()); + assert!(StdError::source(&err).is_none()); + } + + let err_rg = write_adj_factors_dataset( + tmp.0.join("bad"), + &bad_row, + AdjFactorsWriteOptions { + row_group_rows: 0, + zstd_level: 3, + }, + ) + .unwrap_err(); + assert!(matches!(err_rg, ParquetAdjError::InvalidRowGroupRows)); + assert!(!err_rg.to_string().is_empty()); + assert!(StdError::source(&err_rg).is_none()); +} diff --git a/tools/curate-etl/tests/parquet_adj_qa_contract.rs b/tools/curate-etl/tests/parquet_adj_qa_contract.rs new file mode 100644 index 00000000..09f7b729 --- /dev/null +++ b/tools/curate-etl/tests/parquet_adj_qa_contract.rs @@ -0,0 +1,475 @@ +//! QA contract tests for the public `adj_factors` Parquet writer (T-95 / M1.2m). +//! +//! Covers gaps left by `parquet_adj_contract.rs` / `parquet_adj_edge_contract.rs`: +//! - streaming proof: a lazy iterator observes flushed row-group bytes in the staging file +//! before it yields the remaining rows (a collect-then-write writer would fail); +//! - `div_currency` null patterns that land exactly on the 4,096-row string batch boundary; +//! - per-row-group interner reset: currencies that change between row groups keep their labels; +//! - seeded randomized round-trip across several `row_group_rows` values, checking bit-exact +//! values, null positions and `ceil(n / row_group_rows)` row groups in stats and footer. + +use std::borrow::Cow; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + write_adj_factors_dataset, ymd_to_epoch_days, AdjFactorsParquetRow, AdjFactorsWriteOptions, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_DAY: i64 = 86_400_000_000; +/// Mirrors `parquet_publish::STRING_WRITE_BATCH_ROWS` (crate-private). +const STRING_BATCH: usize = 4_096; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-adj-qa-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// Deterministic SplitMix64 (fixed seed per test). +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// Uniform in `[1.0, 2.0)` with a random 52-bit mantissa (incompressible). + fn factor(&mut self) -> f64 { + f64::from_bits(0x3FF0_0000_0000_0000 | (self.next_u64() >> 12)) + } +} + +fn base_day() -> i32 { + ymd_to_epoch_days(1990, 1, 2).expect("valid date") +} + +fn part_path(out: &Path) -> PathBuf { + out.join("adj_factors/part.parquet") +} + +fn opts(row_group_rows: usize) -> AdjFactorsWriteOptions { + AdjFactorsWriteOptions { + row_group_rows, + ..AdjFactorsWriteOptions::default() + } +} + +/// Row `i` of a single listing; `currency = None` makes it split-only. +fn row(i: usize, currency: Option>, rng: &mut Rng) -> AdjFactorsParquetRow { + let ex_date = base_day() + i32::try_from(i).expect("index fits i32"); + let (split_factor, div_cash) = match currency { + None => (rng.factor(), 0.0), + Some(_) => (1.0, rng.factor() - 1.0 + 0.01), + }; + AdjFactorsParquetRow { + listing_id: 7, + ex_date, + split_factor, + div_cash, + div_currency: currency, + cum_split_factor: rng.factor(), + cum_total_factor: rng.factor(), + known_at_micros: (i64::from(ex_date) - 14) * MICROS_PER_DAY, + } +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let rg_reader = reader.get_row_group(rg).expect("rg"); + let n = meta.row_group(rg).num_rows() as usize; + let i32s = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::Int32ColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected INT32 at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + v + }; + let i64s = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::Int64ColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected INT64 at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + v + }; + let f64s = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::DoubleColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected DOUBLE at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + v + }; + let opt_strs = |idx: usize| -> Vec> { + let mut vals = Vec::new(); + let mut defs = Vec::new(); + let ColumnReader::ByteArrayColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected BYTE_ARRAY at {idx}"); + }; + let (read, _, levels_read) = r + .read_records(n, Some(&mut defs), None, &mut vals) + .expect("read"); + assert_eq!(read, n); + assert_eq!(levels_read, n); + let mut vi = 0usize; + let mut res = Vec::with_capacity(n); + for d in defs { + match d { + 0 => res.push(None), + 1 => { + res.push(Some( + String::from_utf8(vals[vi].data().to_vec()).expect("utf8"), + )); + vi += 1; + } + other => panic!("unexpected def level {other}"), + } + } + assert_eq!(vi, vals.len()); + res + }; + + let (lid, ed, sf, dc, dcur, csf, ctf, ka) = ( + i32s(0), + i32s(1), + f64s(2), + f64s(3), + opt_strs(4), + f64s(5), + f64s(6), + i64s(7), + ); + for i in 0..n { + out.push(AdjFactorsParquetRow { + listing_id: lid[i], + ex_date: ed[i], + split_factor: sf[i], + div_cash: dc[i], + div_currency: dcur[i].clone().map(Cow::Owned), + cum_split_factor: csf[i], + cum_total_factor: ctf[i], + known_at_micros: ka[i], + }); + } + } + out +} + +fn assert_bitwise(actual: &[AdjFactorsParquetRow], expected: &[AdjFactorsParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id"); + assert_eq!(a.ex_date, e.ex_date, "row {i} ex_date"); + assert_eq!( + a.split_factor.to_bits(), + e.split_factor.to_bits(), + "row {i} split" + ); + assert_eq!( + a.div_cash.to_bits(), + e.div_cash.to_bits(), + "row {i} div_cash" + ); + assert_eq!(a.div_currency, e.div_currency, "row {i} div_currency"); + assert_eq!( + a.cum_split_factor.to_bits(), + e.cum_split_factor.to_bits(), + "row {i} cum_split" + ); + assert_eq!( + a.cum_total_factor.to_bits(), + e.cum_total_factor.to_bits(), + "row {i} cum_total" + ); + assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at"); + } +} + +fn row_group_sizes(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + reader + .metadata() + .row_groups() + .iter() + .map(|rg| rg.num_rows()) + .collect() +} + +fn staging_bytes(adj_dir: &Path) -> u64 { + let Ok(entries) = fs::read_dir(adj_dir) else { + return 0; + }; + entries + .map(|e| e.expect("dir entry")) + .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp")) + .map(|e| e.metadata().map(|m| m.len()).unwrap_or(0)) + .sum() +} + +/// Lazy source that records the staging-file size each time a new row group starts. +struct ObservingIter { + adj_dir: PathBuf, + total: usize, + row_group_rows: usize, + next_idx: usize, + rng: Rng, + observed_at_group_start: Vec, +} + +impl Iterator for ObservingIter { + type Item = AdjFactorsParquetRow; + + fn next(&mut self) -> Option { + if self.next_idx >= self.total { + return None; + } + if self.next_idx % self.row_group_rows == 0 { + self.observed_at_group_start + .push(staging_bytes(&self.adj_dir)); + } + let currency = if self.next_idx % 3 == 0 { + None + } else { + Some(Cow::Borrowed("USD")) + }; + let r = row(self.next_idx, currency, &mut self.rng); + self.next_idx += 1; + Some(r) + } +} + +#[test] +fn row_groups_are_flushed_to_staging_before_remaining_rows_are_pulled() { + // Arrange: 3 row groups of 20,000 rows with random-mantissa doubles so each flushed + // group (~4 x 160 KB of DOUBLE pages) exceeds the 64 KiB BufWriter and reaches disk. + let tmp = TempDir::new("streaming"); + let row_group_rows = 20_000; + let mut iter = ObservingIter { + adj_dir: tmp.0.join("adj_factors"), + total: 3 * row_group_rows, + row_group_rows, + next_idx: 0, + rng: Rng(0x0A0D_1A55_0000_0001), + observed_at_group_start: Vec::new(), + }; + + // Act: drive the writer through `&mut` so the observations survive. + let stats = write_adj_factors_dataset(&tmp.0, iter.by_ref(), opts(row_group_rows)).unwrap(); + + // Assert + assert_eq!(stats.rows_written, 3 * row_group_rows); + assert_eq!(stats.row_groups_written, 3); + let obs = &iter.observed_at_group_start; + assert_eq!(obs.len(), 3, "one observation per row-group start"); + assert!( + obs[1] > 100_000, + "row group 1 must be on disk before row group 2 is pulled; staging had {} bytes", + obs[1] + ); + assert!( + obs[2] > obs[1] + 100_000, + "row group 2 must be on disk before row group 3 is pulled; observed {obs:?}" + ); + assert!( + stats.bytes_written > obs[2], + "final file must contain the last row group and footer" + ); + assert_eq!( + row_group_sizes(&part_path(&tmp.0)), + vec![20_000, 20_000, 20_000] + ); +} + +#[test] +fn null_runs_aligned_to_4096_string_batch_boundary_round_trip() { + // Each case is a null pattern (true = Some) inside a single row group. + let n = STRING_BATCH; + let cases: Vec<(&str, Vec)> = vec![ + ("4096-null-then-1-some", (0..=n).map(|i| i == n).collect()), + ("1-some-then-4096-null", (0..=n).map(|i| i == 0).collect()), + ( + "4096-some-then-4096-null-then-1-some", + (0..=2 * n).map(|i| i < n || i == 2 * n).collect(), + ), + ("exactly-4096-null", vec![false; n]), + ("exactly-8192-some", vec![true; 2 * n]), + ( + "null-straddles-boundary", + (0..2 * n).map(|i| !(n - 2..n + 2).contains(&i)).collect(), + ), + ]; + + for (label, pattern) in cases { + // Arrange + let tmp = TempDir::new(label); + let mut rng = Rng(0x0A0D_1A55_0000_0002); + let rows: Vec = pattern + .iter() + .enumerate() + .map(|(i, &some)| { + let cur = some.then_some(Cow::Borrowed(if i % 2 == 0 { "USD" } else { "CAD" })); + row(i, cur, &mut rng) + }) + .collect(); + + // Act + let stats = write_adj_factors_dataset(&tmp.0, &rows, opts(1_000_000)).unwrap(); + + // Assert + assert_eq!(stats.rows_written, rows.len(), "{label}"); + assert_eq!(stats.row_groups_written, 1, "{label}"); + assert_bitwise(&read_rows(&part_path(&tmp.0)), &rows); + } +} + +#[test] +fn currency_labels_survive_interner_reset_between_row_groups() { + // Arrange: row group 1 interns [USD, CAD]; row group 2 starts with EUR then CAD then + // GBP, so stale ids from group 1 would surface as the wrong label in group 2. + let tmp = TempDir::new("interner"); + let mut rng = Rng(0x0A0D_1A55_0000_0003); + let labels: [Option<&'static str>; 8] = [ + Some("USD"), + Some("CAD"), + None, + Some("USD"), + Some("EUR"), + Some("CAD"), + None, + Some("GBP"), + ]; + let rows: Vec = labels + .iter() + .enumerate() + .map(|(i, l)| row(i, l.map(Cow::Borrowed), &mut rng)) + .collect(); + + // Act + let stats = write_adj_factors_dataset(&tmp.0, &rows, opts(4)).unwrap(); + + // Assert + assert_eq!(stats.row_groups_written, 2); + let back = read_rows(&part_path(&tmp.0)); + let back_labels: Vec> = back.iter().map(|r| r.div_currency.as_deref()).collect(); + assert_eq!(back_labels, labels.to_vec()); + assert_bitwise(&back, &rows); +} + +#[test] +fn seeded_random_streams_round_trip_with_expected_row_group_layout() { + let currencies = ["USD", "CAD", "EUR", "GBP", "CHF"]; + for (case, &(total, row_group_rows)) in [ + (1usize, 1usize), + (17, 4), + (999, 1000), + (1000, 1000), + (1001, 1000), + (9_000, 4_097), + (12_289, 4_096), + ] + .iter() + .enumerate() + { + // Arrange: seeded mix of split-only (None), dividend-only and combined rows across + // multiple listings, strictly ascending by (listing_id, ex_date). + let tmp = TempDir::new(&format!("random-{case}")); + let mut rng = Rng(0x0A0D_1A55_1000_0000 + case as u64); + let mut rows = Vec::with_capacity(total); + let mut listing_id = 1i32; + let mut ex_date = base_day(); + for _ in 0..total { + let r = rng.next_u64(); + if r % 50 == 0 { + listing_id += 1 + ((r >> 8) % 3) as i32; + ex_date = base_day() + ((r >> 16) % 30) as i32; + } else { + ex_date += 1 + ((r >> 24) % 5) as i32; + } + let kind = (r >> 32) % 10; + let currency = currencies[((r >> 40) as usize) % currencies.len()]; + let (split_factor, div_cash, div_currency) = match kind { + 0 => (rng.factor(), 0.0, None), + 1 => (rng.factor(), rng.factor(), Some(Cow::Borrowed(currency))), + _ => ( + 1.0, + rng.factor() - 1.0 + 0.01, + Some(Cow::Borrowed(currency)), + ), + }; + rows.push(AdjFactorsParquetRow { + listing_id, + ex_date, + split_factor, + div_cash, + div_currency, + cum_split_factor: rng.factor(), + cum_total_factor: rng.factor(), + known_at_micros: (i64::from(ex_date) - ((r >> 48) % 30) as i64) * MICROS_PER_DAY, + }); + } + + // Act + let stats = write_adj_factors_dataset(&tmp.0, rows.iter(), opts(row_group_rows)).unwrap(); + + // Assert + let expected_groups = total.div_ceil(row_group_rows); + assert_eq!(stats.rows_written, total, "case {case}"); + assert_eq!(stats.row_groups_written, expected_groups, "case {case}"); + let path = part_path(&tmp.0); + assert_eq!( + fs::metadata(&path).unwrap().len(), + stats.bytes_written, + "case {case}" + ); + let sizes = row_group_sizes(&path); + assert_eq!(sizes.len(), expected_groups, "case {case}"); + let (last, full) = sizes.split_last().unwrap(); + assert!( + full.iter().all(|&s| s == row_group_rows as i64), + "case {case}: {sizes:?}" + ); + assert_eq!( + *last as usize, + total - row_group_rows * (expected_groups - 1), + "case {case}" + ); + assert_bitwise(&read_rows(&path), &rows); + } +} diff --git a/tools/curate-etl/tests/parquet_corporate_actions_qa_contract.rs b/tools/curate-etl/tests/parquet_corporate_actions_qa_contract.rs new file mode 100644 index 00000000..af3db1c3 --- /dev/null +++ b/tools/curate-etl/tests/parquet_corporate_actions_qa_contract.rs @@ -0,0 +1,779 @@ +//! QA contract tests for the public `corporate_actions` Parquet writer (T-96 / M1.2n). +//! +//! Exercises only the public crate API (`curate_etl::*`) and covers gaps left by the in-crate +//! unit tests: +//! - seeded randomized round-trip of all four kinds across several `row_group_rows` values +//! (including 1 and the 4,096-row string batch boundary), bit-exact values and null positions +//! for every optional column, and `ceil(n / row_group_rows)` row groups in stats and footer; +//! - streaming proof: flushed row groups reach the staging file before later rows are pulled; +//! - `build_corporate_actions` -> `from_corporate_action_row` -> writer end-to-end with all +//! kinds, a same-day regular + special dividend, and known_at derived from `known_at_date`; +//! - currency labels survive the per-row-group interner reset; +//! - a late failure after several flushed row groups preserves a seeded `part.parquet` +//! byte-identically and leaves no `.tmp`/`.bak`/`.write.lock` behind; +//! - invalid options are rejected using finite probe iterators that must never be polled. + +use std::borrow::Cow; +use std::cell::Cell; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + build_corporate_actions, write_corporate_actions_dataset, ymd_to_epoch_days, + CorporateActionKind, CorporateActionsParquetRow, CorporateActionsWriteOptions, + DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, ParquetCorporateActionsError, + SplitActionEvent, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_DAY: i64 = 86_400_000_000; +/// Mirrors `parquet_publish::STRING_WRITE_BATCH_ROWS` (crate-private). +const STRING_BATCH: usize = 4_096; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-ca-qa-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// Deterministic SplitMix64 (fixed seed per test). +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// Uniform in `(0, 1]` with a random mantissa. + fn unit_open(&mut self) -> f64 { + ((self.next_u64() >> 11) as f64 + 1.0) / (1u64 << 53) as f64 + } +} + +fn days(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn opts(row_group_rows: usize) -> CorporateActionsWriteOptions { + CorporateActionsWriteOptions { + row_group_rows, + ..CorporateActionsWriteOptions::default() + } +} + +fn dataset_dir(out: &Path) -> PathBuf { + out.join("corporate_actions") +} + +fn part_path(out: &Path) -> PathBuf { + dataset_dir(out).join("part.parquet") +} + +fn leftover_transients(out: &Path) -> Vec { + let Ok(entries) = fs::read_dir(dataset_dir(out)) else { + return Vec::new(); + }; + entries + .map(|e| { + e.expect("dir entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .filter(|name| name != "part.parquet") + .collect() +} + +fn staging_bytes(dir: &Path) -> u64 { + let Ok(entries) = fs::read_dir(dir) else { + return 0; + }; + entries + .map(|e| e.expect("dir entry")) + .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp")) + .map(|e| e.metadata().map(|m| m.len()).unwrap_or(0)) + .sum() +} + +/// Generates a valid, sorted row for index `i` (listing changes every 8 rows, ex_date steps +/// every 2 rows so consecutive rows can share `(listing_id, ex_date)`). +fn random_row(i: usize, rng: &mut Rng) -> CorporateActionsParquetRow { + let listing_id = 1 + (i / 8) as i32; + let ex_date = days(1995, 1, 2) + ((i % 8) / 2) as i32 * 7; + let r = rng.next_u64(); + let known_at_micros = i64::from(ex_date) * MICROS_PER_DAY + (r % MICROS_PER_DAY as u64) as i64; + // Second row of each (listing_id, ex_date) pair must not sort below the first; use kinds + // with non-decreasing ordinals inside the pair. + let in_pair_second = i % 2 == 1; + let kind_roll = r % 4; + let kind = match (in_pair_second, kind_roll) { + (false, 0) => CorporateActionKind::Split, + (false, _) => CorporateActionKind::Dividend, + (true, 0) | (true, 1) => CorporateActionKind::Dividend, + (true, 2) => CorporateActionKind::OtcDelistTransfer, + (true, _) => CorporateActionKind::Delisting, + }; + let decl = (r >> 8) % 3; + let (declared_date, known_at_source) = match kind { + CorporateActionKind::Split | CorporateActionKind::Dividend => match decl { + 0 => ( + Some(ex_date - 1 - ((r >> 16) % 30) as i32), + KnownAtSource::DeclaredDate, + ), + 1 => (None, KnownAtSource::ExDateFallback), + _ => (Some(ex_date + 2), KnownAtSource::ExDateFallback), + }, + _ => ( + if decl == 0 { Some(ex_date - 5) } else { None }, + KnownAtSource::DelistDate, + ), + }; + let mut row = CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date, + kind, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: None, + known_at_micros, + known_at_source, + }; + match kind { + CorporateActionKind::Split => row.ratio = Some(rng.unit_open() * 20.0), + CorporateActionKind::Dividend => { + row.cash_amount = Some(rng.unit_open() * 3.0); + row.currency = Some(Cow::Borrowed(if (r >> 24) & 1 == 0 { + "USD" + } else { + "CAD" + })); + } + CorporateActionKind::OtcDelistTransfer => { + row.successor_listing_id = Some(listing_id + 1_000_000 + ((r >> 32) % 5) as i32); + } + CorporateActionKind::Delisting => row.terminal_return = Some(-rng.unit_open() + 0.0), + } + row +} + +fn parse_kind(s: &str) -> CorporateActionKind { + match s { + "split" => CorporateActionKind::Split, + "dividend" => CorporateActionKind::Dividend, + "otc_delist_transfer" => CorporateActionKind::OtcDelistTransfer, + "delisting" => CorporateActionKind::Delisting, + other => panic!("unexpected kind {other:?}"), + } +} + +fn parse_source(s: &str) -> KnownAtSource { + match s { + "declared_date" => KnownAtSource::DeclaredDate, + "ex_date_fallback" => KnownAtSource::ExDateFallback, + "delist_date" => KnownAtSource::DelistDate, + other => panic!("unexpected known_at_source {other:?}"), + } +} + +/// Expands values + definition levels into `Option` per record. +fn expand(vals: Vec, defs: Vec, n: usize) -> Vec> { + assert_eq!(defs.len(), n, "one definition level per record"); + let mut vi = 0usize; + let out: Vec> = defs + .iter() + .map(|&d| match d { + 0 => None, + 1 => { + vi += 1; + Some(vals[vi - 1].clone()) + } + other => panic!("unexpected def level {other}"), + }) + .collect(); + assert_eq!(vi, vals.len(), "every value consumed exactly once"); + out +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let rg_reader = reader.get_row_group(rg).expect("rg"); + let n = meta.row_group(rg).num_rows() as usize; + let i32s = |idx: usize| -> Vec> { + let (mut v, mut d) = (Vec::new(), Vec::new()); + let ColumnReader::Int32ColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected INT32 at {idx}"); + }; + r.read_records(n, Some(&mut d), None, &mut v).expect("read"); + if d.is_empty() { + assert_eq!(v.len(), n); + v.into_iter().map(Some).collect() + } else { + expand(v, d, n) + } + }; + let f64s = |idx: usize| -> Vec> { + let (mut v, mut d) = (Vec::new(), Vec::new()); + let ColumnReader::DoubleColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected DOUBLE at {idx}"); + }; + r.read_records(n, Some(&mut d), None, &mut v).expect("read"); + expand(v, d, n) + }; + let i64s = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::Int64ColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected INT64 at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + assert_eq!(v.len(), n); + v + }; + let strs = |idx: usize| -> Vec> { + let (mut v, mut d) = (Vec::new(), Vec::new()); + let ColumnReader::ByteArrayColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected BYTE_ARRAY at {idx}"); + }; + r.read_records(n, Some(&mut d), None, &mut v).expect("read"); + let v: Vec = v + .into_iter() + .map(|b| String::from_utf8(b.data().to_vec()).expect("utf8")) + .collect(); + if d.is_empty() { + assert_eq!(v.len(), n); + v.into_iter().map(Some).collect() + } else { + expand(v, d, n) + } + }; + + let lid = i32s(0); + let ed = i32s(1); + let decl = i32s(2); + let kind = strs(3); + let ratio = f64s(4); + let cash = f64s(5); + let cur = strs(6); + let succ = i32s(7); + let tr = f64s(8); + let ka = i64s(9); + let src = strs(10); + for i in 0..n { + out.push(CorporateActionsParquetRow { + listing_id: lid[i].expect("listing_id required"), + ex_date: ed[i].expect("ex_date required"), + declared_date: decl[i], + kind: parse_kind(kind[i].as_deref().expect("kind required")), + ratio: ratio[i], + cash_amount: cash[i], + currency: cur[i].clone().map(Cow::Owned), + successor_listing_id: succ[i], + terminal_return: tr[i], + known_at_micros: ka[i], + known_at_source: parse_source(src[i].as_deref().expect("source required")), + }); + } + } + out +} + +fn bits(v: Option) -> Option { + v.map(f64::to_bits) +} + +fn assert_bitwise(actual: &[CorporateActionsParquetRow], expected: &[CorporateActionsParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id"); + assert_eq!(a.ex_date, e.ex_date, "row {i} ex_date"); + assert_eq!(a.declared_date, e.declared_date, "row {i} declared_date"); + assert_eq!(a.kind, e.kind, "row {i} kind"); + assert_eq!(bits(a.ratio), bits(e.ratio), "row {i} ratio"); + assert_eq!( + bits(a.cash_amount), + bits(e.cash_amount), + "row {i} cash_amount" + ); + assert_eq!(a.currency, e.currency, "row {i} currency"); + assert_eq!( + a.successor_listing_id, e.successor_listing_id, + "row {i} successor_listing_id" + ); + assert_eq!( + bits(a.terminal_return), + bits(e.terminal_return), + "row {i} terminal_return" + ); + assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at"); + assert_eq!( + a.known_at_source, e.known_at_source, + "row {i} known_at_source" + ); + } +} + +fn row_group_sizes(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + reader + .metadata() + .row_groups() + .iter() + .map(|rg| rg.num_rows()) + .collect() +} + +#[test] +fn seeded_random_streams_of_all_kinds_round_trip_with_expected_row_group_layout() { + // Arrange: one fixed stream, written with several row-group sizes around the string batch. + let total = 2 * STRING_BATCH + 37; + let mut rng = Rng(0xC0A0_0096_0000_0001); + let rows: Vec = + (0..total).map(|i| random_row(i, &mut rng)).collect(); + for kind in [ + CorporateActionKind::Split, + CorporateActionKind::Dividend, + CorporateActionKind::OtcDelistTransfer, + CorporateActionKind::Delisting, + ] { + assert!( + rows.iter().any(|r| r.kind == kind), + "fixture covers {kind:?}" + ); + } + + for rgr in [1usize, 7, STRING_BATCH, STRING_BATCH + 1, total, total + 10] { + let tmp = TempDir::new("random"); + + // Act + let stats = write_corporate_actions_dataset(&tmp.0, &rows, opts(rgr)).unwrap(); + + // Assert + let path = part_path(&tmp.0); + let expected_groups = total.div_ceil(rgr); + assert_eq!(stats.rows_written, total, "rgr={rgr}"); + assert_eq!(stats.files_written, 1, "rgr={rgr}"); + assert_eq!(stats.row_groups_written, expected_groups, "rgr={rgr}"); + assert_eq!(stats.bytes_written, fs::metadata(&path).unwrap().len()); + let sizes = row_group_sizes(&path); + assert_eq!(sizes.len(), expected_groups, "rgr={rgr}"); + assert!(sizes[..sizes.len() - 1].iter().all(|&s| s == rgr as i64)); + assert_bitwise(&read_rows(&path), &rows); + assert!(leftover_transients(&tmp.0).is_empty(), "rgr={rgr}"); + } +} + +/// Lazy source that records the staging-file size each time a new row group starts. +struct ObservingIter { + dir: PathBuf, + total: usize, + row_group_rows: usize, + next_idx: usize, + rng: Rng, + observed_at_group_start: Vec, +} + +impl Iterator for ObservingIter { + type Item = CorporateActionsParquetRow; + + fn next(&mut self) -> Option { + if self.next_idx >= self.total { + return None; + } + if self.next_idx % self.row_group_rows == 0 { + self.observed_at_group_start.push(staging_bytes(&self.dir)); + } + let r = random_row(self.next_idx, &mut self.rng); + self.next_idx += 1; + Some(r) + } +} + +#[test] +fn row_groups_are_flushed_to_staging_before_remaining_rows_are_pulled() { + // Arrange: 3 row groups of 40,000 random-mantissa rows (each group well beyond the + // writer's in-memory BufWriter capacity once compressed). + let tmp = TempDir::new("streaming"); + let row_group_rows = 40_000; + let mut iter = ObservingIter { + dir: dataset_dir(&tmp.0), + total: 3 * row_group_rows, + row_group_rows, + next_idx: 0, + rng: Rng(0xC0A0_0096_0000_0002), + observed_at_group_start: Vec::new(), + }; + + // Act + let stats = + write_corporate_actions_dataset(&tmp.0, iter.by_ref(), opts(row_group_rows)).unwrap(); + + // Assert + assert_eq!(stats.rows_written, 3 * row_group_rows); + assert_eq!(stats.row_groups_written, 3); + let obs = &iter.observed_at_group_start; + assert_eq!(obs.len(), 3, "one observation per row-group start"); + assert_eq!( + obs[0], 0, + "nothing on disk before the first row is buffered" + ); + assert!( + obs[1] > 0, + "row group 1 must reach staging before group 2 is pulled: {obs:?}" + ); + assert!( + obs[2] > obs[1], + "row group 2 must reach staging before group 3: {obs:?}" + ); + assert!(stats.bytes_written > obs[2]); +} + +#[test] +fn builder_output_with_all_kinds_writes_without_resorting_and_round_trips() { + // Arrange: events deliberately supplied out of order; builder sorts, writer must accept. + let d = days; + let splits = vec![ + ( + 7i32, + SplitActionEvent { + ex_date: d(2020, 8, 31), + ratio: 4.0, + declared_date: Some(d(2020, 7, 30)), + }, + ), + ( + 3i32, + SplitActionEvent { + ex_date: d(1999, 6, 1), + ratio: 0.05, + declared_date: None, + }, + ), + ]; + let dividends = vec![ + ( + 7i32, + DividendActionEvent { + ex_date: d(2020, 8, 31), + cash: 0.82, + currency: "USD".to_string(), + declared_date: Some(d(2020, 7, 30)), + }, + ), + ( + 7i32, + DividendActionEvent { + ex_date: d(2020, 8, 31), + cash: 1.5, + currency: "USD".to_string(), + declared_date: None, + }, + ), + ( + 3i32, + DividendActionEvent { + ex_date: d(2001, 3, 15), + cash: 0.25, + currency: "CAD".to_string(), + declared_date: Some(d(2001, 3, 20)), + }, + ), + ]; + let delistings = vec![ + ( + 7i32, + DelistingOutcomeEvent { + delist_date: d(2023, 3, 13), + successor_key: Some(70i32), + terminal_return: None, + }, + ), + ( + 3i32, + DelistingOutcomeEvent { + delist_date: d(2008, 10, 1), + successor_key: None, + terminal_return: Some(-1.0), + }, + ), + ]; + let built = build_corporate_actions(splits, dividends, delistings).unwrap(); + let expected: Vec = built + .rows + .iter() + .map(|r| { + CorporateActionsParquetRow::from_corporate_action_row( + r, + i64::from(r.known_at_date) * MICROS_PER_DAY, + ) + }) + .collect(); + assert_eq!( + expected.len(), + 7, + "builder keeps every event incl. same-day dividends" + ); + let tmp = TempDir::new("builder"); + + // Act + let stats = write_corporate_actions_dataset(&tmp.0, &expected, opts(2)).unwrap(); + + // Assert + assert_eq!(stats.rows_written, 7); + assert_eq!(stats.row_groups_written, 4); + let actual = read_rows(&part_path(&tmp.0)); + assert_bitwise(&actual, &expected); + let kinds: Vec = actual.iter().map(|r| r.kind).collect(); + assert!(kinds.contains(&CorporateActionKind::OtcDelistTransfer)); + assert!(kinds.contains(&CorporateActionKind::Delisting)); + let same_day_divs = actual + .iter() + .filter(|r| { + r.listing_id == 7 + && r.ex_date == d(2020, 8, 31) + && r.kind == CorporateActionKind::Dividend + }) + .count(); + assert_eq!(same_day_divs, 2); +} + +#[test] +fn currency_labels_survive_interner_reset_between_row_groups() { + // Arrange: group 1 only CAD, group 2 only USD, group 3 a mix starting with a null currency + // (non-dividend) — a stale interner would relabel ids across groups. + let mk = |i: usize, cur: Option<&'static str>| { + let ex_date = days(2010, 1, 4) + i as i32; + match cur { + Some(c) => CorporateActionsParquetRow { + listing_id: 1, + ex_date, + declared_date: None, + kind: CorporateActionKind::Dividend, + ratio: None, + cash_amount: Some(0.1 + i as f64), + currency: Some(Cow::Borrowed(c)), + successor_listing_id: None, + terminal_return: None, + known_at_micros: i64::from(ex_date) * MICROS_PER_DAY, + known_at_source: KnownAtSource::ExDateFallback, + }, + None => CorporateActionsParquetRow { + listing_id: 1, + ex_date, + declared_date: None, + kind: CorporateActionKind::Split, + ratio: Some(2.0), + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: None, + known_at_micros: i64::from(ex_date) * MICROS_PER_DAY, + known_at_source: KnownAtSource::ExDateFallback, + }, + } + }; + let rows = vec![ + mk(0, Some("CAD")), + mk(1, Some("CAD")), + mk(2, Some("USD")), + mk(3, Some("USD")), + mk(4, None), + mk(5, Some("USD")), + mk(6, Some("CAD")), + ]; + let tmp = TempDir::new("interner"); + + // Act + write_corporate_actions_dataset(&tmp.0, &rows, opts(2)).unwrap(); + + // Assert + let back = read_rows(&part_path(&tmp.0)); + let currencies: Vec> = back.iter().map(|r| r.currency.as_deref()).collect(); + assert_eq!( + currencies, + vec![ + Some("CAD"), + Some("CAD"), + Some("USD"), + Some("USD"), + None, + Some("USD"), + Some("CAD") + ] + ); + assert_bitwise(&back, &rows); +} + +#[test] +fn late_invalid_row_after_flushed_row_groups_preserves_seeded_file_and_cleans_up() { + // Arrange: seed a valid part.parquet, then stream 3 full row groups plus a bad last row. + let tmp = TempDir::new("late-fail"); + let mut rng = Rng(0xC0A0_0096_0000_0003); + let seed_rows: Vec<_> = (0..16).map(|i| random_row(i, &mut rng)).collect(); + write_corporate_actions_dataset(&tmp.0, &seed_rows, opts(4)).unwrap(); + let before = fs::read(part_path(&tmp.0)).unwrap(); + + let mut rows: Vec<_> = (0..30_000).map(|i| random_row(i, &mut rng)).collect(); + let mut bad = rows.last().unwrap().clone(); + bad.listing_id += 1; + bad.kind = CorporateActionKind::Delisting; + bad.ratio = None; + bad.cash_amount = None; + bad.currency = None; + bad.successor_listing_id = None; + bad.terminal_return = Some(-1.000_000_1); + bad.known_at_source = KnownAtSource::DelistDate; + rows.push(bad.clone()); + + // Act + let err = write_corporate_actions_dataset(&tmp.0, &rows, opts(10_000)).unwrap_err(); + + // Assert + match err { + ParquetCorporateActionsError::InvalidTerminalReturn { + listing_id, + ex_date, + value, + } => { + assert_eq!(listing_id, bad.listing_id); + assert_eq!(ex_date, bad.ex_date); + assert_eq!(bits(value), bits(Some(-1.000_000_1))); + } + other => panic!("expected InvalidTerminalReturn, got {other:?}"), + } + assert_eq!( + fs::read(part_path(&tmp.0)).unwrap(), + before, + "seed file byte-identical" + ); + assert!( + leftover_transients(&tmp.0).is_empty(), + "no staging/backup/lock left: {:?}", + leftover_transients(&tmp.0) + ); +} + +#[test] +fn unsorted_kind_within_same_listing_and_date_is_rejected_with_both_keys() { + // Arrange: dividend then split on the same (listing_id, ex_date) violates kind order. + let tmp = TempDir::new("unsorted-kind"); + let mut rng = Rng(0xC0A0_0096_0000_0004); + let mut div = random_row(1, &mut rng); + while div.kind != CorporateActionKind::Dividend { + div = random_row(1, &mut rng); + } + let split = CorporateActionsParquetRow { + kind: CorporateActionKind::Split, + ratio: Some(2.0), + cash_amount: None, + currency: None, + ..div.clone() + }; + + // Act + let err = write_corporate_actions_dataset(&tmp.0, [&div, &split], opts(1)).unwrap_err(); + + // Assert + match err { + ParquetCorporateActionsError::UnsortedInput { + prev_listing_id, + prev_ex_date, + prev_kind, + listing_id, + ex_date, + kind, + } => { + assert_eq!( + (prev_listing_id, prev_ex_date, prev_kind), + (div.listing_id, div.ex_date, CorporateActionKind::Dividend) + ); + assert_eq!( + (listing_id, ex_date, kind), + (div.listing_id, div.ex_date, CorporateActionKind::Split) + ); + } + other => panic!("expected UnsortedInput, got {other:?}"), + } + assert!(!part_path(&tmp.0).exists()); + assert!(leftover_transients(&tmp.0).is_empty()); +} + +#[test] +fn invalid_options_are_rejected_before_a_finite_iterator_is_polled() { + // Arrange: finite probes (once_with) so a regression cannot buffer rows unboundedly. + let tmp = TempDir::new("options"); + let polled = Cell::new(0usize); + let make_probe = || { + std::iter::once_with(|| { + polled.set(polled.get() + 1); + let mut rng = Rng(0xC0A0_0096_0000_0005); + random_row(0, &mut rng) + }) + }; + + // Act + let zero_rg = write_corporate_actions_dataset(&tmp.0, make_probe(), opts(0)).unwrap_err(); + let bad_zstd = write_corporate_actions_dataset( + &tmp.0, + make_probe(), + CorporateActionsWriteOptions { + zstd_level: 23, + ..CorporateActionsWriteOptions::default() + }, + ) + .unwrap_err(); + + // Assert + assert!(matches!( + zero_rg, + ParquetCorporateActionsError::InvalidRowGroupRows + )); + assert!(matches!( + bad_zstd, + ParquetCorporateActionsError::InvalidZstdLevel { level: 23 } + )); + assert_eq!( + polled.get(), + 0, + "iterator must not be polled on invalid options" + ); + assert!( + !dataset_dir(&tmp.0).exists(), + "no dataset directory created" + ); +} diff --git a/tools/curate-etl/tests/parquet_events_contract.rs b/tools/curate-etl/tests/parquet_events_contract.rs new file mode 100644 index 00000000..9c9ffa8a --- /dev/null +++ b/tools/curate-etl/tests/parquet_events_contract.rs @@ -0,0 +1,281 @@ +//! Contract tests for the public `events` Parquet writer API (T-93 / M1.2k). +//! +//! Uses only the crate's public surface (`build_events`, `write_events_dataset`, +//! `events_parquet_schema`, the `curate-etl` binary) plus an independent Parquet column reader. + +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + build_events, events_parquet_schema, partition_year_utc, write_events_dataset, + ymd_to_epoch_days, EventsParquetRow, EventsWriteOptions, ParquetEventsError, QmEarning, + QmFiling, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, +}; +use parquet::basic::{ + Compression, ConvertedType, Encoding, LogicalType, Repetition, TimeUnit, Type as PhysicalType, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-events-contract-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let n = meta.row_group(rg).num_rows() as usize; + let g = reader.get_row_group(rg).expect("row group"); + let col = |i: usize| g.get_column_reader(i).expect("column reader"); + + let i32s = |c: ColumnReader| -> Vec { + let mut v = Vec::with_capacity(n); + match c { + ColumnReader::Int32ColumnReader(mut r) => { + let mut read = 0; + while read < n { + let (got, _, _) = r.read_records(n - read, None, None, &mut v).unwrap(); + assert!(got > 0); + read += got; + } + } + _ => panic!("expected INT32"), + } + v + }; + let i64s = |c: ColumnReader| -> Vec { + let mut v = Vec::with_capacity(n); + match c { + ColumnReader::Int64ColumnReader(mut r) => { + let mut read = 0; + while read < n { + let (got, _, _) = r.read_records(n - read, None, None, &mut v).unwrap(); + assert!(got > 0); + read += got; + } + } + _ => panic!("expected INT64"), + } + v + }; + let strs = |c: ColumnReader| -> Vec { + let mut v = Vec::with_capacity(n); + match c { + ColumnReader::ByteArrayColumnReader(mut r) => { + let mut read = 0; + while read < n { + let (got, _, _) = r.read_records(n - read, None, None, &mut v).unwrap(); + assert!(got > 0); + read += got; + } + } + _ => panic!("expected BYTE_ARRAY"), + } + v.iter() + .map(|b| std::str::from_utf8(b.data()).expect("utf8").to_string()) + .collect() + }; + + let lid = i32s(col(0)); + let ts = i64s(col(1)); + let ka = i64s(col(2)); + let kas = strs(col(3)); + let kind = strs(col(4)); + let sub = strs(col(5)); + let json = strs(col(6)); + + for i in 0..n { + out.push(EventsParquetRow { + listing_id: lid[i], + ts_micros: ts[i], + known_at_micros: ka[i], + known_at_source: Cow::Owned(kas[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: sub[i].clone(), + payload_json: json[i].clone(), + }); + } + } + out +} + +#[test] +fn public_build_events_round_trip_matches_contract_schema_and_partitions() { + let tmp = TempDir::new("contract"); + let built = build_events( + vec![ + QmFiling { + key: 1_i32, + timefiled: "2022-11-01T14:00:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-1".to_string()), + url: None, + }, + QmFiling { + key: 1_i32, + timefiled: "2023-05-04T16:15:00 EDT".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("F-2".to_string()), + url: Some("https://sec.example/2".to_string()), + }, + QmFiling { + key: 2_i32, + timefiled: "2024-12-31T21:30:00 EST".to_string(), + form_type: "News release".to_string(), + filing_id: Some("F-3".to_string()), + url: None, + }, + ], + vec![ + QmEarning { + key: 1_i32, + report_date: ymd_to_epoch_days(2023, 5, 4).unwrap(), + announce_time: "AMC".to_string(), + fiscal_period_end: Some(ymd_to_epoch_days(2023, 3, 31).unwrap()), + actual_eps: Some(2.15), + revenue: Some(1_000_000.0), + }, + QmEarning { + key: 2_i32, + report_date: ymd_to_epoch_days(2024, 7, 15).unwrap(), + announce_time: "BTO".to_string(), + fiscal_period_end: None, + actual_eps: Some(0.45), + revenue: None, + }, + ], + ); + + let rows: Vec = built.rows.into_iter().map(EventsParquetRow::from).collect(); + let stats = write_events_dataset(&tmp.0, &rows, EventsWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 5); + assert_eq!(stats.files_written, 4); + assert_eq!( + stats.rows_by_year, + BTreeMap::from([(2022, 1), (2023, 2), (2024, 1), (2025, 1)]) + ); + + let expected_schema = events_parquet_schema().unwrap(); + for year in [2022, 2023, 2024, 2025] { + let path = tmp.0.join(format!("events/year={year:04}/part.parquet")); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref()); + let fields = meta.file_metadata().schema().get_fields(); + assert_eq!(fields.len(), 7); + assert_eq!(fields[0].name(), "listing_id"); + assert_eq!(fields[0].get_physical_type(), PhysicalType::INT32); + assert_eq!(fields[0].get_basic_info().repetition(), Repetition::REQUIRED); + assert_eq!( + fields[1].get_basic_info().logical_type_ref().cloned(), + Some(LogicalType::timestamp(true, TimeUnit::MICROS)) + ); + assert_eq!( + fields[2].get_basic_info().converted_type(), + ConvertedType::TIMESTAMP_MICROS + ); + assert_eq!(fields[6].name(), "payload_json"); + assert_eq!( + fields[6].get_basic_info().logical_type_ref().cloned(), + Some(LogicalType::String) + ); + + for rg in meta.row_groups() { + for c in rg.columns() { + assert!(matches!(c.compression(), Compression::ZSTD(_))); + } + for dict_col in [3usize, 4usize] { + assert!(rg + .column(dict_col) + .encodings() + .any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY))); + } + } + + let actual = read_rows(&path); + let expected: Vec = rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == year) + .cloned() + .collect(); + assert_eq!(actual, expected); + } + + // Typed error check via public API + let bad = vec![EventsParquetRow { + listing_id: 1, + ts_micros: 1_700_000_000_000_000, + known_at_micros: 1_700_000_000_000_000 - 1, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + kind: Cow::Borrowed(EVENT_KIND_FILING), + subtype: "8-k".to_string(), + payload_json: "{}".to_string(), + }]; + let err = write_events_dataset(&tmp.0, &bad, EventsWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetEventsError::KnownAtBeforeTs { .. })); +} + +#[test] +fn bench_parquet_events_cli_prints_metrics_and_removes_its_temp_dir() { + let tmp = TempDir::new("cli"); + let out = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(["bench-parquet-events", "20000"]) + .env("TMPDIR", &tmp.0) + .output() + .expect("spawn curate-etl"); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + for needle in [ + "curate-etl bench-parquet-events", + "rows=20000", + "read_back_rows=20000", + "rows/s", + "MB/s", + "bytes/row", + "compression=", + ] { + assert!(stdout.contains(needle), "missing '{needle}' in:\n{stdout}"); + } + let leftovers: Vec<_> = fs::read_dir(&tmp.0).unwrap().collect(); + assert!( + leftovers.is_empty(), + "benchmark left files in TMPDIR: {leftovers:?}" + ); + + let bad = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(["bench-parquet-events", "0"]) + .env("TMPDIR", &tmp.0) + .output() + .expect("spawn curate-etl"); + assert!(!bad.status.success()); + assert!(String::from_utf8_lossy(&bad.stderr).contains("bench-parquet-events")); +} diff --git a/tools/curate-etl/tests/parquet_events_edge_contract.rs b/tools/curate-etl/tests/parquet_events_edge_contract.rs new file mode 100644 index 00000000..b7be66fa --- /dev/null +++ b/tools/curate-etl/tests/parquet_events_edge_contract.rs @@ -0,0 +1,539 @@ +//! QA edge-case contract tests for the public `events` Parquet writer (T-93 / M1.2k). +//! +//! Complements `parquet_events_contract.rs` and the `--lib` suite through the public API only: +//! owned vs borrowed input equivalence, option validation before the iterator is polled, +//! sort-key priority (`known_at` before `known_at_source`), byte-wise (not locale) string order, +//! extreme `listing_id` values, failures in a later year after earlier years were buffered, +//! lock release after a failed run, and preservation of files the writer does not own. + +use std::borrow::Cow; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + build_events, write_events_dataset, ymd_to_epoch_days, EventsParquetRow, EventsWriteOptions, + ParquetEventsError, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_DAY: i64 = 86_400_000_000; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-events-edge-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn day_micros(y: i32, m: u32, d: u32) -> i64 { + i64::from(ymd_to_epoch_days(y, m, d).expect("valid fixture date")) * MICROS_PER_DAY +} + +fn part(out: &Path, year: i32) -> PathBuf { + out.join(format!("events/year={year:04}/part.parquet")) +} + +fn filing(listing_id: i32, ts: i64, subtype: &str, payload: &str) -> EventsParquetRow { + EventsParquetRow { + listing_id, + ts_micros: ts, + known_at_micros: ts, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + kind: Cow::Borrowed(EVENT_KIND_FILING), + subtype: subtype.to_string(), + payload_json: payload.to_string(), + } +} + +/// Every regular file under `dir`, relative path, sorted. +fn list_files(dir: &Path) -> Vec { + fn walk(root: &Path, dir: &Path, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + for entry in entries { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(root, &path, out); + } else { + out.push( + path.strip_prefix(root) + .expect("under root") + .to_string_lossy() + .into_owned(), + ); + } + } + } + let mut out = Vec::new(); + walk(dir, dir, &mut out); + out.sort(); + out +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let n = meta.row_group(rg).num_rows() as usize; + let g = reader.get_row_group(rg).expect("row group"); + let mut lid = Vec::new(); + let mut ts = Vec::new(); + let mut ka = Vec::new(); + let mut strs: Vec> = Vec::new(); + for c in 0..7 { + match g.get_column_reader(c).expect("column reader") { + ColumnReader::Int32ColumnReader(mut r) => { + while lid.len() < n { + let (got, _, _) = + r.read_records(n - lid.len(), None, None, &mut lid).unwrap(); + assert!(got > 0); + } + } + ColumnReader::Int64ColumnReader(mut r) => { + let v = if c == 1 { &mut ts } else { &mut ka }; + while v.len() < n { + let (got, _, _) = r.read_records(n - v.len(), None, None, v).unwrap(); + assert!(got > 0); + } + } + ColumnReader::ByteArrayColumnReader(mut r) => { + let mut v = Vec::new(); + while v.len() < n { + let (got, _, _) = r.read_records(n - v.len(), None, None, &mut v).unwrap(); + assert!(got > 0); + } + strs.push( + v.iter() + .map(|b| std::str::from_utf8(b.data()).expect("utf8").to_string()) + .collect(), + ); + } + _ => panic!("unexpected column type at {c}"), + } + } + for i in 0..n { + out.push(EventsParquetRow { + listing_id: lid[i], + ts_micros: ts[i], + known_at_micros: ka[i], + known_at_source: Cow::Owned(strs[0][i].clone()), + kind: Cow::Owned(strs[1][i].clone()), + subtype: strs[2][i].clone(), + payload_json: strs[3][i].clone(), + }); + } + } + out +} + +fn sample_build_events_rows() -> Vec> { + build_events( + vec![ + QmFiling { + key: 7_i32, + timefiled: "2021-02-10T09:15:00 EST".to_string(), + form_type: "10-K".to_string(), + filing_id: Some("A-1".to_string()), + url: Some("https://sec.example/a1".to_string()), + }, + QmFiling { + key: 7_i32, + timefiled: "2022-08-03T16:20:00 EDT".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("A-2".to_string()), + url: None, + }, + QmFiling { + key: 9_i32, + timefiled: "2023-12-31T20:00:00 EST".to_string(), + form_type: "Material change report".to_string(), + filing_id: Some("B-1".to_string()), + url: None, + }, + ], + vec![ + QmEarning { + key: 7_i32, + report_date: ymd_to_epoch_days(2022, 8, 3).unwrap(), + announce_time: "AMC".to_string(), + fiscal_period_end: Some(ymd_to_epoch_days(2022, 6, 30).unwrap()), + actual_eps: Some(-0.12), + revenue: Some(5.5e7), + }, + QmEarning { + key: 9_i32, + report_date: ymd_to_epoch_days(2023, 3, 1).unwrap(), + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + ], + ) + .rows +} + +#[test] +fn owned_borrowed_and_converted_inputs_produce_byte_identical_files() { + let built = sample_build_events_rows(); + assert!( + built + .iter() + .any(|r| r.kind == EVENT_KIND_EARNINGS + && r.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG), + "fixture must include a lagged earnings row" + ); + + let from_ref: Vec = built.iter().map(EventsParquetRow::from).collect(); + let from_owned: Vec = built + .clone() + .into_iter() + .map(EventsParquetRow::from) + .collect(); + assert_eq!(from_ref, from_owned); + + let opts = EventsWriteOptions { + row_group_rows: 2, + ..EventsWriteOptions::default() + }; + let a = TempDir::new("borrowed"); + let b = TempDir::new("owned"); + let stats_a = write_events_dataset(&a.0, &from_ref, opts).unwrap(); + let stats_b = write_events_dataset(&b.0, from_owned.clone(), opts).unwrap(); + + assert_eq!(stats_a, stats_b); + assert_eq!(stats_a.rows_written, built.len()); + assert_eq!(list_files(&a.0), list_files(&b.0)); + for year in stats_a.rows_by_year.keys() { + assert_eq!( + fs::read(part(&a.0, *year)).unwrap(), + fs::read(part(&b.0, *year)).unwrap(), + "year {year} must be byte-identical for borrowed vs owned input" + ); + } + // Read back equals input, concatenated in year order (input is sorted by listing first, so + // compare as multisets keyed by the full row). + let mut read_back: Vec = stats_a + .rows_by_year + .keys() + .flat_map(|y| read_rows(&part(&a.0, *y))) + .collect(); + let mut expected = from_owned; + let key = |r: &EventsParquetRow| (r.listing_id, r.ts_micros, r.payload_json.clone()); + read_back.sort_by_key(key); + expected.sort_by_key(key); + assert_eq!(read_back, expected); +} + +/// Iterator that fails the test if the writer polls it. +struct MustNotPoll; + +impl Iterator for MustNotPoll { + type Item = EventsParquetRow; + fn next(&mut self) -> Option { + panic!("writer polled the iterator before validating options"); + } +} + +#[test] +fn invalid_options_are_rejected_before_polling_the_iterator() { + let tmp = TempDir::new("opts-before-poll"); + + let err = write_events_dataset( + &tmp.0, + MustNotPoll, + EventsWriteOptions { + row_group_rows: 0, + ..EventsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!( + matches!(err, ParquetEventsError::InvalidRowGroupRows), + "{err:?}" + ); + + for level in [23, 99, -200_000] { + let err = write_events_dataset( + &tmp.0, + MustNotPoll, + EventsWriteOptions { + row_group_rows: 10, + zstd_level: level, + }, + ); + assert!( + matches!(err, Err(ParquetEventsError::InvalidZstdLevel { level: l }) if l == level), + "level {level}: {err:?}" + ); + } + assert!(list_files(&tmp.0).is_empty()); + assert!(!tmp.0.join("events").exists()); +} + +#[test] +fn invalid_first_row_creates_no_events_directory() { + let tmp = TempDir::new("bad-first"); + let ts = day_micros(2024, 5, 1); + let mut bad = filing(1, ts, "8-k", "{\"a\":1}"); + bad.known_at_micros = ts - 1; + + let err = write_events_dataset(&tmp.0, [bad], EventsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetEventsError::KnownAtBeforeTs { row_index: 0, known_at_micros, ts_micros, .. } + if known_at_micros == ts - 1 && ts_micros == ts + ), + "{err:?}" + ); + assert!(!tmp.0.join("events").exists()); +} + +#[test] +fn known_at_takes_priority_over_known_at_source_in_sort_key() { + let tmp = TempDir::new("sort-priority"); + let ts = day_micros(2023, 3, 3); + let mut first = filing(5, ts, "8-k", "{\"x\":1}"); + first.known_at_micros = ts + 10; + first.known_at_source = Cow::Borrowed("a_source"); + let mut second = first.clone(); + // Ascending by known_at_source but descending by known_at: must be rejected because + // known_at_micros precedes known_at_source in the build_events sort key. + second.known_at_micros = ts + 5; + second.known_at_source = Cow::Borrowed("b_source"); + + let err = + write_events_dataset(&tmp.0, [&first, &second], EventsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetEventsError::UnsortedInput { + row_index: 1, + listing_id: 5, + .. + } + ), + "{err:?}" + ); + + // The reverse (known_at ascending, source descending) is valid. + let mut ok_second = first.clone(); + ok_second.known_at_micros = ts + 20; + ok_second.known_at_source = Cow::Borrowed("0_source"); + let stats = + write_events_dataset(&tmp.0, [&first, &ok_second], EventsWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 2); + assert_eq!(read_rows(&part(&tmp.0, 2023)), vec![first, ok_second]); +} + +#[test] +fn string_sort_is_bytewise_utf8_matching_build_events() { + let tmp = TempDir::new("bytewise"); + let ts = day_micros(2020, 1, 15); + // 'Z' (0x5A) < 'a' (0x61) < 'é' (0xC3 0xA9): byte order, not case-insensitive or locale. + let rows = vec![ + filing(1, ts, "Zeta", "{}x"), + filing(1, ts, "alpha", "{}x"), + filing(1, ts, "émission", "{}x"), + ]; + let mut sorted = rows.clone(); + sorted.sort_by(|a, b| a.subtype.cmp(&b.subtype)); + assert_eq!(sorted, rows, "fixture must already be in String::cmp order"); + + let stats = write_events_dataset(&tmp.0, &rows, EventsWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 3); + assert_eq!(read_rows(&part(&tmp.0, 2020)), rows); + + // Locale-style order ("alpha" < "émission" < "Zeta") must be rejected at row 2. + let other = TempDir::new("bytewise-bad"); + let locale = vec![rows[1].clone(), rows[2].clone(), rows[0].clone()]; + let err = write_events_dataset(&other.0, &locale, EventsWriteOptions::default()).unwrap_err(); + assert!( + matches!(err, ParquetEventsError::UnsortedInput { row_index: 2, .. }), + "{err:?}" + ); +} + +#[test] +fn extreme_listing_ids_round_trip() { + let tmp = TempDir::new("listing-extremes"); + let ts = day_micros(2019, 6, 1); + let rows = vec![ + filing(i32::MIN, ts, "8-k", "{\"id\":\"min\"}"), + filing(-1, ts, "8-k", "{\"id\":\"neg\"}"), + filing(0, ts, "8-k", "{\"id\":\"zero\"}"), + filing(i32::MAX, ts, "8-k", "{\"id\":\"max\"}"), + ]; + let stats = write_events_dataset(&tmp.0, &rows, EventsWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 4); + assert_eq!(read_rows(&part(&tmp.0, 2019)), rows); +} + +#[test] +fn failure_in_later_year_after_buffering_earlier_years_publishes_nothing_and_releases_lock() { + let tmp = TempDir::new("later-year-fail"); + let opts = EventsWriteOptions { + row_group_rows: 2, + ..EventsWriteOptions::default() + }; + + // Existing dataset: 2018 and 2020. + let old = vec![ + filing(1, day_micros(2018, 1, 2), "10-k", "{\"gen\":\"old-2018\"}"), + filing(1, day_micros(2020, 1, 2), "10-k", "{\"gen\":\"old-2020\"}"), + ]; + write_events_dataset(&tmp.0, &old, opts).unwrap(); + // Unrelated files the writer does not own must survive success and failure. + fs::write(tmp.0.join("events/year=2018/NOTES.txt"), b"keep me").unwrap(); + fs::write(tmp.0.join("events/README"), b"keep me too").unwrap(); + let old_2018 = fs::read(part(&tmp.0, 2018)).unwrap(); + let old_2020 = fs::read(part(&tmp.0, 2020)).unwrap(); + let files_before = list_files(&tmp.0); + + // New run: several rows in 2018 (flushes a row group), a new 2019 partition, then a bad + // 2020 row (empty payload) for a later listing. + let new = vec![ + filing( + 1, + day_micros(2018, 3, 1), + "10-q", + "{\"gen\":\"new\",\"n\":1}", + ), + filing( + 1, + day_micros(2018, 6, 1), + "10-q", + "{\"gen\":\"new\",\"n\":2}", + ), + filing( + 1, + day_micros(2018, 9, 1), + "10-q", + "{\"gen\":\"new\",\"n\":3}", + ), + filing( + 1, + day_micros(2019, 3, 1), + "10-q", + "{\"gen\":\"new\",\"n\":4}", + ), + filing(2, day_micros(2020, 3, 1), "10-q", " "), + ]; + let err = write_events_dataset(&tmp.0, &new, opts).unwrap_err(); + assert!( + matches!( + err, + ParquetEventsError::EmptyPayloadJson { + row_index: 4, + listing_id: 2, + .. + } + ), + "{err:?}" + ); + + assert_eq!(fs::read(part(&tmp.0, 2018)).unwrap(), old_2018); + assert_eq!(fs::read(part(&tmp.0, 2020)).unwrap(), old_2020); + assert!(!part(&tmp.0, 2019).exists()); + assert_eq!( + list_files(&tmp.0), + files_before, + "no tmp/bak/lock files may remain and no foreign files may be removed" + ); + + // Lock released: a valid follow-up run succeeds immediately (default timeout would hang + // for a long time if `.write.lock` leaked). + let fixed: Vec = new[..4].to_vec(); + let stats = write_events_dataset(&tmp.0, &fixed, opts).unwrap(); + assert_eq!(stats.rows_by_year.get(&2018), Some(&3)); + assert_eq!(stats.rows_by_year.get(&2019), Some(&1)); + assert_eq!(stats.row_groups_written, 3, "2018: 2+1 rows, 2019: 1 row"); + assert_eq!(read_rows(&part(&tmp.0, 2018)), fixed[..3].to_vec()); + assert_eq!( + fs::read(part(&tmp.0, 2020)).unwrap(), + old_2020, + "untouched year preserved" + ); + assert_eq!( + fs::read(tmp.0.join("events/year=2018/NOTES.txt")).unwrap(), + b"keep me" + ); + assert_eq!( + fs::read(tmp.0.join("events/README")).unwrap(), + b"keep me too" + ); + let mut expected_files = files_before; + expected_files.push("events/year=2019/part.parquet".to_string()); + expected_files.sort(); + assert_eq!(list_files(&tmp.0), expected_files); +} + +#[test] +fn stats_match_files_on_disk_for_many_years_and_small_row_groups() { + let tmp = TempDir::new("stats"); + let opts = EventsWriteOptions { + row_group_rows: 3, + zstd_level: 5, + }; + // 4 listings x 5 years, 1..=4 rows per (listing, year) -> varied row-group splits. + let mut rows = Vec::new(); + for listing in 1..=4 { + for year in 2016..=2020 { + for k in 0..(listing as i64) { + let ts = day_micros(year, 2, 1) + k * 3_600_000_000; + rows.push(filing( + listing, + ts, + "6-k", + &format!("{{\"l\":{listing},\"y\":{year},\"k\":{k}}}"), + )); + } + } + } + let stats = write_events_dataset(&tmp.0, &rows, opts).unwrap(); + + assert_eq!(stats.rows_written, rows.len()); + assert_eq!(stats.files_written, 5); + assert_eq!(stats.rows_by_year.values().sum::(), rows.len()); + let mut bytes = 0u64; + let mut row_groups = 0usize; + for (year, n) in &stats.rows_by_year { + assert_eq!(*n, 1 + 2 + 3 + 4, "year {year}"); + let path = part(&tmp.0, *year); + bytes += fs::metadata(&path).unwrap().len(); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + assert_eq!(reader.metadata().file_metadata().num_rows() as usize, *n); + assert_eq!(reader.metadata().num_row_groups(), n.div_ceil(3)); + row_groups += reader.metadata().num_row_groups(); + let expected: Vec = rows + .iter() + .filter(|r| curate_etl::partition_year_utc(r.ts_micros) == *year) + .cloned() + .collect(); + assert_eq!(read_rows(&path), expected, "year {year} order and content"); + } + assert_eq!(stats.bytes_written, bytes); + assert_eq!(stats.row_groups_written, row_groups); +} diff --git a/tools/curate-etl/tests/parquet_fx_contract.rs b/tools/curate-etl/tests/parquet_fx_contract.rs new file mode 100644 index 00000000..e414be86 --- /dev/null +++ b/tools/curate-etl/tests/parquet_fx_contract.rs @@ -0,0 +1,669 @@ +//! Contract tests for the public `fx_1d` Parquet writer API (T-94 / M1.2l). +//! +//! Uses only the crate's public surface (`build_fx_1d`, `Fx1dParquetRow::from_fx_row`, +//! `write_fx_1d_dataset`, `fx_1d_parquet_schema`, the `curate-etl` binary) plus an independent +//! Parquet column reader, guarding the `design/DATA-CONTRACTS.md` §3A `fx_1d/part.parquet` +//! schema, atomic single-file publish semantics, validation errors, concurrency serialization, +//! determinism, and the `bench-parquet-fx` CLI contract. + +use std::borrow::Cow; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Barrier}; +use std::thread; + +use curate_etl::{ + build_fx_1d, fx_1d_parquet_schema, write_fx_1d_dataset, ymd_to_epoch_days, Fx1dParquetRow, + Fx1dWriteOptions, Fx1dWriteStats, FxDailyBar, FxSource, ParquetFxError, FX_PAIR_USDCAD, +}; +use parquet::basic::{ + Compression, ConvertedType, Encoding, LogicalType, Repetition, TimeUnit, Type as PhysicalType, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-fx-contract-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn part_path(out: &Path) -> PathBuf { + out.join("fx_1d/part.parquet") +} + +fn ts_for_day(session_date: i32) -> i64 { + i64::from(session_date) * 86_400_000_000 + 22 * 3_600_000_000 +} + +fn row( + pair: &'static str, + session_date: i32, + open: f64, + high: f64, + low: f64, + close: f64, + source: FxSource, +) -> Fx1dParquetRow { + let ts_micros = ts_for_day(session_date); + Fx1dParquetRow { + pair: Cow::Borrowed(pair), + session_date, + ts_micros, + open, + high, + low, + close, + source: Cow::Borrowed(source.as_str()), + known_at_micros: ts_micros + 60_000_000, + } +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let n = meta.row_group(rg).num_rows() as usize; + let g = reader.get_row_group(rg).expect("row group"); + let col = |i: usize| g.get_column_reader(i).expect("column reader"); + + let i32s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::Int32ColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected INT32"), + } + v + }; + let i64s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::Int64ColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected INT64"), + } + v + }; + let f64s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::DoubleColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected DOUBLE"), + } + v + }; + let strs = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::ByteArrayColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected BYTE_ARRAY"), + } + v.iter() + .map(|b| std::str::from_utf8(b.data()).expect("utf8").to_string()) + .collect() + }; + + let pairs = strs(col(0)); + let dates = i32s(col(1)); + let tss = i64s(col(2)); + let opens = f64s(col(3)); + let highs = f64s(col(4)); + let lows = f64s(col(5)); + let closes = f64s(col(6)); + let sources = strs(col(7)); + let known_ats = i64s(col(8)); + + for i in 0..n { + out.push(Fx1dParquetRow { + pair: Cow::Owned(pairs[i].clone()), + session_date: dates[i], + ts_micros: tss[i], + open: opens[i], + high: highs[i], + low: lows[i], + close: closes[i], + source: Cow::Owned(sources[i].clone()), + known_at_micros: known_ats[i], + }); + } + } + out +} + +fn assert_rows_bitwise(actual: &[Fx1dParquetRow], expected: &[Fx1dParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.pair, e.pair, "row {i} pair"); + assert_eq!(a.session_date, e.session_date, "row {i} session_date"); + assert_eq!(a.ts_micros, e.ts_micros, "row {i} ts"); + assert_eq!(a.open.to_bits(), e.open.to_bits(), "row {i} open"); + assert_eq!(a.high.to_bits(), e.high.to_bits(), "row {i} high"); + assert_eq!(a.low.to_bits(), e.low.to_bits(), "row {i} low"); + assert_eq!(a.close.to_bits(), e.close.to_bits(), "row {i} close"); + assert_eq!(a.source, e.source, "row {i} source"); + assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at"); + } +} + +fn list_files(dir: &Path) -> Vec { + fn walk(root: &Path, dir: &Path, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + for entry in entries { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(root, &path, out); + } else { + out.push(path.strip_prefix(root).unwrap().display().to_string()); + } + } + } + let mut out = Vec::new(); + walk(dir, dir, &mut out); + out.sort(); + out +} + +#[test] +fn build_fx_1d_round_trip_matches_contract_schema_zstd_dict_and_bitwise_values() { + let tmp = TempDir::new("contract"); + let eod = [ + FxDailyBar { + session_date: day(1969, 12, 31), // pre-1970 negative epoch day (-1) + open: 1.0731, + high: 1.0755, + low: 1.0710, + close: 1.0742, + }, + FxDailyBar { + session_date: day(1971, 1, 4), + open: 1.0105, + high: 1.0120, + low: 1.0090, + close: 1.0112, + }, + FxDailyBar { + session_date: day(2025, 1, 2), + open: 1.4305, + high: 1.4402, + low: 1.4251, + close: 1.4357, + }, + ]; + let te = [ + FxDailyBar { + session_date: day(2025, 1, 2), // overlaps EOD -> EOD wins + open: 1.4310, + high: 1.4410, + low: 1.4260, + close: 1.4360, + }, + FxDailyBar { + session_date: day(2025, 1, 3), // interior/tail gap -> TE fills + open: 1.4340, + high: 1.4395, + low: 1.4310, + close: 1.4375, + }, + FxDailyBar { + session_date: day(2026, 1, 2), + open: 1.3805, + high: 1.3900, + low: 1.3750, + close: 1.3855, + }, + ]; + + let built = build_fx_1d(&eod, &te); + assert_eq!(built.rows.len(), 5); + let rows: Vec = built + .rows + .iter() + .map(|r| { + let ts = ts_for_day(r.session_date); + Fx1dParquetRow::from_fx_row(r, ts, ts + 300_000_000) + }) + .collect(); + + let opts = Fx1dWriteOptions { + row_group_rows: 2, + ..Fx1dWriteOptions::default() + }; + let stats = write_fx_1d_dataset(&tmp.0, &rows, opts).unwrap(); + assert_eq!(stats.rows_written, 5); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 3); + + let path = part_path(&tmp.0); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + let file_schema = meta.file_metadata().schema(); + let public_schema = fx_1d_parquet_schema().unwrap(); + assert_eq!(file_schema, public_schema.as_ref()); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 9] = [ + ( + "pair", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "session_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "ts", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "open", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "high", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "low", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "close", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ]; + let fields = file_schema.get_fields(); + assert_eq!(fields.len(), expected.len()); + for (i, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + assert_eq!(fields[i].name(), name); + assert_eq!(fields[i].get_physical_type(), phys); + assert_eq!(fields[i].get_basic_info().repetition(), rep); + assert_eq!(fields[i].get_basic_info().logical_type_ref().cloned(), logical); + assert_eq!(fields[i].get_basic_info().converted_type(), converted); + } + + for rg in meta.row_groups() { + for c in rg.columns() { + assert!( + matches!(c.compression(), Compression::ZSTD(_)), + "{} not ZSTD", + c.column_path() + ); + } + assert!( + rg.column(0) + .encodings() + .any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)), + "pair column must use dictionary encoding" + ); + assert!( + rg.column(7) + .encodings() + .any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)), + "source column must use dictionary encoding" + ); + } + + let got = read_rows(&path); + assert_rows_bitwise(&got, &rows); + for (actual, built_row) in got.iter().zip(&built.rows) { + assert_eq!(actual.pair.as_ref(), built_row.pair); + assert_eq!(actual.session_date, built_row.session_date); + assert_eq!(actual.open.to_bits(), built_row.open.to_bits()); + assert_eq!(actual.high.to_bits(), built_row.high.to_bits()); + assert_eq!(actual.low.to_bits(), built_row.low.to_bits()); + assert_eq!(actual.close.to_bits(), built_row.close.to_bits()); + assert_eq!(actual.source.as_ref(), built_row.source.as_str()); + } + assert_eq!(list_files(&tmp.0.join("fx_1d")), ["part.parquet"]); +} + +#[test] +fn row_group_boundaries_overwrite_empty_and_byte_identical_rerun() { + let tmp = TempDir::new("edges"); + let base = day(2024, 1, 2); + let rows = vec![ + row("EURUSD", base, 1.09, 1.10, 1.08, 1.095, FxSource::EodCadForex), + row("EURUSD", base + 1, 1.095, 1.105, 1.09, 1.10, FxSource::TeUsdCad), + row(FX_PAIR_USDCAD, day(1969, 12, 31), 1.073, 1.076, 1.071, 1.074, FxSource::EodCadForex), + row(FX_PAIR_USDCAD, base, 1.34, 1.35, 1.335, 1.345, FxSource::EodCadForex), + row(FX_PAIR_USDCAD, base + 1, 1.345, 1.355, 1.34, 1.35, FxSource::TeUsdCad), + ]; + + let opts = Fx1dWriteOptions { + row_group_rows: 4, + ..Fx1dWriteOptions::default() + }; + let s_eq = write_fx_1d_dataset(&tmp.0, &rows[..4], opts).unwrap(); + assert_eq!(s_eq.row_groups_written, 1); + + // Overwrite with 5 rows -> 2 row groups [4, 1] + let s_plus = write_fx_1d_dataset(&tmp.0, &rows, opts).unwrap(); + assert_eq!(s_plus.rows_written, 5); + assert_eq!(s_plus.row_groups_written, 2); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &rows); + assert_eq!(list_files(&tmp.0.join("fx_1d")), ["part.parquet"]); + + // Empty input does not destroy existing part.parquet + let bytes_before = fs::read(part_path(&tmp.0)).unwrap(); + let s_empty = + write_fx_1d_dataset(&tmp.0, std::iter::empty::(), opts).unwrap(); + assert_eq!(s_empty, Fx1dWriteStats::default()); + assert_eq!(fs::read(part_path(&tmp.0)).unwrap(), bytes_before); + + // Determinism: second directory yields byte-identical file + let tmp2 = TempDir::new("edges-rerun"); + write_fx_1d_dataset(&tmp2.0, &rows, opts).unwrap(); + assert_eq!(fs::read(part_path(&tmp2.0)).unwrap(), bytes_before); +} + +#[test] +fn invalid_inputs_return_typed_errors_and_leave_existing_file_byte_identical() { + let tmp = TempDir::new("invalid"); + let fresh = tmp.0.join("fresh"); + let seeded = tmp.0.join("seeded"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 3, 18); + let seed = vec![row( + FX_PAIR_USDCAD, + d1, + 1.35, + 1.36, + 1.34, + 1.355, + FxSource::EodCadForex, + )]; + write_fx_1d_dataset(&seeded, &seed, Fx1dWriteOptions::default()).unwrap(); + let before = fs::read(part_path(&seeded)).unwrap(); + + // Option validation errors + for opts in [ + Fx1dWriteOptions { + row_group_rows: 0, + ..Fx1dWriteOptions::default() + }, + Fx1dWriteOptions { + zstd_level: 99, + ..Fx1dWriteOptions::default() + }, + ] { + let e1 = write_fx_1d_dataset(&fresh, &seed, opts).unwrap_err(); + let e2 = write_fx_1d_dataset(&seeded, &seed, opts).unwrap_err(); + if opts.row_group_rows == 0 { + assert!(matches!(e1, ParquetFxError::InvalidRowGroupRows)); + assert!(matches!(e2, ParquetFxError::InvalidRowGroupRows)); + } else { + assert!(matches!(e1, ParquetFxError::InvalidZstdLevel { level: 99 })); + assert!(matches!(e2, ParquetFxError::InvalidZstdLevel { level: 99 })); + } + assert!(!part_path(&fresh).exists()); + assert_eq!(fs::read(part_path(&seeded)).unwrap(), before); + } + + let ts = ts_for_day(d1); + let day_start = i64::from(d1) * 86_400_000_000; + let cases: Vec<(&str, Vec)> = vec![ + ( + "unsorted", + vec![ + row(FX_PAIR_USDCAD, d2, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex), + row(FX_PAIR_USDCAD, d1, 1.34, 1.35, 1.33, 1.345, FxSource::EodCadForex), + ], + ), + ( + "duplicate", + vec![ + row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex), + row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::TeUsdCad), + ], + ), + ( + "empty_pair", + vec![Fx1dParquetRow { + pair: Cow::Borrowed(" "), + ..row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex) + }], + ), + ( + "empty_source", + vec![Fx1dParquetRow { + source: Cow::Borrowed(""), + ..row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex) + }], + ), + ( + "invalid_ohlc", + vec![row(FX_PAIR_USDCAD, d1, f64::NAN, 1.36, 1.34, 1.35, FxSource::EodCadForex)], + ), + ( + "inconsistent_ohlc", + vec![row(FX_PAIR_USDCAD, d1, 1.35, 1.33, 1.36, 1.35, FxSource::EodCadForex)], + ), + ( + "ts_outside", + vec![Fx1dParquetRow { + ts_micros: day_start - 1, + known_at_micros: day_start - 1, + ..row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex) + }], + ), + ( + "known_at_before_ts", + vec![Fx1dParquetRow { + ts_micros: ts, + known_at_micros: ts - 1, + ..row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex) + }], + ), + ]; + + for (label, bad_rows) in cases { + for (dir_label, dir) in [("fresh", &fresh), ("seeded", &seeded)] { + let err = + write_fx_1d_dataset(dir, &bad_rows, Fx1dWriteOptions::default()).unwrap_err(); + match (label, &err) { + ("unsorted", ParquetFxError::UnsortedInput { .. }) => {} + ("duplicate", ParquetFxError::DuplicateKey { .. }) => {} + ("empty_pair", ParquetFxError::EmptyPair { .. }) => {} + ("empty_source", ParquetFxError::EmptySource { .. }) => {} + ("invalid_ohlc", ParquetFxError::InvalidOhlc { .. }) => {} + ("inconsistent_ohlc", ParquetFxError::InconsistentOhlc { .. }) => {} + ("ts_outside", ParquetFxError::TsOutsideSessionDate { .. }) => {} + ("known_at_before_ts", ParquetFxError::KnownAtBeforeTs { .. }) => {} + other => panic!("unexpected error for case {label} ({dir_label}): {other:?}"), + } + } + assert!( + !part_path(&fresh).exists(), + "case {label} created part.parquet in fresh dir" + ); + assert_eq!( + fs::read(part_path(&seeded)).unwrap(), + before, + "case {label} modified existing part.parquet" + ); + assert_eq!( + list_files(&seeded.join("fx_1d")), + ["part.parquet"], + "case {label} left transient files behind" + ); + } + + // out_dir occupied by a regular file returns Io error + let file_out = tmp.0.join("not-a-dir"); + fs::write(&file_out, b"x").unwrap(); + let io_err = write_fx_1d_dataset(&file_out, &seed, Fx1dWriteOptions::default()).unwrap_err(); + assert!(matches!(io_err, ParquetFxError::Io { .. })); + assert!(std::error::Error::source(&io_err).is_some()); +} + +#[test] +fn concurrent_in_process_writers_publish_one_complete_generation_and_no_transients() { + let tmp = TempDir::new("concurrent"); + let out = Arc::new(tmp.0.clone()); + let base = day(2020, 1, 2); + let make = |base_rate: f64| -> Vec { + (0..1_000_i32) + .map(|i| { + let open = base_rate + f64::from(i) * 0.0001; + row( + FX_PAIR_USDCAD, + base + i, + open, + open + 0.005, + open - 0.004, + open + 0.001, + if i % 4 == 0 { + FxSource::TeUsdCad + } else { + FxSource::EodCadForex + }, + ) + }) + .collect() + }; + let gens = Arc::new([make(1.25), make(1.40)]); + let barrier = Arc::new(Barrier::new(2)); + let handles: Vec<_> = (0..2) + .map(|g| { + let (out, gens, barrier) = (out.clone(), gens.clone(), barrier.clone()); + thread::spawn(move || { + barrier.wait(); + let opts = Fx1dWriteOptions { + row_group_rows: 131, + ..Fx1dWriteOptions::default() + }; + write_fx_1d_dataset(out.as_path(), &gens[g], opts) + }) + }) + .collect(); + for h in handles { + let stats = h.join().expect("writer thread").expect("writer result"); + assert_eq!(stats.rows_written, 1_000); + assert_eq!(stats.files_written, 1); + } + + let got = read_rows(&part_path(&tmp.0)); + let g = if got.first().map(|r| r.open) == Some(1.25) { + 0 + } else { + 1 + }; + assert_rows_bitwise(&got, &gens[g]); + assert_eq!(list_files(&tmp.0.join("fx_1d")), ["part.parquet"]); +} + +#[test] +fn bench_parquet_fx_cli_prints_metrics_and_removes_its_temp_dir() { + let tmp = TempDir::new("cli"); + let out = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(["bench-parquet-fx", "20000"]) + .env("TMPDIR", &tmp.0) + .output() + .expect("spawn curate-etl"); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + for needle in [ + "curate-etl bench-parquet-fx", + "rows=20000", + "read_back_rows=20000", + "row_groups=", + "bytes=", + "elapsed=", + "rows/s", + "MB/s", + "bytes/row", + "compression=", + ] { + assert!(stdout.contains(needle), "missing '{needle}' in:\n{stdout}"); + } + let leftovers: Vec<_> = fs::read_dir(&tmp.0).unwrap().collect(); + assert!( + leftovers.is_empty(), + "benchmark left files in TMPDIR: {leftovers:?}" + ); + + let bad = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(["bench-parquet-fx", "0"]) + .env("TMPDIR", &tmp.0) + .output() + .expect("spawn curate-etl"); + assert!(!bad.status.success()); + assert!(String::from_utf8_lossy(&bad.stderr).contains("bench-parquet-fx")); +} diff --git a/tools/curate-etl/tests/parquet_fx_edge_contract.rs b/tools/curate-etl/tests/parquet_fx_edge_contract.rs new file mode 100644 index 00000000..0740cfe5 --- /dev/null +++ b/tools/curate-etl/tests/parquet_fx_edge_contract.rs @@ -0,0 +1,489 @@ +//! QA edge-case contract tests for the public `fx_1d` Parquet writer (T-94 / M1.2l). +//! +//! Complements `parquet_fx_contract.rs` through the public API only: inclusive OHLC bounds +//! and extreme positive floats, owned / non-ASCII pair labels with bytewise ordering, pairs +//! spanning row-group boundaries, every validation variant raised late in the stream after +//! flushed row groups (existing file byte-identical, lock released for a retry), Zstd level +//! bounds, `known_at` far in the future, and `Display` / `source()` of typed errors. + +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + write_fx_1d_dataset, ymd_to_epoch_days, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, + ParquetFxError, +}; +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_DAY: i64 = 86_400_000_000; +const EOD: &str = "eod_cad_forex"; +const TE: &str = "te_usdcad"; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-fx-edge-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn part_path(out: &Path) -> PathBuf { + out.join("fx_1d/part.parquet") +} + +fn row(pair: &'static str, session_date: i32, o: f64, h: f64, l: f64, c: f64) -> Fx1dParquetRow { + let ts = i64::from(session_date) * MICROS_PER_DAY + 21 * 3_600_000_000; + Fx1dParquetRow { + pair: Cow::Borrowed(pair), + session_date, + ts_micros: ts, + open: o, + high: h, + low: l, + close: c, + source: Cow::Borrowed(EOD), + known_at_micros: ts, + } +} + +fn opts(row_group_rows: usize) -> Fx1dWriteOptions { + Fx1dWriteOptions { + row_group_rows, + ..Fx1dWriteOptions::default() + } +} + +fn list_files(dir: &Path) -> Vec { + let Ok(entries) = fs::read_dir(dir) else { + return Vec::new(); + }; + let mut names: Vec = entries + .map(|e| { + e.expect("dir entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .collect(); + names.sort(); + names +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let rg_reader = reader.get_row_group(rg).expect("rg"); + let n = meta.row_group(rg).num_rows() as usize; + let strs = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::ByteArrayColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected BYTE_ARRAY at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + v.into_iter() + .map(|b| String::from_utf8(b.data().to_vec()).expect("utf8")) + .collect() + }; + let i32s = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::Int32ColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected INT32 at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + v + }; + let i64s = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::Int64ColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected INT64 at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + v + }; + let f64s = |idx: usize| -> Vec { + let mut v = Vec::new(); + let ColumnReader::DoubleColumnReader(mut r) = + rg_reader.get_column_reader(idx).expect("col") + else { + panic!("expected DOUBLE at {idx}"); + }; + r.read_records(n, None, None, &mut v).expect("read"); + v + }; + let (pair, sd, ts, o, h, l, c, src, ka) = ( + strs(0), + i32s(1), + i64s(2), + f64s(3), + f64s(4), + f64s(5), + f64s(6), + strs(7), + i64s(8), + ); + assert_eq!(pair.len(), n); + for i in 0..n { + out.push(Fx1dParquetRow { + pair: Cow::Owned(pair[i].clone()), + session_date: sd[i], + ts_micros: ts[i], + open: o[i], + high: h[i], + low: l[i], + close: c[i], + source: Cow::Owned(src[i].clone()), + known_at_micros: ka[i], + }); + } + } + out +} + +fn assert_bitwise(actual: &[Fx1dParquetRow], expected: &[Fx1dParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.pair, e.pair, "row {i} pair"); + assert_eq!(a.session_date, e.session_date, "row {i} session_date"); + assert_eq!(a.ts_micros, e.ts_micros, "row {i} ts"); + assert_eq!(a.open.to_bits(), e.open.to_bits(), "row {i} open"); + assert_eq!(a.high.to_bits(), e.high.to_bits(), "row {i} high"); + assert_eq!(a.low.to_bits(), e.low.to_bits(), "row {i} low"); + assert_eq!(a.close.to_bits(), e.close.to_bits(), "row {i} close"); + assert_eq!(a.source, e.source, "row {i} source"); + assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at"); + } +} + +#[test] +fn inclusive_ohlc_bounds_and_extreme_positive_floats_round_trip_bitwise() { + // Arrange: flat bar, open == low, close == high, open == high, close == low, + // smallest subnormal, MIN_POSITIVE and MAX are all valid (finite, > 0, consistent). + let tmp = TempDir::new("ohlc-bounds"); + let d = day(2024, 6, 3); + let tiny = f64::from_bits(1); // smallest positive subnormal + let rows = vec![ + row("USDCAD", d, 1.37, 1.37, 1.37, 1.37), + row("USDCAD", d + 1, 1.36, 1.38, 1.36, 1.38), + row("USDCAD", d + 2, 1.38, 1.38, 1.36, 1.36), + row("USDCAD", d + 3, tiny, tiny, tiny, tiny), + row( + "USDCAD", + d + 4, + f64::MIN_POSITIVE, + f64::MAX, + f64::MIN_POSITIVE, + f64::MAX, + ), + row("USDCAD", d + 5, 0.1 + 0.2, 0.30000000000000004, 0.3, 0.3), + ]; + + // Act + let stats = write_fx_1d_dataset(tmp.0.as_path(), &rows, opts(4)).unwrap(); + + // Assert + assert_eq!(stats.rows_written, 6); + assert_eq!(stats.row_groups_written, 2); + assert_bitwise(&read_rows(&part_path(&tmp.0)), &rows); +} + +#[test] +fn owned_rows_by_value_and_non_ascii_pairs_sort_bytewise_and_round_trip() { + // Arrange: rows yielded by value with owned strings; ordering is bytewise + // ("USDCAD" < "usdcad" < "ÉURUSD" since 0xC3 > 'u'). + let tmp = TempDir::new("owned"); + let d = day(1965, 3, 1); // negative epoch day + assert!(d < 0); + let mk = |pair: &str, sd: i32, src: &str| Fx1dParquetRow { + pair: Cow::Owned(pair.to_owned()), + source: Cow::Owned(src.to_owned()), + ..row("X", sd, 1.1, 1.2, 1.0, 1.15) + }; + let rows = vec![ + mk("USDCAD", d, EOD), + mk("USDCAD", d + 1, TE), + mk("usdcad", d, TE), + mk("ÉURUSD", d, "source-ü"), + ]; + + // Act + let stats = write_fx_1d_dataset(tmp.0.as_path(), rows.clone(), opts(1)).unwrap(); + + // Assert + assert_eq!(stats.rows_written, 4); + assert_eq!(stats.row_groups_written, 4); + assert_bitwise(&read_rows(&part_path(&tmp.0)), &rows); + + // Reversed non-ASCII ordering is rejected as unsorted. + let bad = vec![mk("ÉURUSD", d, EOD), mk("USDCAD", d, EOD)]; + let err = write_fx_1d_dataset(tmp.0.as_path(), bad, opts(1)).unwrap_err(); + assert!( + matches!(&err, ParquetFxError::UnsortedInput { prev_pair, pair, .. } + if prev_pair == "ÉURUSD" && pair == "USDCAD"), + "got {err:?}" + ); + assert_bitwise(&read_rows(&part_path(&tmp.0)), &rows); +} + +#[test] +fn pairs_and_sources_spanning_row_group_boundaries_keep_values_per_group() { + // Arrange: 3 pairs x 5 days, alternating sources, row_group_rows = 4 so pair runs + // straddle row-group boundaries (interners are cleared between groups). + let tmp = TempDir::new("span"); + let base = day(2023, 1, 2); + let mut rows = Vec::new(); + for (pi, pair) in ["AUDUSD", "EURUSD", "USDCAD"].into_iter().enumerate() { + for k in 0..5 { + let mut r = row(pair, base + k, 1.0, 1.1, 0.9, 1.05); + r.source = Cow::Borrowed(if (pi + k as usize) % 2 == 0 { EOD } else { TE }); + r.close = 0.9 + 0.01 * f64::from(k); + rows.push(r); + } + } + + // Act + let stats = write_fx_1d_dataset(tmp.0.as_path(), &rows, opts(4)).unwrap(); + + // Assert + assert_eq!( + stats, + Fx1dWriteStats { + rows_written: 15, + files_written: 1, + row_groups_written: 4, + bytes_written: fs::metadata(part_path(&tmp.0)).unwrap().len(), + } + ); + let reader = SerializedFileReader::new(File::open(part_path(&tmp.0)).unwrap()).unwrap(); + let sizes: Vec = reader + .metadata() + .row_groups() + .iter() + .map(|rg| rg.num_rows()) + .collect(); + assert_eq!(sizes, vec![4, 4, 4, 3]); + assert_bitwise(&read_rows(&part_path(&tmp.0)), &rows); +} + +#[test] +fn every_validation_variant_late_in_stream_preserves_existing_file_and_releases_lock() { + // Arrange: seed a live file, then for each variant stream 10 valid rows + // (5 flushed row groups at row_group_rows = 2) followed by one bad row. + let tmp = TempDir::new("late"); + let out = tmp.0.as_path(); + let base = day(2020, 1, 1); + let seed = vec![row("USDCAD", base - 10, 1.3, 1.31, 1.29, 1.3)]; + write_fx_1d_dataset(out, &seed, Fx1dWriteOptions::default()).unwrap(); + let before = fs::read(part_path(out)).unwrap(); + + let prefix: Vec = (0..10) + .map(|k| row("USDCAD", base + k, 1.3, 1.31, 1.29, 1.3)) + .collect(); + let next = base + 10; + let last_ts = prefix[9].ts_micros; + let ok = || row("USDCAD", next, 1.3, 1.31, 1.29, 1.3); + type Check = fn(&ParquetFxError) -> bool; + let cases: Vec<(&str, Fx1dParquetRow, Check)> = vec![ + ( + "unsorted", + row("USDCAD", base + 3, 1.3, 1.31, 1.29, 1.3), + |e| matches!(e, ParquetFxError::UnsortedInput { .. }), + ), + ( + "unsorted-pair", + row("AUDUSD", next, 1.3, 1.31, 1.29, 1.3), + |e| matches!(e, ParquetFxError::UnsortedInput { .. }), + ), + ( + "duplicate", + row("USDCAD", base + 9, 1.3, 1.31, 1.29, 1.3), + |e| matches!(e, ParquetFxError::DuplicateKey { .. }), + ), + ( + "empty-pair", + Fx1dParquetRow { + pair: Cow::Borrowed(" "), + ..ok() + }, + |e| matches!(e, ParquetFxError::EmptyPair { .. }), + ), + ( + "empty-source", + Fx1dParquetRow { + source: Cow::Borrowed(""), + ..ok() + }, + |e| matches!(e, ParquetFxError::EmptySource { .. }), + ), + ( + "invalid-ohlc", + Fx1dParquetRow { + close: f64::NAN, + ..ok() + }, + |e| matches!(e, ParquetFxError::InvalidOhlc { .. }), + ), + ( + "inconsistent-ohlc", + Fx1dParquetRow { + high: 1.295, + ..ok() + }, + |e| matches!(e, ParquetFxError::InconsistentOhlc { .. }), + ), + ( + "ts-outside", + Fx1dParquetRow { + ts_micros: last_ts, + known_at_micros: last_ts, + ..ok() + }, + |e| matches!(e, ParquetFxError::TsOutsideSessionDate { .. }), + ), + ( + "known-at", + Fx1dParquetRow { + known_at_micros: ok().ts_micros - 1, + ..ok() + }, + |e| matches!(e, ParquetFxError::KnownAtBeforeTs { .. }), + ), + ]; + + for (name, bad, check) in cases { + let stream: Vec = prefix.iter().cloned().chain([bad]).collect(); + + // Act + let err = write_fx_1d_dataset(out, &stream, opts(2)).unwrap_err(); + + // Assert + assert!(check(&err), "{name}: unexpected error {err:?}"); + assert!(!err.to_string().is_empty(), "{name}: empty Display"); + assert!( + err.source().is_none(), + "{name}: validation errors have no source" + ); + assert_eq!( + fs::read(part_path(out)).unwrap(), + before, + "{name}: live file changed" + ); + assert_eq!( + list_files(&out.join("fx_1d")), + vec!["part.parquet"], + "{name}: leftovers" + ); + } + + // A follow-up valid write succeeds immediately (lock released, no stale state). + let mut good = prefix.clone(); + good.push(ok()); + let stats = write_fx_1d_dataset(out, &good, opts(2)).unwrap(); + assert_eq!(stats.rows_written, 11); + assert_eq!(stats.row_groups_written, 6); + assert_bitwise(&read_rows(&part_path(out)), &good); + assert_eq!(list_files(&out.join("fx_1d")), vec!["part.parquet"]); +} + +#[test] +fn zstd_level_bounds_produce_readable_zstd_files_and_out_of_range_is_rejected_first() { + let tmp = TempDir::new("zstd"); + let rows = vec![row("USDCAD", day(2024, 2, 1), 1.35, 1.36, 1.34, 1.355)]; + + for level in [1, 22] { + let out = tmp.0.join(format!("lvl-{level}")); + let o = Fx1dWriteOptions { + zstd_level: level, + ..Fx1dWriteOptions::default() + }; + write_fx_1d_dataset(&out, &rows, o).unwrap(); + let reader = SerializedFileReader::new(File::open(part_path(&out)).unwrap()).unwrap(); + for col in reader.metadata().row_group(0).columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "level {level}" + ); + } + assert_bitwise(&read_rows(&part_path(&out)), &rows); + } + + // Option errors win over row errors and create nothing. + let bad_rows = vec![Fx1dParquetRow { + pair: Cow::Borrowed(""), + ..rows[0].clone() + }]; + for level in [23, i32::MAX] { + let out = tmp.0.join(format!("bad-{level}")); + let o = Fx1dWriteOptions { + zstd_level: level, + ..Fx1dWriteOptions::default() + }; + let err = write_fx_1d_dataset(&out, &bad_rows, o).unwrap_err(); + assert!( + matches!(err, ParquetFxError::InvalidZstdLevel { level: l } if l == level), + "got {err:?}" + ); + assert!(!out.exists()); + } + let out = tmp.0.join("bad-rg"); + let err = write_fx_1d_dataset( + &out, + &bad_rows, + Fx1dWriteOptions { + row_group_rows: 0, + zstd_level: 99, + }, + ) + .unwrap_err(); + assert!( + matches!(err, ParquetFxError::InvalidRowGroupRows), + "got {err:?}" + ); + assert!(!out.exists()); +} + +#[test] +fn known_at_far_future_is_accepted_and_round_trips() { + // known_at has no upper bound in this writer (caller policy); i64::MAX must pass. + let tmp = TempDir::new("known-at-max"); + let d = day(1971, 1, 4); + let rows = vec![Fx1dParquetRow { + known_at_micros: i64::MAX, + source: Cow::Borrowed(TE), + ..row("USDCAD", d, 1.01, 1.02, 1.0, 1.015) + }]; + let stats = write_fx_1d_dataset(tmp.0.as_path(), &rows, Fx1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 1); + assert_bitwise(&read_rows(&part_path(&tmp.0)), &rows); +} diff --git a/tools/curate-etl/tests/parquet_shorts_contract.rs b/tools/curate-etl/tests/parquet_shorts_contract.rs new file mode 100644 index 00000000..904df543 --- /dev/null +++ b/tools/curate-etl/tests/parquet_shorts_contract.rs @@ -0,0 +1,543 @@ +//! Contract tests for the public `shorts` Parquet writer API (T-92 / M1.2j). +//! +//! Uses only the crate's public surface (`build_shorts`, `write_shorts_dataset`, +//! `shorts_parquet_schema`, the `curate-etl` binary) plus an independent Parquet column reader, +//! guarding the `design/DATA-CONTRACTS.md` §3A `shorts/part.parquet` schema, atomic single-file +//! publish semantics, validation errors, concurrency serialization, determinism, and the +//! `bench-parquet-shorts` CLI contract. + +use std::borrow::Cow; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Barrier}; +use std::thread; + +use curate_etl::{ + build_shorts, shorts_parquet_schema, write_shorts_dataset, ymd_to_epoch_days, CeoShortReport, + ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, ShortsWriteStats, SHORTS_SOURCE_CEO, +}; +use parquet::basic::{ + Compression, ConvertedType, Encoding, LogicalType, Repetition, TimeUnit, Type as PhysicalType, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-shorts-contract-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn part_path(out: &Path) -> PathBuf { + out.join("shorts/part.parquet") +} + +fn row( + listing_id: i32, + report_date: i32, + shares_short: f64, + net_change: Option, + pct_float: Option, +) -> ShortsParquetRow { + ShortsParquetRow { + listing_id, + report_date, + known_at_micros: i64::from(report_date + 6) * 86_400_000_000 + 21 * 3_600_000_000, + shares_short, + net_change, + pct_float, + source: Cow::Borrowed(SHORTS_SOURCE_CEO), + } +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let n = meta.row_group(rg).num_rows() as usize; + let g = reader.get_row_group(rg).expect("row group"); + let col = |i: usize| g.get_column_reader(i).expect("column reader"); + + let i32s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::Int32ColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected INT32"), + } + v + }; + let i64s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::Int64ColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected INT64"), + } + v + }; + let f64s = |c: ColumnReader| -> Vec> { + let mut v = Vec::new(); + let mut defs = Vec::new(); + match c { + ColumnReader::DoubleColumnReader(mut r) => { + assert_eq!( + r.read_records(n, Some(&mut defs), None, &mut v).unwrap().0, + n + ); + } + _ => panic!("expected DOUBLE"), + } + if defs.is_empty() { + return v.into_iter().map(Some).collect(); + } + let mut it = v.into_iter(); + defs.iter() + .map(|&d| if d == 1 { it.next() } else { None }) + .collect() + }; + let strs = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::ByteArrayColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected BYTE_ARRAY"), + } + v.iter() + .map(|b| std::str::from_utf8(b.data()).expect("utf8").to_string()) + .collect() + }; + + let lid = i32s(col(0)); + let rd = i32s(col(1)); + let ka = i64s(col(2)); + let ss: Vec = f64s(col(3)) + .into_iter() + .map(|x| x.expect("required shares_short")) + .collect(); + let nc = f64s(col(4)); + let pf = f64s(col(5)); + let src = strs(col(6)); + + for i in 0..n { + out.push(ShortsParquetRow { + listing_id: lid[i], + report_date: rd[i], + known_at_micros: ka[i], + shares_short: ss[i], + net_change: nc[i], + pct_float: pf[i], + source: Cow::Owned(src[i].clone()), + }); + } + } + out +} + +fn assert_rows_bitwise(actual: &[ShortsParquetRow], expected: &[ShortsParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id"); + assert_eq!(a.report_date, e.report_date, "row {i} report_date"); + assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at"); + assert_eq!( + a.shares_short.to_bits(), + e.shares_short.to_bits(), + "row {i} shares_short" + ); + assert_eq!( + a.net_change.map(f64::to_bits), + e.net_change.map(f64::to_bits), + "row {i} net_change" + ); + assert_eq!( + a.pct_float.map(f64::to_bits), + e.pct_float.map(f64::to_bits), + "row {i} pct_float" + ); + assert_eq!(a.source, e.source, "row {i} source"); + } +} + +fn list_files(dir: &Path) -> Vec { + fn walk(root: &Path, dir: &Path, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + for entry in entries { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(root, &path, out); + } else { + out.push(path.strip_prefix(root).unwrap().display().to_string()); + } + } + } + let mut out = Vec::new(); + walk(dir, dir, &mut out); + out.sort(); + out +} + +#[test] +fn build_shorts_round_trip_matches_contract_schema_zstd_and_bitwise_values() { + let tmp = TempDir::new("contract"); + let built = build_shorts(vec![ + CeoShortReport { + key: 42_i32, + report_date: day(2024, 3, 28), // Good Friday rollover + shares_short: 250_000.0, + net_change: Some(12_500.0), + pct_float: Some(4.75), + }, + CeoShortReport { + key: 42_i32, + report_date: day(2024, 4, 15), + shares_short: 0.0, + net_change: None, + pct_float: None, + }, + CeoShortReport { + key: 7_i32, + report_date: day(2023, 12, 29), // Year-end rollover + shares_short: 15_300.25, + net_change: Some(-300.5), + pct_float: None, + }, + ]) + .expect("build_shorts"); + + let rows_ref: Vec = built.rows.iter().map(ShortsParquetRow::from).collect(); + let rows_owned: Vec = + built.rows.into_iter().map(ShortsParquetRow::from).collect(); + assert_rows_bitwise(&rows_ref, &rows_owned); + + let stats = write_shorts_dataset(&tmp.0, &rows_ref, ShortsWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 1); + + let path = part_path(&tmp.0); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + let file_schema = meta.file_metadata().schema(); + let public_schema = shorts_parquet_schema().unwrap(); + assert_eq!(file_schema, public_schema.as_ref()); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 7] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "report_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "shares_short", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "net_change", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "pct_float", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ]; + let fields = file_schema.get_fields(); + assert_eq!(fields.len(), expected.len()); + for (i, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + assert_eq!(fields[i].name(), name); + assert_eq!(fields[i].get_physical_type(), phys); + assert_eq!(fields[i].get_basic_info().repetition(), rep); + assert_eq!(fields[i].get_basic_info().logical_type_ref().cloned(), logical); + assert_eq!(fields[i].get_basic_info().converted_type(), converted); + } + + for rg in meta.row_groups() { + for c in rg.columns() { + assert!( + matches!(c.compression(), Compression::ZSTD(_)), + "{} not ZSTD", + c.column_path() + ); + } + assert!( + rg.column(6) + .encodings() + .any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)), + "source column must use dictionary encoding" + ); + } + + assert_rows_bitwise(&read_rows(&path), &rows_ref); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); +} + +#[test] +fn row_group_boundaries_overwrite_empty_and_byte_identical_rerun() { + let tmp = TempDir::new("edges"); + let base = day(2024, 1, 15); + let rows: Vec = (0..5_i32) + .map(|i| { + row( + 1 + i / 3, + base + (i % 3) * 15, + 1_000.0 * f64::from(i), + if i % 2 == 0 { None } else { Some(50.0) }, + if i % 3 == 0 { Some(1.5) } else { None }, + ) + }) + .collect(); + + // Exact row_group_rows == 4 -> 1 group; 5 rows -> 2 groups [4, 1] + let opts = ShortsWriteOptions { + row_group_rows: 4, + ..ShortsWriteOptions::default() + }; + let s_eq = write_shorts_dataset(&tmp.0, &rows[..4], opts).unwrap(); + assert_eq!(s_eq.row_groups_written, 1); + + // Overwrite with 5 rows + let s_plus = write_shorts_dataset(&tmp.0, &rows, opts).unwrap(); + assert_eq!(s_plus.rows_written, 5); + assert_eq!(s_plus.row_groups_written, 2); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &rows); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); + + // Empty input does not destroy existing part.parquet + let bytes_before = fs::read(part_path(&tmp.0)).unwrap(); + let s_empty = + write_shorts_dataset(&tmp.0, std::iter::empty::(), opts).unwrap(); + assert_eq!(s_empty, ShortsWriteStats::default()); + assert_eq!(fs::read(part_path(&tmp.0)).unwrap(), bytes_before); + + // Determinism: second directory yields byte-identical file + let tmp2 = TempDir::new("edges-rerun"); + write_shorts_dataset(&tmp2.0, &rows, opts).unwrap(); + assert_eq!(fs::read(part_path(&tmp2.0)).unwrap(), bytes_before); +} + +#[test] +fn invalid_inputs_return_typed_errors_and_leave_existing_file_byte_identical() { + let tmp = TempDir::new("invalid"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 3, 31); + let seed = vec![row(1, d1, 10_000.0, Some(200.0), Some(2.0))]; + write_shorts_dataset(&tmp.0, &seed, ShortsWriteOptions::default()).unwrap(); + let before = fs::read(part_path(&tmp.0)).unwrap(); + + let cases: Vec<(&str, Vec)> = vec![ + ( + "unsorted", + vec![row(1, d2, 10.0, None, None), row(1, d1, 20.0, None, None)], + ), + ( + "duplicate", + vec![row(1, d1, 10.0, None, None), row(1, d1, 10.0, None, None)], + ), + ("nan_shares", vec![row(1, d1, f64::NAN, None, None)]), + ("neg_shares", vec![row(1, d1, -1.0, None, None)]), + ("inf_net_change", vec![row(1, d1, 10.0, Some(f64::INFINITY), None)]), + ("nan_pct_float", vec![row(1, d1, 10.0, None, Some(f64::NAN))]), + ( + "known_at_not_after", + vec![ShortsParquetRow { + known_at_micros: i64::from(d1) * 86_400_000_000, + ..row(1, d1, 10.0, None, None) + }], + ), + ( + "empty_source", + vec![ShortsParquetRow { + source: Cow::Borrowed(""), + ..row(1, d1, 10.0, None, None) + }], + ), + ]; + + for (label, bad_rows) in cases { + let err = + write_shorts_dataset(&tmp.0, &bad_rows, ShortsWriteOptions::default()).unwrap_err(); + match (label, &err) { + ("unsorted", ParquetShortsError::UnsortedInput { .. }) => {} + ("duplicate", ParquetShortsError::DuplicateKey { .. }) => {} + ("nan_shares" | "neg_shares", ParquetShortsError::InvalidSharesShort { .. }) => {} + ("inf_net_change", ParquetShortsError::InvalidNetChange { .. }) => {} + ("nan_pct_float", ParquetShortsError::InvalidPctFloat { .. }) => {} + ("known_at_not_after", ParquetShortsError::KnownAtNotAfterReportDate { .. }) => {} + ("empty_source", ParquetShortsError::EmptySource { .. }) => {} + other => panic!("unexpected error for case {label}: {other:?}"), + } + assert_eq!( + fs::read(part_path(&tmp.0)).unwrap(), + before, + "case {label} modified existing part.parquet" + ); + assert_eq!( + list_files(&tmp.0.join("shorts")), + ["part.parquet"], + "case {label} left transient files behind" + ); + } + + // out_dir occupied by a regular file returns Io error + let file_out = tmp.0.join("not-a-dir"); + fs::write(&file_out, b"x").unwrap(); + let io_err = write_shorts_dataset(&file_out, &seed, ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!(io_err, ParquetShortsError::Io { .. })); + assert!(std::error::Error::source(&io_err).is_some()); +} + +#[test] +fn concurrent_in_process_writers_publish_one_complete_generation_and_no_transients() { + let tmp = TempDir::new("concurrent"); + let out = Arc::new(tmp.0.clone()); + let base = day(2022, 1, 15); + let make = |base_shares: f64| -> Vec { + (0..1_000_i32) + .map(|i| { + row( + 1 + i / 200, + base + (i % 200) * 15, + base_shares + f64::from(i), + Some(f64::from(i)), + if i % 2 == 0 { None } else { Some(1.25) }, + ) + }) + .collect() + }; + let gens = Arc::new([make(1_000.0), make(9_000.0)]); + let barrier = Arc::new(Barrier::new(2)); + let handles: Vec<_> = (0..2) + .map(|g| { + let (out, gens, barrier) = (out.clone(), gens.clone(), barrier.clone()); + thread::spawn(move || { + barrier.wait(); + let opts = ShortsWriteOptions { + row_group_rows: 131, + ..ShortsWriteOptions::default() + }; + write_shorts_dataset(out.as_path(), &gens[g], opts) + }) + }) + .collect(); + for h in handles { + let stats = h.join().expect("writer thread").expect("writer result"); + assert_eq!(stats.rows_written, 1_000); + assert_eq!(stats.files_written, 1); + } + + let got = read_rows(&part_path(&tmp.0)); + let g = if got.first().map(|r| r.shares_short) == Some(1_000.0) { + 0 + } else { + 1 + }; + assert_rows_bitwise(&got, &gens[g]); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); +} + +#[test] +fn bench_parquet_shorts_cli_prints_metrics_and_removes_its_temp_dir() { + let tmp = TempDir::new("cli"); + let out = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(["bench-parquet-shorts", "20000"]) + .env("TMPDIR", &tmp.0) + .output() + .expect("spawn curate-etl"); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + for needle in [ + "curate-etl bench-parquet-shorts", + "rows=20000", + "read_back_rows=20000", + "rows/s", + "MB/s", + "bytes/row", + "compression=", + ] { + assert!(stdout.contains(needle), "missing '{needle}' in:\n{stdout}"); + } + let leftovers: Vec<_> = fs::read_dir(&tmp.0).unwrap().collect(); + assert!( + leftovers.is_empty(), + "benchmark left files in TMPDIR: {leftovers:?}" + ); + + let bad = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(["bench-parquet-shorts", "0"]) + .env("TMPDIR", &tmp.0) + .output() + .expect("spawn curate-etl"); + assert!(!bad.status.success()); + assert!(String::from_utf8_lossy(&bad.stderr).contains("bench-parquet-shorts")); +} diff --git a/tools/curate-etl/tests/parquet_shorts_edge_contract.rs b/tools/curate-etl/tests/parquet_shorts_edge_contract.rs new file mode 100644 index 00000000..091185fc --- /dev/null +++ b/tools/curate-etl/tests/parquet_shorts_edge_contract.rs @@ -0,0 +1,598 @@ +//! QA edge-case contract tests for the public `shorts` Parquet writer (T-92 / M1.2j). +//! +//! Complements `parquet_shorts_contract.rs` through the public API only: mid-stream failures +//! after flushed row groups, option validation ordering, exact `known_at` cutoffs (including +//! pre-1970 and extreme epoch days), bit-exact special floats, high-cardinality `source` +//! values across row groups, write-stat accounting, panic-unwind cleanup, blocker paths and +//! preservation of files the writer does not own. + +use std::borrow::Cow; +use std::fs::{self, File}; +use std::panic::{self, AssertUnwindSafe}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + write_shorts_dataset, ymd_to_epoch_days, ParquetShortsError, ShortsParquetRow, + ShortsWriteOptions, ShortsWriteStats, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL, + SHORTS_SOURCE_CEO, +}; +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_DAY: i64 = 86_400_000_000; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-shorts-edge-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn part_path(out: &Path) -> PathBuf { + out.join("shorts/part.parquet") +} + +fn row(listing_id: i32, report_date: i32, shares_short: f64) -> ShortsParquetRow { + ShortsParquetRow { + listing_id, + report_date, + known_at_micros: (i64::from(report_date) + 6) + .saturating_mul(MICROS_PER_DAY) + .saturating_add(21 * 3_600_000_000), + shares_short, + net_change: None, + pct_float: None, + source: Cow::Borrowed(SHORTS_SOURCE_CEO), + } +} + +fn opts(row_group_rows: usize) -> ShortsWriteOptions { + ShortsWriteOptions { + row_group_rows, + ..ShortsWriteOptions::default() + } +} + +fn list_files(dir: &Path) -> Vec { + let Ok(entries) = fs::read_dir(dir) else { + return Vec::new(); + }; + let mut out: Vec = entries + .map(|e| { + e.expect("dir entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .collect(); + out.sort(); + out +} + +fn row_group_sizes(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).unwrap()).unwrap(); + reader + .metadata() + .row_groups() + .iter() + .map(|rg| rg.num_rows()) + .collect() +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let n = meta.row_group(rg).num_rows() as usize; + let g = reader.get_row_group(rg).expect("row group"); + let col = |i: usize| g.get_column_reader(i).expect("column reader"); + let i32s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + let ColumnReader::Int32ColumnReader(mut r) = c else { + panic!("expected INT32") + }; + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + v + }; + let i64s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + let ColumnReader::Int64ColumnReader(mut r) = c else { + panic!("expected INT64") + }; + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + v + }; + let f64s = |c: ColumnReader| -> Vec> { + let mut v = Vec::new(); + let mut defs = Vec::new(); + let ColumnReader::DoubleColumnReader(mut r) = c else { + panic!("expected DOUBLE") + }; + assert_eq!( + r.read_records(n, Some(&mut defs), None, &mut v).unwrap().0, + n + ); + if defs.is_empty() { + return v.into_iter().map(Some).collect(); + } + let mut it = v.into_iter(); + defs.iter() + .map(|&d| if d == 1 { it.next() } else { None }) + .collect() + }; + let strs = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + let ColumnReader::ByteArrayColumnReader(mut r) = c else { + panic!("expected BYTE_ARRAY") + }; + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + v.iter() + .map(|b| std::str::from_utf8(b.data()).expect("utf8").to_string()) + .collect() + }; + let (lid, rd, ka) = (i32s(col(0)), i32s(col(1)), i64s(col(2))); + let ss = f64s(col(3)); + let (nc, pf, src) = (f64s(col(4)), f64s(col(5)), strs(col(6))); + for i in 0..n { + out.push(ShortsParquetRow { + listing_id: lid[i], + report_date: rd[i], + known_at_micros: ka[i], + shares_short: ss[i].expect("required shares_short"), + net_change: nc[i], + pct_float: pf[i], + source: Cow::Owned(src[i].clone()), + }); + } + } + out +} + +fn assert_rows_bitwise(actual: &[ShortsParquetRow], expected: &[ShortsParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id"); + assert_eq!(a.report_date, e.report_date, "row {i} report_date"); + assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at"); + assert_eq!( + a.shares_short.to_bits(), + e.shares_short.to_bits(), + "row {i} shares" + ); + assert_eq!( + a.net_change.map(f64::to_bits), + e.net_change.map(f64::to_bits), + "row {i} net_change" + ); + assert_eq!( + a.pct_float.map(f64::to_bits), + e.pct_float.map(f64::to_bits), + "row {i} pct_float" + ); + assert_eq!(a.source, e.source, "row {i} source"); + } +} + +fn seeded(tmp: &TempDir) -> Vec { + let seed = vec![row(1, day(2024, 3, 15), 10_000.0)]; + write_shorts_dataset(&tmp.0, &seed, ShortsWriteOptions::default()).unwrap(); + fs::read(part_path(&tmp.0)).unwrap() +} + +#[test] +fn default_options_use_shared_row_group_and_zstd_defaults() { + let o = ShortsWriteOptions::default(); + assert_eq!(o.row_group_rows, DEFAULT_ROW_GROUP_ROWS); + assert_eq!(o.zstd_level, DEFAULT_ZSTD_LEVEL); + assert_eq!(DEFAULT_ROW_GROUP_ROWS, 1_000_000); + assert_eq!(DEFAULT_ZSTD_LEVEL, 3); +} + +#[test] +fn mid_stream_failure_after_flushed_row_groups_preserves_live_file_and_cleans_up() { + let tmp = TempDir::new("midstream"); + let before = seeded(&tmp); + let base = day(2020, 1, 15); + let mut rows: Vec = (0..7).map(|i| row(5, base + i * 15, 100.0)).collect(); + // Row 7 (after three flushed groups of 2) fails validation, then an unsorted row would follow. + rows.push(ShortsParquetRow { + pct_float: Some(f64::NEG_INFINITY), + ..row(5, base + 7 * 15, 100.0) + }); + + let err = write_shorts_dataset(&tmp.0, &rows, opts(2)).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::InvalidPctFloat { listing_id: 5, .. } + ), + "got {err:?}" + ); + assert_eq!(fs::read(part_path(&tmp.0)).unwrap(), before); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); + + // Same failure on a fresh dir publishes nothing and leaves no transient files. + let fresh = TempDir::new("midstream-fresh"); + let err = write_shorts_dataset(&fresh.0, &rows, opts(2)).unwrap_err(); + assert!(matches!(err, ParquetShortsError::InvalidPctFloat { .. })); + assert!(list_files(&fresh.0.join("shorts")).is_empty()); +} + +#[test] +fn invalid_options_are_rejected_before_touching_disk_even_for_empty_input() { + let tmp = TempDir::new("options"); + let rows = [row(1, day(2024, 1, 15), 1.0)]; + + for (o, label) in [ + (opts(0), "row_group_rows=0"), + ( + ShortsWriteOptions { + zstd_level: 23, + ..ShortsWriteOptions::default() + }, + "zstd=23", + ), + ( + ShortsWriteOptions { + zstd_level: 99, + ..ShortsWriteOptions::default() + }, + "zstd=99", + ), + ] { + for input in [&rows[..], &[][..]] { + let err = write_shorts_dataset(&tmp.0, input, o).unwrap_err(); + match (o.row_group_rows, &err) { + (0, ParquetShortsError::InvalidRowGroupRows) => {} + (_, ParquetShortsError::InvalidZstdLevel { level }) => { + assert_eq!(*level, o.zstd_level) + } + _ => panic!("{label}: unexpected {err:?}"), + } + assert!(!tmp.0.join("shorts").exists(), "{label} created shorts dir"); + } + } +} + +#[test] +fn invalid_first_row_never_creates_shorts_dir() { + let tmp = TempDir::new("first-row"); + let d = day(2024, 1, 15); + let bad = [ + row(1, d, f64::INFINITY), + ShortsParquetRow { + net_change: Some(f64::NAN), + ..row(1, d, 1.0) + }, + ShortsParquetRow { + source: Cow::Borrowed(" \t\n"), + ..row(1, d, 1.0) + }, + ]; + for r in bad { + assert!(write_shorts_dataset(&tmp.0, [&r], ShortsWriteOptions::default()).is_err()); + assert!(!tmp.0.join("shorts").exists()); + } +} + +#[test] +fn known_at_cutoff_is_exact_to_the_microsecond_including_pre_epoch_and_extremes() { + let tmp = TempDir::new("known-at"); + for d in [day(1965, 6, 30), 0, day(2024, 2, 29)] { + let midnight = i64::from(d) * MICROS_PER_DAY; + let at = |known_at_micros| ShortsParquetRow { + known_at_micros, + ..row(1, d, 1.0) + }; + for k in [midnight, midnight - 1] { + let err = + write_shorts_dataset(&tmp.0, [at(k)], ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::KnownAtNotAfterReportDate { known_at_micros, .. } + if known_at_micros == k + ), + "day {d} known_at {k}: {err:?}" + ); + } + write_shorts_dataset(&tmp.0, [at(midnight + 1)], ShortsWriteOptions::default()) + .expect("one microsecond after midnight is accepted"); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &[at(midnight + 1)]); + } + + // i32::MAX epoch days is beyond i64 micros: nothing can be after it, and no overflow panic. + let err = write_shorts_dataset( + &tmp.0, + [ShortsParquetRow { + known_at_micros: i64::MAX, + ..row(1, i32::MAX, 1.0) + }], + ShortsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetShortsError::KnownAtNotAfterReportDate { .. } + )); + + // i32::MIN epoch days precedes every i64 micros value, so even i64::MIN is "after" it. + let extreme = ShortsParquetRow { + known_at_micros: i64::MIN, + ..row(i32::MIN, i32::MIN, 1.0) + }; + write_shorts_dataset(&tmp.0, [&extreme], ShortsWriteOptions::default()).unwrap(); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &[extreme]); +} + +#[test] +fn special_floats_round_trip_bitwise_and_every_non_finite_variant_is_rejected() { + let tmp = TempDir::new("floats"); + let base = day(2023, 1, 15); + let good = vec![ + ShortsParquetRow { + net_change: Some(-0.0), + pct_float: Some(f64::MIN_POSITIVE / 4.0), + ..row(1, base, -0.0) + }, + ShortsParquetRow { + net_change: Some(f64::MIN), + pct_float: Some(0.0), + ..row(1, base + 15, f64::MAX) + }, + ShortsParquetRow { + net_change: Some(f64::EPSILON), + pct_float: None, + ..row(1, base + 31, 5e-324) + }, + ]; + let stats = write_shorts_dataset(&tmp.0, &good, opts(2)).unwrap(); + assert_eq!(stats.row_groups_written, 2); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &good); + let before = fs::read(part_path(&tmp.0)).unwrap(); + + let bad: Vec<(ShortsParquetRow, &str)> = vec![ + (row(1, base, f64::NEG_INFINITY), "shares"), + (row(1, base, -f64::MIN_POSITIVE), "shares"), + ( + ShortsParquetRow { + net_change: Some(f64::NEG_INFINITY), + ..row(1, base, 1.0) + }, + "net", + ), + ( + ShortsParquetRow { + net_change: Some(f64::NAN), + ..row(1, base, 1.0) + }, + "net", + ), + ( + ShortsParquetRow { + pct_float: Some(f64::INFINITY), + ..row(1, base, 1.0) + }, + "pct", + ), + ]; + for (r, kind) in bad { + let err = write_shorts_dataset(&tmp.0, [&r], ShortsWriteOptions::default()).unwrap_err(); + let ok = match kind { + "shares" => matches!(err, ParquetShortsError::InvalidSharesShort { .. }), + "net" => matches!(err, ParquetShortsError::InvalidNetChange { .. }), + _ => matches!(err, ParquetShortsError::InvalidPctFloat { .. }), + }; + assert!(ok, "{kind}: {err:?}"); + assert_eq!(fs::read(part_path(&tmp.0)).unwrap(), before); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); + } +} + +#[test] +fn many_distinct_sources_and_extreme_listing_ids_survive_multiple_row_groups() { + let tmp = TempDir::new("sources"); + let base = day(2021, 1, 15); + let ids = [i32::MIN, -1, 0, 1, i32::MAX]; + let mut rows = Vec::new(); + for (li, &id) in ids.iter().enumerate() { + for k in 0..6 { + let n = li * 6 + k; + let source = match n % 4 { + 0 => Cow::Borrowed(SHORTS_SOURCE_CEO), + 1 => Cow::Owned(format!("src-{n}")), + 2 => Cow::Owned(format!("Émetteur-{n}-короткие")), + _ => Cow::Owned(format!(" padded {n} ")), + }; + rows.push(ShortsParquetRow { + source, + net_change: (k % 2 == 0).then_some(k as f64), + pct_float: (k % 3 == 0).then_some(0.5), + ..row(id, base + (k as i32) * 15, n as f64) + }); + } + } + + let stats = write_shorts_dataset(&tmp.0, &rows, opts(7)).unwrap(); + let file_len = fs::metadata(part_path(&tmp.0)).unwrap().len(); + assert_eq!( + stats, + ShortsWriteStats { + rows_written: 30, + files_written: 1, + row_groups_written: 5, + bytes_written: file_len, + } + ); + assert_eq!(row_group_sizes(&part_path(&tmp.0)), [7, 7, 7, 7, 2]); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &rows); +} + +#[test] +fn single_row_and_all_zstd_level_bounds_produce_readable_zstd_files() { + for level in [1, 22] { + let tmp = TempDir::new("zstd-level"); + let r = ShortsParquetRow { + net_change: Some(-12.5), + pct_float: Some(3.25), + ..row(9, day(2025, 6, 13), 42.0) + }; + let o = ShortsWriteOptions { + zstd_level: level, + ..ShortsWriteOptions::default() + }; + let stats = write_shorts_dataset(&tmp.0, [&r], o).unwrap(); + assert_eq!((stats.rows_written, stats.row_groups_written), (1, 1)); + let reader = SerializedFileReader::new(File::open(part_path(&tmp.0)).unwrap()).unwrap(); + for c in reader.metadata().row_group(0).columns() { + assert!(matches!(c.compression(), Compression::ZSTD(_))); + } + assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &[r]); + } +} + +#[test] +fn panicking_row_iterator_releases_lock_removes_staging_and_keeps_live_file() { + let tmp = TempDir::new("panic"); + let before = seeded(&tmp); + let base = day(2022, 1, 15); + let rows: Vec = (0..10).map(|i| row(3, base + i * 15, 1.0)).collect(); + + let out = tmp.0.clone(); + let result = panic::catch_unwind(AssertUnwindSafe(|| { + let iter = rows.iter().enumerate().map(|(i, r)| { + if i == 5 { + panic!("injected iterator panic"); + } + r + }); + let _ = write_shorts_dataset(&out, iter, opts(2)); + })); + assert!(result.is_err(), "iterator panic must propagate"); + assert_eq!(fs::read(part_path(&tmp.0)).unwrap(), before); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); + + // The next writer neither hangs on the lock nor sees leftovers. + write_shorts_dataset(&tmp.0, &rows, opts(2)).unwrap(); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &rows); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); +} + +#[test] +fn unowned_staging_like_files_are_preserved_on_success_and_failure() { + let tmp = TempDir::new("unowned"); + let shorts = tmp.0.join("shorts"); + fs::create_dir_all(&shorts).unwrap(); + let foreign = [ + "part.parquet.999999-0.tmp", + "part.parquet.999999-0.bak", + "notes.txt", + ]; + for name in foreign { + fs::write(shorts.join(name), name.as_bytes()).unwrap(); + } + let d = day(2024, 5, 15); + + write_shorts_dataset(&tmp.0, [row(1, d, 1.0)], ShortsWriteOptions::default()).unwrap(); + let err = write_shorts_dataset( + &tmp.0, + [row(1, d, 1.0), row(1, d, 2.0)], + ShortsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetShortsError::DuplicateKey { listing_id: 1, .. } + )); + + let mut expected: Vec = foreign.iter().map(|s| s.to_string()).collect(); + expected.push("part.parquet".into()); + expected.sort(); + assert_eq!(list_files(&shorts), expected); + for name in foreign { + assert_eq!(fs::read(shorts.join(name)).unwrap(), name.as_bytes()); + } +} + +#[test] +fn blocker_paths_return_io_errors_without_destroying_the_blocker() { + let d = day(2024, 5, 15); + + // `shorts` occupied by a regular file. + let tmp = TempDir::new("blocker-file"); + fs::write(tmp.0.join("shorts"), b"keep").unwrap(); + let err = + write_shorts_dataset(&tmp.0, [row(1, d, 1.0)], ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetShortsError::Io { .. }), "{err:?}"); + assert_eq!(fs::read(tmp.0.join("shorts")).unwrap(), b"keep"); + + // `part.parquet` occupied by a non-empty directory: rename fails, staging is removed. + let tmp = TempDir::new("blocker-dir"); + let blocker = part_path(&tmp.0); + fs::create_dir_all(&blocker).unwrap(); + fs::write(blocker.join("inner"), b"keep").unwrap(); + let err = + write_shorts_dataset(&tmp.0, [row(1, d, 1.0)], ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetShortsError::Io { .. }), "{err:?}"); + assert!(err.to_string().contains("part.parquet")); + assert_eq!(fs::read(blocker.join("inner")).unwrap(), b"keep"); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); +} + +#[test] +fn ordering_errors_report_both_keys_and_take_precedence_over_row_validation() { + let tmp = TempDir::new("ordering"); + let (d1, d2) = (day(2024, 1, 15), day(2024, 1, 31)); + + // Second row is both out of order and invalid: ordering is reported with both keys. + let err = write_shorts_dataset( + &tmp.0, + [row(2, d1, 1.0), row(1, d2, f64::NAN)], + ShortsWriteOptions::default(), + ) + .unwrap_err(); + match err { + ParquetShortsError::UnsortedInput { + prev_listing_id, + prev_report_date, + listing_id, + report_date, + } => { + assert_eq!((prev_listing_id, prev_report_date), (2, d1)); + assert_eq!((listing_id, report_date), (1, d2)); + } + other => panic!("unexpected {other:?}"), + } + + // Same listing, earlier date is unsorted; a later listing with an earlier date is fine. + assert!(matches!( + write_shorts_dataset(&tmp.0, [row(1, d2, 1.0), row(1, d1, 1.0)], opts(1)).unwrap_err(), + ParquetShortsError::UnsortedInput { .. } + )); + let ok = [row(1, d2, 1.0), row(2, d1, 1.0)]; + write_shorts_dataset(&tmp.0, &ok, opts(1)).unwrap(); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &ok); +} diff --git a/tools/curate-etl/tests/session_close_qa_contract.rs b/tools/curate-etl/tests/session_close_qa_contract.rs new file mode 100644 index 00000000..7c93a8d4 --- /dev/null +++ b/tools/curate-etl/tests/session_close_qa_contract.rs @@ -0,0 +1,335 @@ +//! QA contract tests for `session_close::et_session_close_utc_micros` (T-99 / M1.2q) and the +//! pre-2008 `bars_1d` write path. +//! +//! The DST transition table below is NOT derived from the crate's Sunday-rule logic: it was +//! generated once from IANA tzdata (Python `zoneinfo`, `America/New_York` and `America/Toronto` +//! produced identical tables for 1976..=2030) by finding the first day each year whose 16:00 local +//! close maps to 20:00 UTC (EDT start) and back to 21:00 UTC (EST start). It also confirmed that in +//! 1974 the two zones diverged (New York 16:00 = 20:00 UTC on 1974-01-15, Toronto 21:00 UTC), which +//! is why dates before 1976-01-01 must stay out of range. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::error::Error; +use std::fs::{self, File}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + curate_and_write_bars_1d, curate_bars_1d, et_session_close_utc_micros, Bars1dWriteOptions, + EodDailyBar, ProviderMappingRow, ProviderMappingTable, QmRawVolume, SessionCloseError, + SplitTable, SESSION_CLOSE_MAX_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_YEAR, + SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MIN_SUPPORTED_YEAR, +}; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_HOUR: i64 = 3_600_000_000; +const MICROS_PER_DAY: i64 = 86_400_000_000; + +/// `(year, edt_start_month, edt_start_day, est_start_month, est_start_day)` from IANA tzdata. +const TZDATA_TRANSITIONS: [(i32, u32, u32, u32, u32); 55] = [ + (1976, 4, 25, 10, 31), + (1977, 4, 24, 10, 30), + (1978, 4, 30, 10, 29), + (1979, 4, 29, 10, 28), + (1980, 4, 27, 10, 26), + (1981, 4, 26, 10, 25), + (1982, 4, 25, 10, 31), + (1983, 4, 24, 10, 30), + (1984, 4, 29, 10, 28), + (1985, 4, 28, 10, 27), + (1986, 4, 27, 10, 26), + (1987, 4, 5, 10, 25), + (1988, 4, 3, 10, 30), + (1989, 4, 2, 10, 29), + (1990, 4, 1, 10, 28), + (1991, 4, 7, 10, 27), + (1992, 4, 5, 10, 25), + (1993, 4, 4, 10, 31), + (1994, 4, 3, 10, 30), + (1995, 4, 2, 10, 29), + (1996, 4, 7, 10, 27), + (1997, 4, 6, 10, 26), + (1998, 4, 5, 10, 25), + (1999, 4, 4, 10, 31), + (2000, 4, 2, 10, 29), + (2001, 4, 1, 10, 28), + (2002, 4, 7, 10, 27), + (2003, 4, 6, 10, 26), + (2004, 4, 4, 10, 31), + (2005, 4, 3, 10, 30), + (2006, 4, 2, 10, 29), + (2007, 3, 11, 11, 4), + (2008, 3, 9, 11, 2), + (2009, 3, 8, 11, 1), + (2010, 3, 14, 11, 7), + (2011, 3, 13, 11, 6), + (2012, 3, 11, 11, 4), + (2013, 3, 10, 11, 3), + (2014, 3, 9, 11, 2), + (2015, 3, 8, 11, 1), + (2016, 3, 13, 11, 6), + (2017, 3, 12, 11, 5), + (2018, 3, 11, 11, 4), + (2019, 3, 10, 11, 3), + (2020, 3, 8, 11, 1), + (2021, 3, 14, 11, 7), + (2022, 3, 13, 11, 6), + (2023, 3, 12, 11, 5), + (2024, 3, 10, 11, 3), + (2025, 3, 9, 11, 2), + (2026, 3, 8, 11, 1), + (2027, 3, 14, 11, 7), + (2028, 3, 12, 11, 5), + (2029, 3, 11, 11, 4), + (2030, 3, 10, 11, 3), +]; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-session-close-qa-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + curate_etl::ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn close_at(epoch_day: i32, utc_hour: i64) -> i64 { + i64::from(epoch_day) * MICROS_PER_DAY + utc_hour * MICROS_PER_HOUR +} + +fn bar(key: &str, d: i32, c: f64) -> EodDailyBar { + EodDailyBar { + key: key.to_string(), + session_date: d, + open: c, + high: c + 1.0, + low: c - 1.0, + close: c, + adj_volume: 1_000.0, + } +} + +fn open_mapping(id: &str, lid: i32) -> ProviderMappingTable { + ProviderMappingTable::from_rows([ProviderMappingRow { + source: "eod".to_string(), + source_id: id.to_string(), + valid_from: i32::MIN, + valid_to: None, + listing_id: lid, + }]) + .unwrap() +} + +#[test] +fn tzdata_table_covers_exactly_the_supported_years() { + assert_eq!(TZDATA_TRANSITIONS[0].0, SESSION_CLOSE_MIN_SUPPORTED_YEAR); + assert_eq!( + TZDATA_TRANSITIONS[TZDATA_TRANSITIONS.len() - 1].0, + SESSION_CLOSE_MAX_SUPPORTED_YEAR + ); + assert_eq!(SESSION_CLOSE_MIN_SUPPORTED_DATE, day(1976, 1, 1)); + assert_eq!(SESSION_CLOSE_MAX_SUPPORTED_DATE, day(2030, 12, 31)); +} + +#[test] +fn every_day_1976_to_2030_matches_iana_tzdata_close() { + for &(y, sm, sd, em, ed) in &TZDATA_TRANSITIONS { + let edt_start = day(y, sm, sd); + let est_start = day(y, em, ed); + for d in day(y, 1, 1)..=day(y, 12, 31) { + let hour = if d >= edt_start && d < est_start { 20 } else { 21 }; + assert_eq!( + et_session_close_utc_micros(d), + Ok(close_at(d, hour)), + "epoch_day={d} in {y}: expected 16:00 ET = {hour}:00 UTC per tzdata" + ); + } + } +} + +#[test] +fn transition_eve_and_day_after_match_tzdata_for_every_year() { + // Saturday before each switch keeps the old offset; Monday after (first trading session) + // has the new one. These are the dates real bars land on. + for &(y, sm, sd, em, ed) in &TZDATA_TRANSITIONS { + let s = day(y, sm, sd); + let e = day(y, em, ed); + assert_eq!(et_session_close_utc_micros(s - 1), Ok(close_at(s - 1, 21)), "{y} spring eve"); + assert_eq!(et_session_close_utc_micros(s + 1), Ok(close_at(s + 1, 20)), "{y} spring Mon"); + assert_eq!(et_session_close_utc_micros(e - 1), Ok(close_at(e - 1, 20)), "{y} fall eve"); + assert_eq!(et_session_close_utc_micros(e + 1), Ok(close_at(e + 1, 21)), "{y} fall Mon"); + } +} + +#[test] +fn pre_1976_divergent_emergency_dst_years_and_post_2030_are_out_of_range() { + // 1974-01-15: New York was on emergency DST (20:00 UTC) while Toronto was not (21:00 UTC). + let probes = [ + day(1974, 1, 15), + day(1975, 2, 24), + day(1975, 12, 31), + day(1970, 1, 1), + day(1900, 1, 1), + day(2031, 1, 1), + day(2100, 6, 1), + 0, + -1, + i32::MIN, + i32::MIN + 1, + i32::MAX, + i32::MAX - 1, + ]; + for d in probes { + let err = et_session_close_utc_micros(d).unwrap_err(); + let SessionCloseError::DateOutOfRange { + epoch_day, + min_supported, + max_supported, + } = err; + assert_eq!(epoch_day, d); + assert_eq!(min_supported, SESSION_CLOSE_MIN_SUPPORTED_DATE); + assert_eq!(max_supported, SESSION_CLOSE_MAX_SUPPORTED_DATE); + assert!(err.source().is_none()); + // Usable as a boxed error. + let boxed: Box = Box::new(err); + assert!(boxed.to_string().contains(&d.to_string())); + } + // Boundaries themselves are in range (both winter, EST). + assert_eq!( + et_session_close_utc_micros(SESSION_CLOSE_MIN_SUPPORTED_DATE), + Ok(close_at(SESSION_CLOSE_MIN_SUPPORTED_DATE, 21)) + ); + assert_eq!( + et_session_close_utc_micros(SESSION_CLOSE_MAX_SUPPORTED_DATE), + Ok(close_at(SESSION_CLOSE_MAX_SUPPORTED_DATE, 21)) + ); +} + +#[test] +fn close_is_strictly_increasing_and_never_before_1600_et() { + // Monotonic: a later session never gets an earlier known_at (no look-ahead via ordering). + // Never earlier than 16:00 EDT (20:00 UTC) and never later than 16:00 EST (21:00 UTC). + let mut prev = i64::MIN; + for d in SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE { + let t = et_session_close_utc_micros(d).unwrap(); + assert!(t > prev, "non-monotonic at epoch_day={d}"); + assert!(t >= close_at(d, 20) && t <= close_at(d, 21)); + prev = t; + } +} + +#[test] +fn curate_stage_drops_bars_on_either_side_of_1976_boundary_correctly() { + let mapping = open_mapping("GE.US", 7); + let curr: HashMap> = [(7, Cow::Borrowed("USD"))].into_iter().collect(); + // 1975-12-31 (Wed) dropped; 1976-01-02 (Fri, first 1976 session) kept at 21:00 UTC; + // 1976-04-26 (Mon after first 1976 spring-forward) kept at 20:00 UTC. + let input = vec![ + bar("GE.US", day(1975, 12, 31), 10.0), + bar("GE.US", day(1976, 1, 2), 11.0), + bar("GE.US", day(1976, 4, 26), 12.0), + ]; + let out = curate_bars_1d( + input, + &SplitTable::::default(), + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + ) + .unwrap(); + assert_eq!(out.stats.rows_in, 3); + assert_eq!(out.stats.dropped_ts_out_of_range, 1); + assert_eq!(out.stats.rows_out, 2); + assert_eq!( + out.stats.rows_in, + out.stats.rows_out + + out.stats.dropped_unmapped + + out.stats.dropped_missing_currency + + out.stats.dropped_ts_out_of_range + + out.stats.listing_collision_collapsed + + out.stats.listing_collision_dropped + ); + let d0 = day(1976, 1, 2); + let d1 = day(1976, 4, 26); + assert_eq!(out.rows[0].session_date, d0); + assert_eq!(out.rows[0].ts_micros, close_at(d0, 21)); + assert_eq!(out.rows[0].known_at_micros, close_at(d0, 21)); + assert_eq!(out.rows[1].session_date, d1); + assert_eq!(out.rows[1].ts_micros, close_at(d1, 20)); + assert_eq!(out.rows[1].known_at_micros, close_at(d1, 20)); +} + +#[test] +fn write_wrapper_publishes_pre_2008_year_partitions_with_footer_row_counts() { + let tmp = TempDir::new("pre2008-write"); + let mapping = open_mapping("IBM.US", 42); + let curr: HashMap> = + [(42, Cow::Borrowed("USD"))].into_iter().collect(); + let input = vec![ + bar("IBM.US", day(1975, 6, 16), 5.0), // dropped (out of range) + bar("IBM.US", day(1976, 3, 1), 6.0), + bar("IBM.US", day(1976, 7, 1), 7.0), + bar("IBM.US", day(1999, 1, 15), 8.0), + bar("IBM.US", day(2006, 6, 15), 9.0), + bar("IBM.US", day(2007, 12, 31), 10.0), + bar("IBM.US", day(2008, 1, 2), 11.0), + ]; + let report = curate_and_write_bars_1d( + &tmp.0, + input, + &SplitTable::::default(), + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + Bars1dWriteOptions::default(), + ) + .unwrap(); + + assert_eq!(report.curate_stats.dropped_ts_out_of_range, 1); + assert_eq!(report.write_stats.rows_written, 6); + let by_year: Vec<(i32, usize)> = report + .write_stats + .rows_by_year + .iter() + .map(|(&y, &n)| (y, n)) + .collect(); + assert_eq!( + by_year, + vec![(1976, 2), (1999, 1), (2006, 1), (2007, 1), (2008, 1)] + ); + assert_eq!(report.write_stats.files_written, 5); + assert!(!tmp.0.join("bars_1d/year=1975").exists()); + for (year, n) in by_year { + let path = tmp.0.join(format!("bars_1d/year={year:04}/part.parquet")); + let reader = SerializedFileReader::new(File::open(&path).expect("open")).expect("reader"); + assert_eq!( + reader.metadata().file_metadata().num_rows(), + n as i64, + "footer row count for {}", + path.display() + ); + } +}