From 8906f3ad343299c33e3f014602eb323d5b75f9a6 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 11:33:26 -0500 Subject: [PATCH] =?UTF-8?q?T-167:=20M2.2j=20(re-queue)=20=E2=80=94=20`tool?= =?UTF-8?q?s/curate-etl`:=20`curate-posts`=20CLI=20command=20(file=20mode)?= =?UTF-8?q?=20wiring=20`run=5Fcurate=5Fposts`=20into=20`cli.rs`=20+=20`mai?= =?UTF-8?q?n.rs`=20with=20parser=20tests=20(no=20new=20crates,=20no=20benc?= =?UTF-8?q?h=20changes,=20no=20`--from-mongo`,=20no=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 43 ++- tools/curate-etl/src/cli.rs | 561 +++++++++++++++++++++++++++++++++-- tools/curate-etl/src/main.rs | 11 + 3 files changed, 591 insertions(+), 24 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 599110d5..d7d6b6ac 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -142,7 +142,7 @@ Rules: 4. **Global `spiel_id` deduplication & deterministic tie-break:** Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail`. Within each `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties by the maximum lexicographic tuple `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero dependence on input order. The remaining `group_len - 1` rows are counted in `stats.duplicates_dropped`. 5. **Sort order & invariants:** Both `newswire` and `retail` are sorted strictly ascending by `(key, known_at, spiel_id)`. Any input permutation yields identical `newswire`, `retail`, and `stats`, and `input == newswire + retail + duplicates_dropped + rejected_invalid`. -Deferred out of `src/posts.rs`: `curate-posts` CLI subcommand, benchmark, live `ceoPosts` verification (including live `edited` BSON type verification), and co-publishing with `curate-events` output (offline raw-BSON decoding lives in `src/bson_ceo_posts.rs`, chunked streaming in `src/bson_stream.rs`, `events` Parquet row mapping in `src/parquet_posts.rs`, `provider_mapping` listing resolution + Parquet writing in `src/curate_posts.rs`, and the file-to-file runner in `src/run_curate_posts.rs`). +Deferred out of `src/posts.rs`: benchmark, live `ceoPosts` verification (including live `edited` BSON type verification), `--from-mongo` streaming, and co-publishing with `curate-events` output (offline raw-BSON decoding lives in `src/bson_ceo_posts.rs`, chunked streaming in `src/bson_stream.rs`, `events` Parquet row mapping in `src/parquet_posts.rs`, `provider_mapping` listing resolution + Parquet writing in `src/curate_posts.rs`, the file-to-file runner in `src/run_curate_posts.rs`, and the file-mode `curate-posts` CLI command in `src/cli.rs` + `src/main.rs`). ### `run_curate_posts` File-to-File Runner (`M2.2i`) @@ -921,7 +921,7 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0a1b7ace - **Global `spiel_id` deduplication & `listing_duplicate_collapsed`:** because `build_posts` deduplicates globally on `spiel_id` (keeping the greatest `known_at` and breaking ties by the maximum `(posted_at, is_edited, is_bot, key, user_id, text)` tuple) and `payload_json` carries `spiel_id`, `listing_duplicate_collapsed` is expected to be `0` for real input and exists only as a defensive writer-key uniqueness guard; when the same `spiel_id` appears under two source keys, the surviving key is chosen by `build_posts`'s existing tie-break. - **In-memory buffering:** both `build_posts` and the final 7-field sort buffer all rows in RAM; full-corpus memory and throughput over the 14.8M-row `ceoPosts` dataset remain unverified. - **Separate output root (no co-publishing with `curate-events`):** `write_events_dataset` writes and replaces `/events/year=YYYY/part.parquet` partitions, so publishing curated posts alongside `curate-events` filings/earnings in the same `events/` directory is not handled here; pass a dedicated `out_dir` until a unified publisher exists. - - **Not done / deferred:** the `curate-posts` CLI subcommand, benchmark, live `ceoPosts` run/verification, and co-publishing posts with `curate-events` output remain deferred to follow-up tasks. + - **Not done / deferred:** benchmark, `--from-mongo` / live `ceoPosts` run and schema verification, and co-publishing posts with `curate-events` output remain deferred to follow-up tasks. ## `fx_1d` Curation Stage (`M1.2t`) @@ -1539,6 +1539,45 @@ Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs wi - **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the `provider_mapping` namespace (for example, the QuoteMedia security ID, not a bare ticker — the security master records distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` for the same symbol and exchange, so switching earnings to bare `symbol` can merge distinct identities or drop rows). If a live `qmFilings` export lacks that unambiguous key, prepare the export with verified QuoteMedia IDs and exclude unresolved rows rather than downgrading `qmEarnings` to bare tickers. - **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope. +## `curate-posts` Command (`M2.2j`) + +End-to-end file-to-Parquet CLI command (`src/run_curate_posts.rs`, wired in `src/cli.rs` and `src/main.rs`) streaming a concatenated raw BSON `ceoPosts` dump alongside `provider_mapping.tsv` into atomically published `/events/year=YYYY/part.parquet` partitions with zero extra crates and no database connections (`--from-mongo` is not supported yet and is rejected as an unknown flag). + +### Invocation + +```bash +curate-etl curate-posts \ + --ceo-posts ceoPosts.bson \ + --provider-mapping provider_mapping.tsv \ + --out ./out-posts \ + --timestamp-unit \ + [--key-field ceoId] \ + [--spiel-id-field spielId] \ + [--timestamp-field timestamp] \ + [--edited-field edited] \ + [--bot-field bot] \ + [--user-id-field userId] \ + [--text-field spiel] \ + [--mapping-source ceo] +``` + +Inputs, defaults, and output rules: +- `--ceo-posts ` *(required)*: concatenated raw BSON (`mongodump` `ceoPosts.bson`). +- `--provider-mapping ` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`). +- `--out ` *(required, dedicated output directory)*: dataset root where `/events/year=YYYY/part.parquet` is atomically published. Because `curate-events` (filings + earnings) writes to the same `/events` directory layout, `curate-posts` requires a dedicated `--out` directory and fails closed before any write if `/events` already contains any `year=*` entry (leaving existing partitions byte-identical). +- `--timestamp-unit ` *(required, **no default**)*: explicit numeric epoch unit (`seconds` or `millis`) for numeric `timestamp` and `edited` fields. There is intentionally no default because the live MongoDB `ceoPosts` numeric timestamp unit is unverified in the repository; BSON `DateTime` values are always epoch milliseconds regardless of unit. +- Optional field-name overrides (defaults from `src/bson_ceo_posts.rs` / `get-posts.action.ts`): + - `--key-field` (default `ceoId`) + - `--spiel-id-field` (default `spielId`) + - `--timestamp-field` (default `timestamp`) + - `--edited-field` (default `edited`) + - `--bot-field` (default `bot`) + - `--user-id-field` (default `userId`) + - `--text-field` (default `spiel`) +- `--mapping-source ` *(optional, default `ceo`)*: `provider_mapping` source name used to resolve `(mapping_source, key, et_date) -> listing_id` on the Eastern local posting date of `posted_at`. + +Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, invalid `--timestamp-unit`, duplicate flags, unknown flags (including `--from-mongo`), positional arguments, blank field names or `--mapping-source`, and colliding field-name roles (checked after applying defaults) exit non-zero with usage on stderr. + ## Read-Only MongoDB URI Safety Guard (`M1.2ak`) Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero new crates, no sockets, no DNS resolution, no subprocesses) that ports the QA MongoDB target-classification rules from `apps/stock/config/src/env-safety.ts` before any Rust code may open a MongoDB connection. diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 11a967b9..3483d0ed 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -26,6 +26,15 @@ use crate::bench::{ DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, }; +use crate::bson_ceo_posts::{ + CeoPostsTimestampUnit, DEFAULT_BOT_FIELD as DEFAULT_POSTS_BOT_FIELD, + DEFAULT_EDITED_FIELD as DEFAULT_POSTS_EDITED_FIELD, + DEFAULT_KEY_FIELD as DEFAULT_POSTS_KEY_FIELD, + DEFAULT_SPIEL_ID_FIELD as DEFAULT_POSTS_SPIEL_ID_FIELD, + DEFAULT_TEXT_FIELD as DEFAULT_POSTS_TEXT_FIELD, + DEFAULT_TIMESTAMP_FIELD as DEFAULT_POSTS_TIMESTAMP_FIELD, + DEFAULT_USER_ID_FIELD as DEFAULT_POSTS_USER_ID_FIELD, +}; use crate::bson_ceo_shorts::{DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD}; use crate::bson_eod_prices::parse_ymd_strict_days; use crate::bson_qm_events::{ @@ -44,6 +53,9 @@ use crate::run_curate_bars::{ use crate::run_curate_corporate_actions::CurateCorporateActionsArgs; use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE}; use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; +use crate::run_curate_posts::{ + CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE, +}; use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE}; use crate::run_mongo::{ CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs, @@ -68,6 +80,7 @@ pub enum CliAction { CurateShortsMongo(CurateShortsMongoArgs), CurateEvents(CurateEventsArgs), CurateEventsMongo(CurateEventsMongoArgs), + CuratePosts(CuratePostsArgs), BenchSplit(usize), BenchAdj(usize), BenchCorporateActions(usize), @@ -127,8 +140,11 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} curate-shorts --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ Curate shorts from ceoShorts BSON or read-only MongoDB + provider_mapping TSV into shorts/part.parquet (defaults: --key-field {DEFAULT_KEY_FIELD}, --report-date-field {DEFAULT_REPORT_DATE_FIELD}, --mapping-source {DEFAULT_MAPPING_SOURCE})\n\ {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ + {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ {name} curate-events --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ Curate events from qmFilings + qmEarnings BSON or read-only MongoDB + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\ + {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ + Curate ceoPosts from BSON + provider_mapping TSV into /events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\ {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ {name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\ {name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\ @@ -177,6 +193,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} curate-fx-1d --eod-prices --te-market-data [--te-symbol ] --out \n\ {name} curate-shorts --ceo-shorts --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ + {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ {name} bench-split [rows]\n\ {name} bench-adj [events]\n\ {name} bench-corporate-actions [events]\n\ @@ -992,6 +1009,28 @@ fn parse_curate_fx_1d_args(args: &[&str]) -> Result { })) } +fn set_path(slot: &mut Option, flag_name: &str, raw: &str) -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(PathBuf::from(raw)); + Ok(()) +} + +fn set_name(slot: &mut Option, flag_name: &str, raw: &str) -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.trim().is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(raw.to_string()); + Ok(()) +} + fn parse_curate_shorts_args(args: &[&str]) -> Result { let mut mongo = MongoFlagState::default(); let mut ceo_shorts: Option = None; @@ -1040,28 +1079,6 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result { continue; } - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.trim().is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.to_string()); - Ok(()) - }; - match flag { "--ceo-shorts" => set_path(&mut ceo_shorts, "--ceo-shorts", value)?, "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, @@ -1149,6 +1166,119 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result { Ok(CliAction::CurateShorts(parsed)) } +fn parse_curate_posts_args(args: &[&str]) -> Result { + let mut ceo_posts: Option = None; + let mut provider_mapping: Option = None; + let mut out_dir: Option = None; + let mut timestamp_unit: Option = None; + let mut key_field: Option = None; + let mut spiel_id_field: Option = None; + let mut timestamp_field: Option = None; + let mut edited_field: Option = None; + let mut bot_field: Option = None; + let mut user_id_field: Option = None; + let mut text_field: Option = None; + let mut mapping_source: Option = None; + + let mut i = 0usize; + while i < args.len() { + let token = args[i]; + if !token.starts_with("--") { + return Err(format!( + "unexpected positional argument '{token}' for curate-posts" + )); + } + + let flag_name = token.split_once('=').map_or(token, |(k, _)| k); + if !matches!( + flag_name, + "--ceo-posts" + | "--provider-mapping" + | "--out" + | "--timestamp-unit" + | "--key-field" + | "--spiel-id-field" + | "--timestamp-field" + | "--edited-field" + | "--bot-field" + | "--user-id-field" + | "--text-field" + | "--mapping-source" + ) { + return Err(format!("unknown flag '{flag_name}' for curate-posts")); + } + + let (flag, value) = if let Some((k, v)) = token.split_once('=') { + i += 1; + (k, v) + } else { + let Some(&v) = args.get(i + 1) else { + return Err(format!("missing value for flag '{token}'")); + }; + if v.starts_with("--") { + return Err(format!("missing value for flag '{token}'")); + } + i += 2; + (token, v) + }; + + match flag { + "--ceo-posts" => set_path(&mut ceo_posts, "--ceo-posts", value)?, + "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, + "--out" => set_path(&mut out_dir, "--out", value)?, + "--timestamp-unit" => { + if timestamp_unit.is_some() { + return Err("duplicate flag '--timestamp-unit'".to_string()); + } + timestamp_unit = Some(match value { + "seconds" => CeoPostsTimestampUnit::Seconds, + "millis" => CeoPostsTimestampUnit::Millis, + _ => { + return Err(format!( + "invalid --timestamp-unit '{value}' (expected 'seconds' or 'millis')" + )); + } + }); + } + "--key-field" => set_name(&mut key_field, "--key-field", value)?, + "--spiel-id-field" => set_name(&mut spiel_id_field, "--spiel-id-field", value)?, + "--timestamp-field" => set_name(&mut timestamp_field, "--timestamp-field", value)?, + "--edited-field" => set_name(&mut edited_field, "--edited-field", value)?, + "--bot-field" => set_name(&mut bot_field, "--bot-field", value)?, + "--user-id-field" => set_name(&mut user_id_field, "--user-id-field", value)?, + "--text-field" => set_name(&mut text_field, "--text-field", value)?, + "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, + other => return Err(format!("unknown flag '{other}' for curate-posts")), + } + } + + let ceo_posts = ceo_posts.ok_or_else(|| "missing required flag '--ceo-posts'".to_string())?; + let provider_mapping = + provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let timestamp_unit = + timestamp_unit.ok_or_else(|| "missing required flag '--timestamp-unit'".to_string())?; + + let parsed = CuratePostsArgs { + ceo_posts, + provider_mapping, + out_dir, + timestamp_unit, + key_field: key_field.unwrap_or_else(|| DEFAULT_POSTS_KEY_FIELD.to_string()), + spiel_id_field: spiel_id_field.unwrap_or_else(|| DEFAULT_POSTS_SPIEL_ID_FIELD.to_string()), + timestamp_field: timestamp_field + .unwrap_or_else(|| DEFAULT_POSTS_TIMESTAMP_FIELD.to_string()), + edited_field: edited_field.unwrap_or_else(|| DEFAULT_POSTS_EDITED_FIELD.to_string()), + bot_field: bot_field.unwrap_or_else(|| DEFAULT_POSTS_BOT_FIELD.to_string()), + user_id_field: user_id_field.unwrap_or_else(|| DEFAULT_POSTS_USER_ID_FIELD.to_string()), + text_field: text_field.unwrap_or_else(|| DEFAULT_POSTS_TEXT_FIELD.to_string()), + mapping_source: mapping_source.unwrap_or_else(|| DEFAULT_POSTS_MAPPING_SOURCE.to_string()), + }; + + parsed.field_names().validate().map_err(|e| e.to_string())?; + Ok(CliAction::CuratePosts(parsed)) +} + fn parse_curate_events_args(args: &[&str]) -> Result { let mut mongo = MongoFlagState::default(); let mut qm_filings: Option = None; @@ -1437,6 +1567,7 @@ pub fn parse_args(args: &[String]) -> Result { ["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest), ["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest), ["curate-events", rest @ ..] => parse_curate_events_args(rest), + ["curate-posts", rest @ ..] => parse_curate_posts_args(rest), ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), ["bench-split", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)), @@ -3459,4 +3590,390 @@ mod tests { assert!(parse_args(&to_args(&["bench-fundamentals", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-fundamentals", "1", "2"])).is_err()); } + + #[test] + fn curate_posts_parsing_validation_and_usage() { + let usage = format_usage("curate-etl", "0.1.0"); + let stderr_usage = format_usage_stderr("curate-etl"); + assert!(usage.contains("curate-posts --ceo-posts")); + assert!(stderr_usage.contains("curate-posts --ceo-posts")); + + // Minimal valid invocation with --timestamp-unit seconds fills all 8 defaults + assert_eq!( + parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "posts.bson", + "--provider-mapping", + "map.tsv", + "--out", + "posts_out", + "--timestamp-unit", + "seconds", + ])), + Ok(CliAction::CuratePosts(CuratePostsArgs { + ceo_posts: PathBuf::from("posts.bson"), + provider_mapping: PathBuf::from("map.tsv"), + out_dir: PathBuf::from("posts_out"), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: "ceoId".to_string(), + spiel_id_field: "spielId".to_string(), + timestamp_field: "timestamp".to_string(), + edited_field: "edited".to_string(), + bot_field: "bot".to_string(), + user_id_field: "userId".to_string(), + text_field: "spiel".to_string(), + mapping_source: "ceo".to_string(), + })) + ); + + // Minimal valid invocation with --timestamp-unit millis + assert_eq!( + parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "posts.bson", + "--provider-mapping", + "map.tsv", + "--out", + "posts_out", + "--timestamp-unit", + "millis", + ])), + Ok(CliAction::CuratePosts(CuratePostsArgs { + ceo_posts: PathBuf::from("posts.bson"), + provider_mapping: PathBuf::from("map.tsv"), + out_dir: PathBuf::from("posts_out"), + timestamp_unit: CeoPostsTimestampUnit::Millis, + key_field: DEFAULT_POSTS_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_POSTS_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_POSTS_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_POSTS_EDITED_FIELD.to_string(), + bot_field: DEFAULT_POSTS_BOT_FIELD.to_string(), + user_id_field: DEFAULT_POSTS_USER_ID_FIELD.to_string(), + text_field: DEFAULT_POSTS_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + })) + ); + + // All 8 optional flags overridden using --flag=value syntax + assert_eq!( + parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts=p2.bson", + "--provider-mapping=m2.tsv", + "--out=o2", + "--timestamp-unit=millis", + "--key-field=channel", + "--spiel-id-field=postId", + "--timestamp-field=createdAt", + "--edited-field=updatedAt", + "--bot-field=isBot", + "--user-id-field=authorId", + "--text-field=body", + "--mapping-source=ceo_alt", + ])), + Ok(CliAction::CuratePosts(CuratePostsArgs { + ceo_posts: PathBuf::from("p2.bson"), + provider_mapping: PathBuf::from("m2.tsv"), + out_dir: PathBuf::from("o2"), + timestamp_unit: CeoPostsTimestampUnit::Millis, + key_field: "channel".to_string(), + spiel_id_field: "postId".to_string(), + timestamp_field: "createdAt".to_string(), + edited_field: "updatedAt".to_string(), + bot_field: "isBot".to_string(), + user_id_field: "authorId".to_string(), + text_field: "body".to_string(), + mapping_source: "ceo_alt".to_string(), + })) + ); + + // Each missing required flag errors + for (missing_flag, args) in [ + ( + "--ceo-posts", + &[ + "curate-posts", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--provider-mapping", + &[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--out", + &[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--timestamp-unit", + &[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + ][..], + ), + ] { + let err = parse_args(&to_args(args)).unwrap_err(); + assert!( + err.contains(&format!("missing required flag '{missing_flag}'")), + "expected missing {missing_flag}, got: {err}" + ); + } + + // Invalid --timestamp-unit values + for bad_unit in ["", " ", "ms", "sec", "SECONDS", "MILLIS", "micros"] { + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + bad_unit, + ])) + .unwrap_err(); + assert!( + err.contains("invalid --timestamp-unit"), + "expected invalid --timestamp-unit for '{bad_unit}', got: {err}" + ); + } + + // Missing flag value (at end and followed by --flag) + let err = parse_args(&to_args(&["curate-posts", "--ceo-posts"])).unwrap_err(); + assert!(err.contains("missing value for flag '--ceo-posts'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert!(err.contains("missing value for flag '--ceo-posts'"), "{err}"); + + // Duplicate flags including --timestamp-unit + for (dup_flag, args) in [ + ( + "--ceo-posts", + &[ + "curate-posts", + "--ceo-posts", + "a.bson", + "--ceo-posts=b.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--timestamp-unit", + &[ + "curate-posts", + "--ceo-posts", + "a.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--timestamp-unit=millis", + ][..], + ), + ( + "--key-field", + &[ + "curate-posts", + "--ceo-posts", + "a.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--key-field", + "k1", + "--key-field=k2", + ][..], + ), + ] { + let err = parse_args(&to_args(args)).unwrap_err(); + assert!( + err.contains(&format!("duplicate flag '{dup_flag}'")), + "expected duplicate {dup_flag}, got: {err}" + ); + } + + // Unknown flags and --from-mongo (bare, followed by other flags, or with =) + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--bogus", + "1", + ])) + .unwrap_err(); + assert_eq!(err, "unknown flag '--bogus' for curate-posts"); + + for from_mongo_args in [ + &["curate-posts", "--from-mongo"][..], + &[ + "curate-posts", + "--from-mongo", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + &["curate-posts", "--from-mongo=true"][..], + ] { + let err = parse_args(&to_args(from_mongo_args)).unwrap_err(); + assert_eq!(err, "unknown flag '--from-mongo' for curate-posts"); + } + + // Positional argument rejected + let err = parse_args(&to_args(&[ + "curate-posts", + "extra", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert_eq!(err, "unexpected positional argument 'extra' for curate-posts"); + + // Empty / blank field names and path values rejected + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts=", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert!(err.contains("empty value for flag '--ceo-posts'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--text-field", + " ", + ])) + .unwrap_err(); + assert!(err.contains("empty value for flag '--text-field'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--mapping-source", + " ", + ])) + .unwrap_err(); + assert!( + err.contains("empty value for flag '--mapping-source'"), + "{err}" + ); + + // Role collisions after defaults are applied + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--text-field", + "ceoId", + ])) + .unwrap_err(); + assert!(err.contains("cannot share BSON field 'ceoId'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--bot-field", + "shared", + "--user-id-field", + "shared", + ])) + .unwrap_err(); + assert!(err.contains("cannot share BSON field 'shared'"), "{err}"); + } } diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 6f3be0c3..936c0d64 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -28,6 +28,7 @@ use curate_etl::run_curate_corporate_actions::{ }; use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events}; use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d}; +use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts}; use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts}; use curate_etl::run_mongo::{ run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo, @@ -197,6 +198,16 @@ fn main() -> ExitCode { } } } + Ok(CliAction::CuratePosts(curate_args)) => match run_curate_posts(&curate_args) { + Ok(report) => { + println!("{}", format_curate_posts_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + }, Ok(CliAction::BenchSplit(rows)) => { let report = match run_split_benchmark(rows) { Ok(report) => report,