T-176: merge dev

This commit is contained in:
Studio 2026-12-02 15:50:40 -05:00
commit fc2ca6f483
13 changed files with 3618 additions and 369 deletions

View file

@ -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 `<out_dir>/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,37 @@ 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<str>` 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 `<out>/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 seconds
```
Inputs, defaults, and output rules:
- `--ceo-posts <path>` *(required)*: concatenated raw BSON (`mongodump` `ceoPosts.bson`).
- `--provider-mapping <path>` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`).
- `--out <dir>` *(required, dedicated output directory)*: dataset root where `<out>/events/year=YYYY/part.parquet` is atomically published. Because `curate-events` (filings + earnings) writes to the same `<out>/events` directory layout, `curate-posts` requires a dedicated `--out` directory and fails closed before any write if `<out>/events` already contains any `year=*` entry (leaving existing partitions byte-identical).
- `--timestamp-unit <seconds|millis>` *(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 <name>` *(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.

View file

@ -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 <VAR> | --mongo-uri <uri>] [--batch-size <N>] [--limit <N>] --provider-mapping <path> --out <dir> --shares-short-field <name> [--key-field <name>] [--report-date-field <name>] [--net-change-field <name>] [--pct-float-field <name>] [--mapping-source <name>]\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 <path> --qm-earnings <path> --provider-mapping <path> --out <dir> --filings-form-type-field <name> [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--earnings-key-field <name>] [--earnings-report-date-field <name>] [--earnings-announce-time-field <name>] [--earnings-fiscal-period-end-field <name>] [--earnings-actual-eps-field <name>] [--earnings-revenue-field <name>] [--mapping-source <name>]\n\
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
{name} curate-events --from-mongo [--mongo-uri-env <VAR> | --mongo-uri <uri>] [--batch-size <N>] [--limit <N>] [--date-gte <YYYY-MM-DD>] [--date-lt <YYYY-MM-DD>] --provider-mapping <path> --out <dir> --filings-form-type-field <name> [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--earnings-key-field <name>] [--earnings-report-date-field <name>] [--earnings-announce-time-field <name>] [--earnings-fiscal-period-end-field <name>] [--earnings-actual-eps-field <name>] [--earnings-revenue-field <name>] [--mapping-source <name>]\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 <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
Curate ceoPosts from BSON + provider_mapping TSV into <out>/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 <path> --te-market-data <path> [--te-symbol <sym>] --out <dir>\n\
{name} curate-shorts --ceo-shorts <path> --provider-mapping <path> --out <dir> --shares-short-field <name> [--key-field <name>] [--report-date-field <name>] [--net-change-field <name>] [--pct-float-field <name>] [--mapping-source <name>]\n\
{name} curate-events --qm-filings <path> --qm-earnings <path> --provider-mapping <path> --out <dir> --filings-form-type-field <name> [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--earnings-key-field <name>] [--earnings-report-date-field <name>] [--earnings-announce-time-field <name>] [--earnings-fiscal-period-end-field <name>] [--earnings-actual-eps-field <name>] [--earnings-revenue-field <name>] [--mapping-source <name>]\n\
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\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<CliAction, String> {
}))
}
fn set_path(slot: &mut Option<PathBuf>, 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<String>, 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<CliAction, String> {
let mut mongo = MongoFlagState::default();
let mut ceo_shorts: Option<PathBuf> = None;
@ -1040,28 +1079,6 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result<CliAction, String> {
continue;
}
let set_path = |slot: &mut Option<PathBuf>, 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<String>, 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<CliAction, String> {
Ok(CliAction::CurateShorts(parsed))
}
fn parse_curate_posts_args(args: &[&str]) -> Result<CliAction, String> {
let mut ceo_posts: Option<PathBuf> = None;
let mut provider_mapping: Option<PathBuf> = None;
let mut out_dir: Option<PathBuf> = None;
let mut timestamp_unit: Option<CeoPostsTimestampUnit> = None;
let mut key_field: Option<String> = None;
let mut spiel_id_field: Option<String> = None;
let mut timestamp_field: Option<String> = None;
let mut edited_field: Option<String> = None;
let mut bot_field: Option<String> = None;
let mut user_id_field: Option<String> = None;
let mut text_field: Option<String> = None;
let mut mapping_source: Option<String> = 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<CliAction, String> {
let mut mongo = MongoFlagState::default();
let mut qm_filings: Option<PathBuf> = None;
@ -1437,6 +1567,7 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
["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::<usize>() {
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}");
}
}

View file

@ -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,

View file

@ -17,11 +17,11 @@
//! 12. `total_assets` (`DOUBLE`, `OPTIONAL`)
//! 13. `total_equity` (`DOUBLE`, `OPTIONAL`)
//! 14. `shares_outstanding` (`DOUBLE`, `OPTIONAL`)
//! 15. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`)
//! 16. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`)
//! 17. `ttm_revenue` (`DOUBLE`, `OPTIONAL`)
//! 18. `ttm_net_income` (`DOUBLE`, `OPTIONAL`)
//! 19. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`)
//! 15. `ttm_revenue` (`DOUBLE`, `OPTIONAL`)
//! 16. `ttm_net_income` (`DOUBLE`, `OPTIONAL`)
//! 17. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`)
//! 18. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`)
//! 19. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`)
//! 20. `ttm_has_estimated_lag` (`BOOLEAN`, `OPTIONAL`)
//!
//! Each physical row flattens `periods[0]` (the latest visible resolved period) and the
@ -500,21 +500,7 @@ pub fn fundamentals_pit_parquet_schema() -> Result<TypePtr, ParquetError> {
.with_repetition(Repetition::OPTIONAL)
.build()?,
),
// 15. ttm_period_end INT32 DATE OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32)
.with_repetition(Repetition::OPTIONAL)
.with_logical_type(Some(LogicalType::Date))
.build()?,
),
// 16. ttm_currency STRING OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::OPTIONAL)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
// 17-19. TTM flow sums DOUBLE OPTIONAL
// 15-17. TTM flow sums DOUBLE OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_revenue", PhysicalType::DOUBLE)
.with_repetition(Repetition::OPTIONAL)
@ -530,6 +516,20 @@ pub fn fundamentals_pit_parquet_schema() -> Result<TypePtr, ParquetError> {
.with_repetition(Repetition::OPTIONAL)
.build()?,
),
// 18. ttm_period_end INT32 DATE OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32)
.with_repetition(Repetition::OPTIONAL)
.with_logical_type(Some(LogicalType::Date))
.build()?,
),
// 19. ttm_currency STRING OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::OPTIONAL)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
// 20. ttm_has_estimated_lag BOOLEAN OPTIONAL
Arc::new(
Type::primitive_type_builder("ttm_has_estimated_lag", PhysicalType::BOOLEAN)
@ -998,43 +998,43 @@ impl YearWriter {
&self.buf.shares_outstanding_def,
)
.map_err(map_pq)?;
// 15. ttm_period_end (INT32, OPTIONAL, DATE)
write_optional_i32_col(
&mut rg_writer,
&self.buf.ttm_period_end_values,
&self.buf.ttm_period_end_def,
)
.map_err(map_pq)?;
// 16. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING)
write_optional_interned_str_col(
&mut rg_writer,
&self.buf.ttm_currency_ids,
&self.buf.ttm_currency_def,
&self.buf.ttm_currency_interner,
scratch,
)
.map_err(map_pq)?;
// 17. ttm_revenue (DOUBLE, OPTIONAL)
// 15. ttm_revenue (DOUBLE, OPTIONAL)
write_optional_f64_col(
&mut rg_writer,
&self.buf.ttm_revenue_values,
&self.buf.ttm_revenue_def,
)
.map_err(map_pq)?;
// 18. ttm_net_income (DOUBLE, OPTIONAL)
// 16. ttm_net_income (DOUBLE, OPTIONAL)
write_optional_f64_col(
&mut rg_writer,
&self.buf.ttm_net_income_values,
&self.buf.ttm_net_income_def,
)
.map_err(map_pq)?;
// 19. ttm_operating_cash_flow (DOUBLE, OPTIONAL)
// 17. ttm_operating_cash_flow (DOUBLE, OPTIONAL)
write_optional_f64_col(
&mut rg_writer,
&self.buf.ttm_operating_cash_flow_values,
&self.buf.ttm_operating_cash_flow_def,
)
.map_err(map_pq)?;
// 18. ttm_period_end (INT32, OPTIONAL, DATE)
write_optional_i32_col(
&mut rg_writer,
&self.buf.ttm_period_end_values,
&self.buf.ttm_period_end_def,
)
.map_err(map_pq)?;
// 19. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING)
write_optional_interned_str_col(
&mut rg_writer,
&self.buf.ttm_currency_ids,
&self.buf.ttm_currency_def,
&self.buf.ttm_currency_interner,
scratch,
)
.map_err(map_pq)?;
// 20. ttm_has_estimated_lag (BOOLEAN, OPTIONAL)
write_bool_col(
&mut rg_writer,

View file

@ -23,7 +23,8 @@ use crate::events::{
};
use crate::fundamentals::{
build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod,
FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm, StatutoryLagVenue, TtmFlowFields,
FundamentalsFields, FundamentalsPeriodSlot, FundamentalsSnapshot, FundamentalsTtm,
StatutoryLagVenue, TtmFlowFields,
};
use crate::split::ymd_to_epoch_days;
@ -113,11 +114,11 @@ struct DecodedFundamentalsPitRow {
total_assets: Option<f64>,
total_equity: Option<f64>,
shares_outstanding: Option<f64>,
ttm_period_end: Option<i32>,
ttm_currency: Option<String>,
ttm_revenue: Option<f64>,
ttm_net_income: Option<f64>,
ttm_operating_cash_flow: Option<f64>,
ttm_period_end: Option<i32>,
ttm_currency: Option<String>,
ttm_has_estimated_lag: Option<bool>,
}
@ -345,11 +346,11 @@ fn read_parquet_rows(path: &Path) -> Vec<DecodedFundamentalsPitRow> {
let total_assets = read_opt_f64(11);
let total_equity = read_opt_f64(12);
let shares_outstanding = read_opt_f64(13);
let ttm_period_end = read_opt_i32(14);
let ttm_currency = read_opt_str(15);
let ttm_revenue = read_opt_f64(16);
let ttm_net_income = read_opt_f64(17);
let ttm_operating_cash_flow = read_opt_f64(18);
let ttm_revenue = read_opt_f64(14);
let ttm_net_income = read_opt_f64(15);
let ttm_operating_cash_flow = read_opt_f64(16);
let ttm_period_end = read_opt_i32(17);
let ttm_currency = read_opt_str(18);
let ttm_has_estimated_lag = read_opt_bool(19);
for i in 0..rg_rows {
@ -368,11 +369,11 @@ fn read_parquet_rows(path: &Path) -> Vec<DecodedFundamentalsPitRow> {
total_assets: total_assets[i],
total_equity: total_equity[i],
shares_outstanding: shares_outstanding[i],
ttm_period_end: ttm_period_end[i],
ttm_currency: ttm_currency[i].clone(),
ttm_revenue: ttm_revenue[i],
ttm_net_income: ttm_net_income[i],
ttm_operating_cash_flow: ttm_operating_cash_flow[i],
ttm_period_end: ttm_period_end[i],
ttm_currency: ttm_currency[i].clone(),
ttm_has_estimated_lag: ttm_has_estimated_lag[i],
});
}
@ -381,6 +382,80 @@ fn read_parquet_rows(path: &Path) -> Vec<DecodedFundamentalsPitRow> {
out
}
fn assert_decoded_matches_snapshot_bit_for_bit(
actual: &DecodedFundamentalsPitRow,
snapshot: &FundamentalsSnapshot<i32>,
) {
let latest = snapshot
.periods
.first()
.expect("snapshot must have at least one period");
assert_eq!(actual.listing_id, snapshot.key);
assert_eq!(
actual.effective_known_at,
snapshot.effective_known_at_utc_micros
);
assert_eq!(actual.known_at_source, snapshot.known_at_source);
assert_eq!(actual.has_estimated_lag, snapshot.has_estimated_lag);
assert_eq!(actual.period_end, latest.period_end);
assert_eq!(actual.fiscal_period, latest.fiscal_period.as_str());
assert_eq!(actual.currency, latest.currency);
assert_eq!(actual.period_known_at, latest.known_at_utc_micros);
assert_eq!(
actual.revenue.map(f64::to_bits),
latest.fields.revenue.map(f64::to_bits)
);
assert_eq!(
actual.net_income.map(f64::to_bits),
latest.fields.net_income.map(f64::to_bits)
);
assert_eq!(
actual.operating_cash_flow.map(f64::to_bits),
latest.fields.operating_cash_flow.map(f64::to_bits)
);
assert_eq!(
actual.total_assets.map(f64::to_bits),
latest.fields.total_assets.map(f64::to_bits)
);
assert_eq!(
actual.total_equity.map(f64::to_bits),
latest.fields.total_equity.map(f64::to_bits)
);
assert_eq!(
actual.shares_outstanding.map(f64::to_bits),
latest.fields.shares_outstanding.map(f64::to_bits)
);
match &snapshot.ttm {
Some(ttm) => {
assert_eq!(
actual.ttm_revenue.map(f64::to_bits),
ttm.flows.revenue.map(f64::to_bits)
);
assert_eq!(
actual.ttm_net_income.map(f64::to_bits),
ttm.flows.net_income.map(f64::to_bits)
);
assert_eq!(
actual.ttm_operating_cash_flow.map(f64::to_bits),
ttm.flows.operating_cash_flow.map(f64::to_bits)
);
assert_eq!(actual.ttm_period_end, Some(ttm.ending_period_end));
assert_eq!(actual.ttm_currency.as_deref(), Some(ttm.currency.as_str()));
assert_eq!(actual.ttm_has_estimated_lag, Some(ttm.has_estimated_lag));
}
None => {
assert_eq!(actual.ttm_revenue, None);
assert_eq!(actual.ttm_net_income, None);
assert_eq!(actual.ttm_operating_cash_flow, None);
assert_eq!(actual.ttm_period_end, None);
assert_eq!(actual.ttm_currency, None);
assert_eq!(actual.ttm_has_estimated_lag, None);
}
}
}
fn assert_no_transient_files(dir: &Path) {
if !dir.exists() {
return;
@ -654,20 +729,6 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() {
None,
ConvertedType::NONE,
),
(
"ttm_period_end",
PhysicalType::INT32,
Repetition::OPTIONAL,
Some(LogicalType::Date),
ConvertedType::DATE,
),
(
"ttm_currency",
PhysicalType::BYTE_ARRAY,
Repetition::OPTIONAL,
Some(LogicalType::String),
ConvertedType::UTF8,
),
(
"ttm_revenue",
PhysicalType::DOUBLE,
@ -689,6 +750,20 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() {
None,
ConvertedType::NONE,
),
(
"ttm_period_end",
PhysicalType::INT32,
Repetition::OPTIONAL,
Some(LogicalType::Date),
ConvertedType::DATE,
),
(
"ttm_currency",
PhysicalType::BYTE_ARRAY,
Repetition::OPTIONAL,
Some(LogicalType::String),
ConvertedType::UTF8,
),
(
"ttm_has_estimated_lag",
PhysicalType::BOOLEAN,
@ -741,19 +816,19 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() {
assert_eq!(decoded[0].total_assets, None);
assert_eq!(decoded[0].total_equity, Some(220.0));
assert_eq!(decoded[0].shares_outstanding, None);
assert_eq!(decoded[0].ttm_period_end, None);
assert_eq!(decoded[0].ttm_currency, None);
assert_eq!(decoded[0].ttm_revenue, None);
assert_eq!(decoded[0].ttm_net_income, None);
assert_eq!(decoded[0].ttm_operating_cash_flow, None);
assert_eq!(decoded[0].ttm_period_end, None);
assert_eq!(decoded[0].ttm_currency, None);
assert_eq!(decoded[0].ttm_has_estimated_lag, None);
// Row 1: ttm_has_estimated_lag = Some(false)
assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30)));
assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD"));
assert_eq!(decoded[1].ttm_revenue, Some(370.0));
assert_eq!(decoded[1].ttm_net_income, Some(37.0));
assert_eq!(decoded[1].ttm_operating_cash_flow, Some(55.0));
assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30)));
assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD"));
assert_eq!(decoded[1].ttm_has_estimated_lag, Some(false));
// Row 2: ttm_has_estimated_lag = Some(true), partial missing TTM flow, statutory lag source.
@ -761,16 +836,273 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() {
assert!(decoded[2].has_estimated_lag);
assert_eq!(decoded[2].fiscal_period, "FY");
assert_eq!(decoded[2].currency, "CAD");
assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30)));
assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD"));
assert_eq!(decoded[2].ttm_revenue, Some(450.0));
assert_eq!(decoded[2].ttm_net_income, None);
assert_eq!(decoded[2].ttm_operating_cash_flow, Some(60.0));
assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30)));
assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD"));
assert_eq!(decoded[2].ttm_has_estimated_lag, Some(true));
assert_no_transient_files(&tmp.path().join("fundamentals_pit"));
}
#[test]
fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero() {
let tmp = TempDirGuard::new("builder-roundtrip-bits");
let venues = BTreeMap::from([
(10_i32, StatutoryLagVenue::UsTsx),
(20_i32, StatutoryLagVenue::TsxvCse),
]);
let observations = vec![
// Listing 10: 5 consecutive quarters (Q1 2023 .. Q1 2024).
// Q1..Q4 2023 all have distinct non-null flow values so Q4 2023's snapshot carries
// three distinct non-null TTM flows (catching any positional TTM column transposition).
// Q1 2024 omits operating_cash_flow so its snapshot has ttm_operating_cash_flow = None
// while ttm_revenue and ttm_net_income remain populated and distinct.
obs(
10,
day(2023, 3, 31),
FiscalPeriod::Quarterly,
"USD",
Some(day(2023, 5, 2)),
FundamentalsFields {
revenue: Some(95.5),
net_income: Some(9.25),
operating_cash_flow: Some(17.75),
total_assets: Some(960.0),
total_equity: Some(380.0),
shares_outstanding: Some(49_500_000.0),
},
),
obs(
10,
day(2023, 6, 30),
FiscalPeriod::Quarterly,
"USD",
Some(day(2023, 8, 2)),
FundamentalsFields {
revenue: Some(101.25),
net_income: Some(11.5),
operating_cash_flow: Some(19.75),
total_assets: Some(1_000.0),
total_equity: Some(400.0),
shares_outstanding: Some(50_000_000.0),
},
),
obs(
10,
day(2023, 9, 30),
FiscalPeriod::Quarterly,
"USD",
Some(day(2023, 11, 3)),
FundamentalsFields {
revenue: Some(110.5),
net_income: Some(12.25),
operating_cash_flow: Some(21.0),
total_assets: None,
total_equity: Some(415.0),
shares_outstanding: Some(50_100_000.0),
},
),
obs(
10,
day(2023, 12, 31),
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 2, 14)),
FundamentalsFields {
revenue: Some(125.0),
net_income: Some(14.0),
operating_cash_flow: Some(22.5),
total_assets: Some(1_120.0),
total_equity: None,
shares_outstanding: Some(50_200_000.0),
},
),
obs(
10,
day(2024, 3, 31),
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 5, 1)),
FundamentalsFields {
revenue: Some(130.75),
net_income: Some(16.5),
operating_cash_flow: None,
total_assets: Some(1_150.0),
total_equity: Some(440.0),
shares_outstanding: None,
},
),
// Listing 20: unlinked observation -> statutory_lag_estimate (+60d for TSXV/CSE),
// ttm == None.
obs(
20,
day(2024, 3, 31),
FiscalPeriod::Quarterly,
"CAD",
None,
FundamentalsFields {
revenue: Some(42.5),
net_income: Some(-3.5),
operating_cash_flow: None,
total_assets: Some(25.0),
total_equity: Some(12.5),
shares_outstanding: Some(8_000_000.0),
},
),
];
let filings = vec![
filing(10, "2023-05-02T16:05:00 EDT", "10-Q"),
filing(10, "2023-08-02T16:10:00 EDT", "10-Q"),
filing(10, "2023-11-03T16:05:00 EDT", "10-Q"),
filing(10, "2024-02-14T16:15:00 EST", "10-Q"),
filing(10, "2024-05-01T16:20:00 EDT", "10-Q"),
];
let built = build_fundamentals_rows(observations, filings, &venues);
let mut snapshots = build_fundamentals_snapshots(&built.rows, 4).expect("build snapshots");
assert_eq!(snapshots.len(), 6);
// Append a direct snapshot carrying signed negative zero (-0.0) vs positive zero (+0.0) in
// statement fields (builder normalizes -0.0; this verifies the Parquet writer preserves exact
// IEEE-754 bit patterns without altering them).
snapshots.push(FundamentalsSnapshot {
key: 30_i32,
effective_known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0),
known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG,
has_estimated_lag: true,
periods: vec![FundamentalsPeriodSlot {
period_end: day(2024, 3, 31),
fiscal_period: FiscalPeriod::Quarterly,
currency: "CAD".to_string(),
known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0),
known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG,
has_estimated_lag: true,
fields: FundamentalsFields {
revenue: Some(-0.0_f64),
net_income: Some(0.0_f64),
operating_cash_flow: None,
total_assets: Some(10.0),
total_equity: None,
shares_outstanding: Some(1_000_000.0),
},
}],
ttm: None,
});
let rows_from_ref: Vec<FundamentalsPitParquetRow> = snapshots
.iter()
.map(FundamentalsPitParquetRow::from)
.collect();
let rows_from_owned: Vec<FundamentalsPitParquetRow> = snapshots
.clone()
.into_iter()
.map(FundamentalsPitParquetRow::from)
.collect();
assert_eq!(rows_from_ref, rows_from_owned);
let stats = write_fundamentals_pit_dataset(
tmp.path(),
&rows_from_ref,
FundamentalsPitWriteOptions {
row_group_rows: 2,
zstd_level: DEFAULT_ZSTD_LEVEL,
},
)
.expect("write builder snapshots");
let expected_by_year = BTreeMap::from([(2023, 3), (2024, 4)]);
assert_eq!(stats.rows_written, 7);
assert_eq!(stats.files_written, 2);
assert_eq!(stats.row_groups_written, 4);
assert_eq!(stats.rows_by_year, expected_by_year);
let mut total_bytes = 0u64;
for (&year, &expected_count) in &expected_by_year {
let path = tmp
.path()
.join(format!("fundamentals_pit/year={year:04}/part.parquet"));
assert!(path.is_file(), "missing {}", path.display());
total_bytes += fs::metadata(&path).expect("metadata").len();
let decoded = read_parquet_rows(&path);
let expected_snapshots: Vec<&FundamentalsSnapshot<i32>> = snapshots
.iter()
.filter(|s| partition_year_utc(s.effective_known_at_utc_micros) == year)
.collect();
assert_eq!(decoded.len(), expected_count);
assert_eq!(decoded.len(), expected_snapshots.len());
for (actual_row, snap) in decoded.iter().zip(expected_snapshots.iter()) {
assert_decoded_matches_snapshot_bit_for_bit(actual_row, snap);
}
if year == 2024 {
// Q4 2023 snapshot (filed 2024-02-14): all three TTM flows present and distinct.
let full_ttm = decoded
.iter()
.find(|r| r.listing_id == 10 && r.period_end == day(2023, 12, 31))
.expect("listing 10 Q4 2023 row");
assert_eq!(full_ttm.ttm_revenue, Some(432.25));
assert_eq!(full_ttm.ttm_net_income, Some(47.0));
assert_eq!(full_ttm.ttm_operating_cash_flow, Some(81.0));
assert_eq!(full_ttm.ttm_period_end, Some(day(2023, 12, 31)));
assert_eq!(full_ttm.ttm_currency.as_deref(), Some("USD"));
assert_eq!(full_ttm.ttm_has_estimated_lag, Some(false));
// Q1 2024 snapshot (filed 2024-05-01): partial null TTM flow.
let partial_ttm = decoded
.iter()
.find(|r| r.listing_id == 10 && r.period_end == day(2024, 3, 31))
.expect("listing 10 Q1 2024 row");
assert_eq!(partial_ttm.ttm_revenue, Some(467.5));
assert_eq!(partial_ttm.ttm_net_income, Some(54.25));
assert_eq!(partial_ttm.ttm_operating_cash_flow, None);
assert_eq!(partial_ttm.ttm_period_end, Some(day(2024, 3, 31)));
assert_eq!(partial_ttm.ttm_currency.as_deref(), Some("USD"));
assert_eq!(partial_ttm.ttm_has_estimated_lag, Some(false));
// Listing 20: statutory lag provenance and ttm == None.
let est_row = decoded
.iter()
.find(|r| r.listing_id == 20)
.expect("listing 20 row");
assert_eq!(est_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
assert!(est_row.has_estimated_lag);
assert_eq!(est_row.ttm_revenue, None);
assert_eq!(est_row.ttm_net_income, None);
assert_eq!(est_row.ttm_operating_cash_flow, None);
assert_eq!(est_row.ttm_period_end, None);
assert_eq!(est_row.ttm_currency, None);
assert_eq!(est_row.ttm_has_estimated_lag, None);
// Listing 30: exact IEEE-754 -0.0 vs +0.0 bit preservation across Parquet write/read.
let signed_zero_row = decoded
.iter()
.find(|r| r.listing_id == 30)
.expect("listing 30 row");
assert_eq!(
signed_zero_row.revenue.map(f64::to_bits),
Some((-0.0_f64).to_bits())
);
assert_ne!(
signed_zero_row.revenue.map(f64::to_bits),
Some(0.0_f64.to_bits())
);
assert_eq!(
signed_zero_row.net_income.map(f64::to_bits),
Some(0.0_f64.to_bits())
);
}
}
assert_eq!(stats.bytes_written, total_bytes);
assert_no_transient_files(&tmp.path().join("fundamentals_pit"));
}
#[test]
fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm() {
let listing_id = 42_i32;
@ -1033,6 +1365,11 @@ fn utc_year_partitioning_interleaved_listings_and_midnight_boundary() {
let path_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet");
assert!(path_2023.is_file());
assert!(path_2024.is_file());
assert_eq!(
stats.bytes_written,
fs::metadata(&path_2023).expect("meta 2023").len()
+ fs::metadata(&path_2024).expect("meta 2024").len()
);
let decoded_2023 = read_parquet_rows(&path_2023);
let decoded_2024 = read_parquet_rows(&path_2024);
@ -1264,7 +1601,6 @@ fn publish_failure_on_later_year_rolls_back_replaced_and_new_partitions() {
assert_no_transient_files(&tmp.path().join("fundamentals_pit"));
}
// ---------------------------------------------------------------------------------------------
// QA additions (T-143): full-row round-trip equality, builder estimated-lag provenance,
// partial-rewrite semantics, deterministic bytes, and remaining typed validation errors.
@ -1291,11 +1627,11 @@ fn expected_decoded(row: &FundamentalsPitParquetRow) -> DecodedFundamentalsPitRo
total_assets: latest.fields.total_assets,
total_equity: latest.fields.total_equity,
shares_outstanding: latest.fields.shares_outstanding,
ttm_period_end: ttm.map(|t| t.ending_period_end),
ttm_currency: ttm.map(|t| t.currency.clone()),
ttm_revenue: ttm.and_then(|t| t.flows.revenue),
ttm_net_income: ttm.and_then(|t| t.flows.net_income),
ttm_operating_cash_flow: ttm.and_then(|t| t.flows.operating_cash_flow),
ttm_period_end: ttm.map(|t| t.ending_period_end),
ttm_currency: ttm.map(|t| t.currency.clone()),
ttm_has_estimated_lag: ttm.map(|t| t.has_estimated_lag),
}
}
@ -1594,11 +1930,11 @@ fn builder_statutory_lag_snapshots_keep_estimated_provenance_on_disk() {
assert_eq!(decoded[1].operating_cash_flow, None);
// Only two quarters exist, so TTM is unavailable and every ttm_* column is null.
for r in &decoded {
assert_eq!(r.ttm_period_end, None);
assert_eq!(r.ttm_currency, None);
assert_eq!(r.ttm_revenue, None);
assert_eq!(r.ttm_net_income, None);
assert_eq!(r.ttm_operating_cash_flow, None);
assert_eq!(r.ttm_period_end, None);
assert_eq!(r.ttm_currency, None);
assert_eq!(r.ttm_has_estimated_lag, None);
}
}

View file

@ -0,0 +1,191 @@
//! End-to-end tests for the file-mode curate-posts CLI.
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use bson::{doc, Document};
use curate_etl::bson_ceo_posts::CeoPostsTimestampUnit;
use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts, CuratePostsArgs};
use parquet::file::reader::{FileReader, SerializedFileReader};
use parquet::record::RowAccessor;
const POSTED: i64 = 1_718_460_000;
const EDITED: i64 = POSTED + 3_600;
const PARTITION: &str = "events/year=2024/part.parquet";
const MAPPING: &str = "ceo_alt\tCH_1\t2020-01-01\t\t555\nceo_alt\tCH_2\t2020-01-01\t\t556\n";
const CUSTOM_FLAGS: &[&str] = &[
"--key-field=channel",
"--spiel-id-field=id",
"--timestamp-field=ts",
"--edited-field=ed",
"--bot-field=isBot",
"--user-id-field=author",
"--text-field=body",
"--mapping-source=ceo_alt",
];
struct TempDir(PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn cli() -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_curate-etl"));
command.arg("curate-posts");
command
}
fn curate(dir: &Path, out: &str, unit: &str) -> Output {
cli()
.current_dir(dir)
.args([
"--ceo-posts",
"posts.bson",
"--provider-mapping=mapping.tsv",
])
.args(["--out", out, "--timestamp-unit", unit])
.args(CUSTOM_FLAGS)
.output()
.expect("run curate-posts")
}
fn write_posts(path: &Path, scale: i64, edited_text: &str) {
let posts: [Document; 3] = [
doc! {
"channel": "CH_1", "id": "p-1", "ts": POSTED * scale,
"ed": EDITED * scale, "author": "u1", "body": edited_text,
},
doc! {
"channel": "CH_2", "id": "wire-1", "ts": POSTED * scale,
"isBot": "1", "body": "wire release",
},
doc! {
"channel": "unmapped", "id": "p-2", "ts": POSTED * scale,
"body": "unmapped post",
},
];
let bytes: Vec<u8> = posts
.iter()
.flat_map(|post| post.to_vec().unwrap())
.collect();
fs::write(path, bytes).expect("write concatenated BSON");
}
#[test]
fn cli_publishes_runner_equivalent_posts_and_preserves_an_existing_partition() {
// Use the runner's fixed custom-field and edited-post fixture, plus a wire and an unmapped row.
let path = std::env::temp_dir().join(format!("curate-posts-cli-{}", std::process::id()));
fs::create_dir(&path).expect("create isolated test directory");
let dir = TempDir(path);
let bson = dir.0.join("posts.bson");
let mapping = dir.0.join("mapping.tsv");
write_posts(&bson, 1, "hello");
fs::write(&mapping, MAPPING).unwrap();
let baseline_dir = dir.0.join("baseline");
let baseline_report = run_curate_posts(&CuratePostsArgs {
ceo_posts: bson.clone(),
provider_mapping: mapping,
out_dir: baseline_dir.clone(),
timestamp_unit: CeoPostsTimestampUnit::Seconds,
key_field: "channel".into(),
spiel_id_field: "id".into(),
timestamp_field: "ts".into(),
edited_field: "ed".into(),
bot_field: "isBot".into(),
user_id_field: "author".into(),
text_field: "body".into(),
mapping_source: "ceo_alt".into(),
})
.expect("run library baseline");
let baseline = fs::read(baseline_dir.join(PARTITION)).unwrap();
let expected_report = format_curate_posts_report(&baseline_report);
for (unit, scale) in [("seconds", 1), ("millis", 1_000)] {
write_posts(&bson, scale, "hello");
let result = curate(&dir.0, unit, unit);
assert!(result.status.success(), "{unit}: {:?}", result);
assert!(result.stderr.is_empty());
let stdout = String::from_utf8(result.stdout).unwrap();
assert_eq!(
stdout.lines().take(5).collect::<Vec<_>>(),
expected_report.lines().take(5).collect::<Vec<_>>()
);
assert!(stdout.contains("docs_framed=3"));
assert!(stdout.contains("dropped_unmapped=1"));
assert!(stdout.contains("rows_written=2"));
assert!(stdout.lines().last().unwrap().contains("timing:"));
assert_eq!(
fs::read(dir.0.join(unit).join(PARTITION)).unwrap(),
baseline
);
}
let partition = dir.0.join("millis").join(PARTITION);
let reader = SerializedFileReader::new(File::open(&partition).unwrap()).unwrap();
let rows: Vec<_> = reader
.get_row_iter(None)
.unwrap()
.map(Result::unwrap)
.collect();
assert_eq!(rows.len(), 2);
for (row, listing, subtype, known_at) in [
(&rows[0], 555, "retail", EDITED),
(&rows[1], 556, "newswire", POSTED),
] {
assert_eq!(row.get_int(0).unwrap(), listing);
assert_eq!(row.get_timestamp_micros(1).unwrap(), POSTED * 1_000_000);
assert_eq!(row.get_timestamp_micros(2).unwrap(), known_at * 1_000_000);
assert_eq!(row.get_string(4).unwrap(), "post");
assert_eq!(row.get_string(5).unwrap(), subtype);
}
let edited_text_visible = |cutoff| {
rows.iter().any(|row| {
row.get_timestamp_micros(2).unwrap() <= cutoff
&& row.get_string(6).unwrap().contains(r#""text":"hello""#)
})
};
assert!(!edited_text_visible(EDITED * 1_000_000 - 1));
assert!(edited_text_visible(EDITED * 1_000_000));
write_posts(&bson, 1_000, "replacement");
let retry = curate(&dir.0, "millis", "millis");
assert_eq!(retry.status.code(), Some(1));
assert!(retry.stdout.is_empty());
assert!(String::from_utf8_lossy(&retry.stderr)
.starts_with("error: refusing to overwrite existing events partition"));
assert_eq!(fs::read(partition).unwrap(), baseline);
}
#[test]
fn cli_reports_usage_for_invalid_posts_flags() {
for (args, error) in [
(
&["--from-mongo"][..],
"unknown flag '--from-mongo' for curate-posts",
),
(
&["--timestamp-unit", "--out=x"][..],
"missing value for flag '--timestamp-unit'",
),
(
&["--text-field=first", "--text-field", "second"][..],
"duplicate flag '--text-field'",
),
] {
let result = cli().args(args).output().expect("run curate-posts");
assert_eq!(result.status.code(), Some(1), "{args:?}");
assert!(result.stdout.is_empty(), "{args:?}");
let stderr = String::from_utf8(result.stderr).unwrap();
assert_eq!(
stderr.lines().next(),
Some(format!("error: {error}").as_str())
);
assert!(stderr.contains("curate-posts --ceo-posts"), "{stderr}");
}
}