stock-bot/tools/curate-etl/src/run_curate_fundamentals.rs

1296 lines
50 KiB
Rust

//! File-to-file `curate-fundamentals` runner (`M2.2m`).
//!
//! Streams concatenated raw BSON `qmFinancials` and `qmFilings` dump files alongside
//! `provider_mapping.tsv` and `listing_venues.tsv` into atomically published
//! `<out_dir>/fundamentals_pit/year=YYYY/part.parquet` partitions via
//! [`curate_and_write_fundamentals`].
//!
//! # Contract & Point-in-Time Rules
//! - `qmFinancials` field defaults are restricted strictly to repo-evidenced top-level names
//! (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`). The `currency` path, all six
//! numeric metric paths (`Option<String>`), and [`CurateFundamentalsFiscalPeriod`] have **no
//! defaults** and must be supplied explicitly.
//! - `qmFilings` field defaults match `run_curate_events` (`symbol`, `timefiled`), while
//! `form_type` has no default and `filing_id` / `url` are optional.
//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from
//! [`crate::run_curate_bars::load_provider_mapping_tsv`].
//! - `listing_venues.tsv` uses a strict headerless 2-column TSV format `listing_id<TAB>venue`
//! where `venue` is exactly `us_tsx` or `tsxv_cse` ([`load_listing_venues_tsv`]).
//! - Decoded provider keys are preserved verbatim (no trimming or suffix rewriting) and resolved
//! to permanent `listing_id`s inside [`curate_and_write_fundamentals`].
//! - **In-memory accumulation:** [`RawBsonChunkReader`] bounds only the raw BSON framing buffer
//! (`*_peak_chunk_bytes`); decoded observations and filings accumulate in memory before
//! [`curate_and_write_fundamentals`] runs.
//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_and_write_fundamentals`],
//! returning `Ok` with `rows_written == 0` and `files_written == 0` without creating
//! `<out_dir>/fundamentals_pit` or modifying any pre-existing partitions.
//! - **Fail-closed safety:** invalid field/fiscal config, blank `mapping_source`, `k == 0`,
//! unreadable inputs, malformed/overlapping `provider_mapping.tsv`, malformed/duplicate
//! `listing_venues.tsv`, truncated/corrupt BSON, `out_dir` or `<out_dir>/fundamentals_pit`
//! occupied by a regular file, or any input path resolving to `out_dir`, `<out_dir>/fundamentals_pit`,
//! or an existing `year=YYYY` partition target all return a typed [`RunCurateFundamentalsError`]
//! before anything is created or modified under `out_dir`.
//!
//! # Counter Conservation Invariants
//! Every successful [`CurateFundamentalsRunReport`] satisfies:
//! - `financials_docs_framed as usize == financials_decode.docs_in == financials_decode.rows_out + financials_decode.skipped_total()`
//! - `filings_docs_framed as usize == filings_decode.docs_in == filings_decode.rows_out + filings_decode.skipped_total()`
//! - `financials_decode.rows_out == curate_stats.observations_in`
//! - `filings_decode.rows_out == curate_stats.filings_in`
//! - `write_stats.rows_written == curate_stats.rows_out`
use std::collections::{BTreeMap, HashSet};
use std::error::Error;
use std::fmt::{self, Write as _};
use std::fs::{self, File};
use std::io;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use crate::bson_qm_events::{
BsonQmEventsError, BsonQmFilingsDecodeStats, QmFilingsFieldNames, DEFAULT_FILINGS_KEY_FIELD,
DEFAULT_FILINGS_TIMEFILED_FIELD,
};
use crate::bson_qm_financials::{
BsonQmFinancialsDecodeStats, BsonQmFinancialsError, QmFinancialsFieldNames,
QmFinancialsFiscalPeriod, DEFAULT_QM_FINANCIALS_KEY_FIELD,
DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD, DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD,
DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD,
};
use crate::bson_stream::{
decode_qm_filings_chunks, decode_qm_financials_chunks, BsonQmEventsStreamError,
BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader,
};
use crate::curate_fundamentals::{
curate_and_write_fundamentals_with_legacy, CurateFundamentalsStats,
CurateFundamentalsWriteError,
};
use crate::events::QmFiling;
use crate::fundamentals::{FinancialObservation, FiscalPeriod, StatutoryLagVenue};
use crate::parquet_fundamentals::{FundamentalsPitWriteOptions, FundamentalsPitWriteStats};
use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable};
use crate::run_curate_bars::{
load_provider_mapping_tsv, parse_strict_positive_i32, read_tsv_lines, RunCurateBarsError,
};
/// Default `mapping_source` passed to `provider_mapping` lookups for `qmFinancials` / `qmFilings`.
pub const DEFAULT_FUNDAMENTALS_MAPPING_SOURCE: &str = "qm";
/// Owned fiscal-period resolution policy for [`CurateFundamentalsArgs`].
///
/// Mirrors [`QmFinancialsFiscalPeriod`] without borrowing lifetimes so arguments can be stored
/// and passed cleanly to [`run_curate_fundamentals`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CurateFundamentalsFiscalPeriod {
/// Assign a fixed [`FiscalPeriod`] to every decoded `qmFinancials` document.
Fixed(FiscalPeriod),
/// Match exact `report_period` BSON string values against explicit quarterly and annual lists.
ByTokens {
quarterly: Vec<String>,
annual: Vec<String>,
},
}
impl CurateFundamentalsFiscalPeriod {
/// Borrows this policy as [`QmFinancialsFiscalPeriod`] for validation or decoding.
pub fn with_borrowed<R>(&self, f: impl FnOnce(QmFinancialsFiscalPeriod<'_>) -> R) -> R {
match self {
Self::Fixed(period) => f(QmFinancialsFiscalPeriod::Fixed(*period)),
Self::ByTokens { quarterly, annual } => {
let q_refs: Vec<&str> = quarterly.iter().map(String::as_str).collect();
let a_refs: Vec<&str> = annual.iter().map(String::as_str).collect();
f(QmFinancialsFiscalPeriod::ByTokens {
quarterly: &q_refs,
annual: &a_refs,
})
}
}
}
}
/// Arguments for [`run_curate_fundamentals`] and [`run_curate_fundamentals_with_readers`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateFundamentalsArgs {
pub qm_financials: PathBuf,
pub qm_financials_old: Option<PathBuf>,
pub qm_filings: PathBuf,
pub provider_mapping: PathBuf,
pub listing_venues: PathBuf,
pub out_dir: PathBuf,
pub financials_key_field: String,
pub financials_period_end_field: String,
pub financials_report_date_field: String,
pub financials_report_period_field: String,
pub financials_currency_field: String,
pub financials_revenue_field: Option<String>,
pub financials_net_income_field: Option<String>,
pub financials_operating_cash_flow_field: Option<String>,
pub financials_total_assets_field: Option<String>,
pub financials_total_equity_field: Option<String>,
pub financials_shares_outstanding_field: Option<String>,
pub fiscal_period: CurateFundamentalsFiscalPeriod,
pub filings_key_field: String,
pub filings_timefiled_field: String,
pub filings_form_type_field: String,
pub filings_filing_id_field: Option<String>,
pub filings_url_field: Option<String>,
pub mapping_source: String,
pub k: usize,
}
impl CurateFundamentalsArgs {
/// Constructs arguments pre-populated with the four repo-evidenced `qmFinancials` defaults
/// (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified
/// `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`.
///
/// Unverified fields (`financials_currency_field`, all six numeric `Option<String>` paths,
/// `fiscal_period`, `filings_form_type_field`, and snapshot period limit `k`) must be supplied
/// explicitly. `filings_filing_id_field` and `filings_url_field` default to `None`.
#[allow(clippy::too_many_arguments)]
pub fn with_verified_defaults(
qm_financials: PathBuf,
qm_filings: PathBuf,
provider_mapping: PathBuf,
listing_venues: PathBuf,
out_dir: PathBuf,
financials_currency_field: impl Into<String>,
financials_revenue_field: Option<String>,
financials_net_income_field: Option<String>,
financials_operating_cash_flow_field: Option<String>,
financials_total_assets_field: Option<String>,
financials_total_equity_field: Option<String>,
financials_shares_outstanding_field: Option<String>,
fiscal_period: CurateFundamentalsFiscalPeriod,
filings_form_type_field: impl Into<String>,
k: usize,
) -> Self {
Self {
qm_financials,
qm_financials_old: None,
qm_filings,
provider_mapping,
listing_venues,
out_dir,
financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(),
financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(),
financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(),
financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string(),
financials_currency_field: financials_currency_field.into(),
financials_revenue_field,
financials_net_income_field,
financials_operating_cash_flow_field,
financials_total_assets_field,
financials_total_equity_field,
financials_shares_outstanding_field,
fiscal_period,
filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(),
filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(),
filings_form_type_field: filings_form_type_field.into(),
filings_filing_id_field: None,
filings_url_field: None,
mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(),
k,
}
}
/// Borrows the configured `qmFinancials` BSON field paths as [`QmFinancialsFieldNames`].
#[inline]
pub fn financials_field_names(&self) -> QmFinancialsFieldNames<'_> {
QmFinancialsFieldNames {
key: self.financials_key_field.as_str(),
period_end: self.financials_period_end_field.as_str(),
report_date: self.financials_report_date_field.as_str(),
report_period: self.financials_report_period_field.as_str(),
currency: self.financials_currency_field.as_str(),
revenue: self.financials_revenue_field.as_deref(),
net_income: self.financials_net_income_field.as_deref(),
operating_cash_flow: self.financials_operating_cash_flow_field.as_deref(),
total_assets: self.financials_total_assets_field.as_deref(),
total_equity: self.financials_total_equity_field.as_deref(),
shares_outstanding: self.financials_shares_outstanding_field.as_deref(),
}
}
/// Borrows the configured `qmFilings` BSON field names as [`QmFilingsFieldNames`].
#[inline]
pub fn filings_field_names(&self) -> QmFilingsFieldNames<'_> {
QmFilingsFieldNames {
key: self.filings_key_field.as_str(),
timefiled: self.filings_timefiled_field.as_str(),
form_type: self.filings_form_type_field.as_str(),
filing_id: self.filings_filing_id_field.as_deref(),
url: self.filings_url_field.as_deref(),
}
}
}
/// Full run report produced by [`run_curate_fundamentals`] and
/// [`run_curate_fundamentals_with_readers`].
#[derive(Debug, Clone, PartialEq)]
pub struct CurateFundamentalsRunReport {
pub financials_docs_framed: u64,
pub financials_bytes_read: u64,
pub financials_peak_chunk_bytes: usize,
pub financials_decode: BsonQmFinancialsDecodeStats,
pub filings_docs_framed: u64,
pub filings_bytes_read: u64,
pub filings_peak_chunk_bytes: usize,
pub filings_decode: BsonQmFilingsDecodeStats,
pub curate_stats: CurateFundamentalsStats,
pub write_stats: FundamentalsPitWriteStats,
pub elapsed_secs: f64,
}
/// Typed errors returned by [`load_listing_venues_tsv`], [`run_curate_fundamentals`], and
/// [`run_curate_fundamentals_with_readers`].
///
/// Every variant's `Display` output is a single line naming the offending path (and line number or
/// byte offset where applicable).
#[derive(Debug)]
pub enum RunCurateFundamentalsError {
InvalidOutDir {
path: PathBuf,
detail: String,
},
InspectOutDir {
path: PathBuf,
source: io::Error,
},
InvalidFinancialsConfig {
path: PathBuf,
source: BsonQmFinancialsError,
},
InvalidFilingsFieldNames {
path: PathBuf,
source: BsonQmEventsError,
},
EmptyMappingSource,
InvalidPeriodLimit {
k: usize,
},
OpenInput {
label: &'static str,
path: PathBuf,
source: io::Error,
},
ReadInput {
label: &'static str,
path: PathBuf,
source: io::Error,
},
TsvParse {
path: PathBuf,
line: usize,
detail: String,
},
ProviderMapping {
path: PathBuf,
source: ProviderMappingError,
},
BsonStream {
label: &'static str,
path: PathBuf,
source: BsonStreamError,
},
CorruptFinancialsBson {
path: PathBuf,
offset: u64,
source: BsonQmFinancialsError,
},
CorruptFilingsBson {
path: PathBuf,
offset: u64,
source: BsonQmEventsError,
},
CurateWrite {
out_dir: PathBuf,
source: CurateFundamentalsWriteError,
},
}
struct SingleLineWriter<'a, 'b> {
f: &'a mut fmt::Formatter<'b>,
}
impl fmt::Write for SingleLineWriter<'_, '_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
let mut rest = s;
while let Some(idx) = rest.find(['\n', '\r']) {
let (head, tail) = rest.split_at(idx);
if !head.is_empty() {
self.f.write_str(head)?;
}
let mut chars = tail.chars();
match chars.next() {
Some('\n') => self.f.write_str("\\n")?,
Some('\r') => self.f.write_str("\\r")?,
_ => unreachable!(),
}
rest = chars.as_str();
}
if !rest.is_empty() {
self.f.write_str(rest)?;
}
Ok(())
}
}
impl fmt::Display for RunCurateFundamentalsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut w = SingleLineWriter { f };
match self {
Self::InvalidOutDir { path, detail } => {
write!(w, "invalid --out '{}': {detail}", path.display())
}
Self::InspectOutDir { path, source } => {
write!(
w,
"failed to inspect output path '{}': {source}",
path.display()
)
}
Self::InvalidFinancialsConfig { path, source } => {
write!(
w,
"invalid qm-financials config for '{}': {source}",
path.display()
)
}
Self::InvalidFilingsFieldNames { path, source } => {
write!(
w,
"invalid qm-filings field config for '{}': {source}",
path.display()
)
}
Self::EmptyMappingSource => {
write!(w, "invalid --mapping-source: must not be empty or blank")
}
Self::InvalidPeriodLimit { k } => {
write!(w, "invalid snapshot period limit k={k}: must be >= 1")
}
Self::OpenInput {
label,
path,
source,
} => write!(w, "failed to open {label} '{}': {source}", path.display()),
Self::ReadInput {
label,
path,
source,
} => write!(w, "failed to read {label} '{}': {source}", path.display()),
Self::TsvParse { path, line, detail } => {
write!(w, "{}:{line}: {detail}", path.display())
}
Self::ProviderMapping { path, source } => {
write!(w, "invalid provider_mapping '{}': {source}", path.display())
}
Self::BsonStream {
label,
path,
source,
} => write!(w, "failed reading {label} '{}': {source}", path.display()),
Self::CorruptFinancialsBson {
path,
offset,
source,
} => write!(
w,
"corrupt qm-financials BSON '{}' at byte offset {offset}: {source}",
path.display()
),
Self::CorruptFilingsBson {
path,
offset,
source,
} => write!(
w,
"corrupt qm-filings BSON '{}' at byte offset {offset}: {source}",
path.display()
),
Self::CurateWrite { out_dir, source } => {
write!(w, "curate/write to '{}' failed: {source}", out_dir.display())
}
}
}
}
impl Error for RunCurateFundamentalsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::InspectOutDir { source, .. } => Some(source),
Self::InvalidFinancialsConfig { source, .. } => Some(source),
Self::InvalidFilingsFieldNames { source, .. } => Some(source),
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
Self::ProviderMapping { source, .. } => Some(source),
Self::BsonStream { source, .. } => Some(source),
Self::CorruptFinancialsBson { source, .. } => Some(source),
Self::CorruptFilingsBson { source, .. } => Some(source),
Self::CurateWrite { source, .. } => Some(source),
Self::InvalidOutDir { .. }
| Self::EmptyMappingSource
| Self::InvalidPeriodLimit { .. }
| Self::TsvParse { .. } => None,
}
}
}
fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateFundamentalsError {
match err {
RunCurateBarsError::OpenInput {
label,
path,
source,
} => RunCurateFundamentalsError::OpenInput {
label,
path,
source,
},
RunCurateBarsError::ReadInput {
label,
path,
source,
} => RunCurateFundamentalsError::ReadInput {
label,
path,
source,
},
RunCurateBarsError::TsvParse { path, line, detail } => {
RunCurateFundamentalsError::TsvParse { path, line, detail }
}
RunCurateBarsError::ProviderMapping { path, source } => {
RunCurateFundamentalsError::ProviderMapping { path, source }
}
other => RunCurateFundamentalsError::TsvParse {
path: path.to_path_buf(),
line: 0,
detail: other.to_string(),
},
}
}
/// Loads `listing_venues.tsv` into an ordered `listing_id -> StatutoryLagVenue` map.
///
/// Format (no header, 2 `\t`-separated columns):
/// `listing_id \t venue`
///
/// `listing_id` must be a strictly positive ASCII base-10 `i32` (no sign or surrounding
/// whitespace). `venue` must be exact `"us_tsx"` or `"tsxv_cse"`. Duplicate `listing_id`s,
/// wrong column counts, unknown venues, and interior blank lines fail closed with a typed
/// single-line error naming `path` and the 1-based line number.
pub fn load_listing_venues_tsv(
path: &Path,
) -> Result<BTreeMap<i32, StatutoryLagVenue>, RunCurateFundamentalsError> {
let mut venues = BTreeMap::new();
read_tsv_lines(path, "listing-venues", |_line_no, line| {
let mut cols = line.split('\t');
let id_str = cols
.next()
.ok_or_else(|| "expected 2 tab-separated columns (listing_id, venue)".to_string())?;
let venue_str = cols.next().ok_or_else(|| {
"expected 2 tab-separated columns (listing_id, venue), got 1".to_string()
})?;
if cols.next().is_some() {
let count = line.split('\t').count();
return Err(format!(
"expected 2 tab-separated columns (listing_id, venue), got {count}"
));
}
let listing_id = parse_strict_positive_i32(id_str).ok_or_else(|| {
format!("invalid listing_id '{id_str}': expected strictly positive integer")
})?;
let venue = match venue_str {
"us_tsx" => StatutoryLagVenue::UsTsx,
"tsxv_cse" => StatutoryLagVenue::TsxvCse,
other => {
return Err(format!(
"unknown venue '{other}': expected 'us_tsx' or 'tsxv_cse'"
));
}
};
if venues.insert(listing_id, venue).is_some() {
return Err(format!("duplicate listing_id {listing_id}"));
}
Ok(())
})
.map_err(|err| map_tsv_error(path, err))?;
Ok(venues)
}
/// Resolves `path` to an absolute normalized path while preserving OS symlink-before-`..`
/// semantics: if `path` exists it is canonicalized directly; otherwise components are walked
/// left-to-right, canonicalizing each existing prefix before resolving `..`, and only lexically
/// normalizing `..` within any non-existent suffix.
fn resolve_normalized_path(path: &Path) -> PathBuf {
if let Ok(canon) = path.canonicalize() {
return canon;
}
let abs = if path.is_absolute() {
path.to_path_buf()
} else if let Ok(cwd) = std::env::current_dir() {
cwd.join(path)
} else {
path.to_path_buf()
};
if let Ok(canon) = abs.canonicalize() {
return canon;
}
let mut resolved = PathBuf::new();
for comp in abs.components() {
match comp {
Component::Prefix(prefix) => resolved.push(prefix.as_os_str()),
Component::RootDir => resolved.push(Component::RootDir.as_os_str()),
Component::CurDir => {}
Component::Normal(seg) => {
resolved.push(seg);
if let Ok(canon) = resolved.canonicalize() {
resolved = canon;
}
}
Component::ParentDir => {
resolved.push(Component::ParentDir.as_os_str());
if let Ok(canon) = resolved.canonicalize() {
resolved = canon;
} else {
resolved.pop();
if matches!(resolved.components().next_back(), Some(Component::Normal(_))) {
resolved.pop();
}
}
}
}
}
resolved
}
fn validate_out_dir_and_inputs(
args: &CurateFundamentalsArgs,
) -> Result<(), RunCurateFundamentalsError> {
if args.out_dir.as_os_str().is_empty() {
return Err(RunCurateFundamentalsError::InvalidOutDir {
path: args.out_dir.clone(),
detail: "output directory path must not be empty".to_string(),
});
}
match fs::metadata(&args.out_dir) {
Ok(meta) if !meta.is_dir() => {
return Err(RunCurateFundamentalsError::InvalidOutDir {
path: args.out_dir.clone(),
detail: "path exists and is not a directory".to_string(),
});
}
Ok(_) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(source) => {
return Err(RunCurateFundamentalsError::InspectOutDir {
path: args.out_dir.clone(),
source,
});
}
}
let fundamentals_dir = args.out_dir.join("fundamentals_pit");
let fundamentals_dir_exists = match fs::metadata(&fundamentals_dir) {
Ok(meta) if !meta.is_dir() => {
return Err(RunCurateFundamentalsError::InvalidOutDir {
path: fundamentals_dir,
detail: "fundamentals_pit output path exists and is not a directory".to_string(),
});
}
Ok(_) => true,
Err(err) if err.kind() == io::ErrorKind::NotFound => false,
Err(source) => {
return Err(RunCurateFundamentalsError::InspectOutDir {
path: fundamentals_dir,
source,
});
}
};
let resolved_out = resolve_normalized_path(&args.out_dir);
let resolved_fundamentals = resolve_normalized_path(&fundamentals_dir);
let mut resolved_inputs = vec![
(
"qm-financials",
&args.qm_financials,
resolve_normalized_path(&args.qm_financials),
),
(
"qm-filings",
&args.qm_filings,
resolve_normalized_path(&args.qm_filings),
),
(
"provider-mapping",
&args.provider_mapping,
resolve_normalized_path(&args.provider_mapping),
),
(
"listing-venues",
&args.listing_venues,
resolve_normalized_path(&args.listing_venues),
),
];
if let Some(old_path) = &args.qm_financials_old {
resolved_inputs.push((
"qm-financials-old",
old_path,
resolve_normalized_path(old_path),
));
}
for (label, input_path, resolved_in) in &resolved_inputs {
if *resolved_in == resolved_out
|| *resolved_in == resolved_fundamentals
|| resolved_in.starts_with(&resolved_fundamentals)
{
return Err(RunCurateFundamentalsError::InvalidOutDir {
path: args.out_dir.clone(),
detail: format!(
"output directory would overlap {label} input '{}'",
input_path.display()
),
});
}
}
// Check existing `year=YYYY` partition directories and their `part.parquet` targets for:
// 1. unresolvable / dangling `year=*` symlinks (whose target could be created mid-run and
// silently alias another year's partition),
// 2. two distinct `year=*` entries resolving to the same directory or `part.parquet` file
// (which would cause publishing one year to silently overwrite another year's data), and
// 3. aliases to any input path, catching symlinked year directories whose resolved targets
// live outside `<out_dir>/fundamentals_pit`.
if fundamentals_dir_exists {
let entries = fs::read_dir(&fundamentals_dir).map_err(|source| {
RunCurateFundamentalsError::InspectOutDir {
path: fundamentals_dir.clone(),
source,
}
})?;
let mut year_dirs: Vec<PathBuf> = Vec::new();
for entry_res in entries {
let entry = entry_res.map_err(|source| RunCurateFundamentalsError::InspectOutDir {
path: fundamentals_dir.clone(),
source,
})?;
let name = entry.file_name();
if name.to_string_lossy().starts_with("year=") {
year_dirs.push(entry.path());
}
}
year_dirs.sort();
let mut seen_year_dirs: BTreeMap<PathBuf, PathBuf> = BTreeMap::new();
let mut seen_part_files: BTreeMap<PathBuf, PathBuf> = BTreeMap::new();
for year_dir in year_dirs {
let entry_meta = fs::symlink_metadata(&year_dir).map_err(|source| {
RunCurateFundamentalsError::InspectOutDir {
path: year_dir.clone(),
source,
}
})?;
let resolved_year_dir = if entry_meta.file_type().is_symlink() {
fs::canonicalize(&year_dir).map_err(|err| {
RunCurateFundamentalsError::InvalidOutDir {
path: year_dir.clone(),
detail: format!("partition symlink target cannot be resolved: {err}"),
}
})?
} else {
resolve_normalized_path(&year_dir)
};
let resolved_part_via_dir = resolved_year_dir.join("part.parquet");
let resolved_part = resolve_normalized_path(&year_dir.join("part.parquet"));
if let Some(prev_year_dir) =
seen_year_dirs.insert(resolved_year_dir.clone(), year_dir.clone())
{
return Err(RunCurateFundamentalsError::InvalidOutDir {
path: year_dir,
detail: format!(
"partition directory aliases '{}' via shared target '{}'",
prev_year_dir.display(),
resolved_year_dir.display()
),
});
}
if let Some(prev_year_dir) =
seen_part_files.insert(resolved_part.clone(), year_dir.clone())
{
return Err(RunCurateFundamentalsError::InvalidOutDir {
path: year_dir,
detail: format!(
"partition file aliases '{}' via shared target '{}'",
prev_year_dir.display(),
resolved_part.display()
),
});
}
for (label, input_path, resolved_in) in &resolved_inputs {
if *resolved_in == resolved_year_dir
|| *resolved_in == resolved_part_via_dir
|| *resolved_in == resolved_part
|| resolved_in.starts_with(&resolved_year_dir)
{
return Err(RunCurateFundamentalsError::InvalidOutDir {
path: year_dir,
detail: format!(
"partition output '{}' would overlap {label} input '{}'",
resolved_part_via_dir.display(),
input_path.display()
),
});
}
}
}
}
Ok(())
}
fn financials_bson_error_offset(err: &BsonQmFinancialsError) -> u64 {
match err {
BsonQmFinancialsError::TruncatedDocument { offset, .. }
| BsonQmFinancialsError::CorruptDocumentLength { offset, .. }
| BsonQmFinancialsError::CorruptBson { offset, .. } => *offset,
BsonQmFinancialsError::InvalidFieldNames { .. }
| BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. } => 0,
}
}
fn filings_bson_error_offset(err: &BsonQmEventsError) -> u64 {
match err {
BsonQmEventsError::TruncatedDocument { offset, .. }
| BsonQmEventsError::CorruptDocumentLength { offset, .. }
| BsonQmEventsError::CorruptBson { offset, .. } => *offset,
BsonQmEventsError::InvalidFieldNames { .. } => 0,
}
}
fn map_financials_stream_error(
label: &'static str,
path: &Path,
err: BsonQmFinancialsStreamError,
) -> RunCurateFundamentalsError {
match err {
BsonQmFinancialsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream {
label,
path: path.to_path_buf(),
source,
},
BsonQmFinancialsStreamError::Decode(source) => match &source {
BsonQmFinancialsError::InvalidFieldNames { .. }
| BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. } => {
RunCurateFundamentalsError::InvalidFinancialsConfig {
path: path.to_path_buf(),
source,
}
}
_ => {
let offset = financials_bson_error_offset(&source);
RunCurateFundamentalsError::CorruptFinancialsBson {
path: path.to_path_buf(),
offset,
source,
}
}
},
}
}
fn map_filings_stream_error(
path: &Path,
err: BsonQmEventsStreamError,
) -> RunCurateFundamentalsError {
match err {
BsonQmEventsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream {
label: "qm-filings",
path: path.to_path_buf(),
source,
},
BsonQmEventsStreamError::Decode(source) => match &source {
BsonQmEventsError::InvalidFieldNames { .. } => {
RunCurateFundamentalsError::InvalidFilingsFieldNames {
path: path.to_path_buf(),
source,
}
}
_ => {
let offset = filings_bson_error_offset(&source);
RunCurateFundamentalsError::CorruptFilingsBson {
path: path.to_path_buf(),
offset,
source,
}
}
},
}
}
#[inline]
fn intern_key(interner: &mut HashSet<Arc<str>>, key: &str) -> Arc<str> {
if let Some(existing) = interner.get(key) {
Arc::clone(existing)
} else {
let arc: Arc<str> = Arc::from(key);
interner.insert(Arc::clone(&arc));
arc
}
}
struct DecodedFundamentalsInputs {
mapping: ProviderMappingTable,
venues: BTreeMap<i32, StatutoryLagVenue>,
observations: Vec<FinancialObservation<Arc<str>>>,
legacy_observations: Vec<FinancialObservation<Arc<str>>>,
filings: Vec<QmFiling<Arc<str>>>,
financials_docs_framed: u64,
financials_bytes_read: u64,
financials_peak_chunk_bytes: usize,
financials_decode: BsonQmFinancialsDecodeStats,
filings_docs_framed: u64,
filings_bytes_read: u64,
filings_peak_chunk_bytes: usize,
filings_decode: BsonQmFilingsDecodeStats,
}
fn decode_inputs_from_openers<RF, FF, RO, FO, RL, FL>(
args: &CurateFundamentalsArgs,
open_financials: FF,
open_financials_old: Option<(&Path, FO)>,
open_filings: FL,
) -> Result<DecodedFundamentalsInputs, RunCurateFundamentalsError>
where
RF: io::Read,
FF: FnOnce() -> Result<RF, RunCurateFundamentalsError>,
RO: io::Read,
FO: FnOnce() -> Result<RO, RunCurateFundamentalsError>,
RL: io::Read,
FL: FnOnce() -> Result<RL, RunCurateFundamentalsError>,
{
let financials_fields = args.financials_field_names();
financials_fields.validate().map_err(|source| {
RunCurateFundamentalsError::InvalidFinancialsConfig {
path: args.qm_financials.clone(),
source,
}
})?;
args.fiscal_period
.with_borrowed(|fp| fp.validate())
.map_err(|source| RunCurateFundamentalsError::InvalidFinancialsConfig {
path: args.qm_financials.clone(),
source,
})?;
let filings_fields = args.filings_field_names();
filings_fields.validate().map_err(|source| {
RunCurateFundamentalsError::InvalidFilingsFieldNames {
path: args.qm_filings.clone(),
source,
}
})?;
if args.mapping_source.trim().is_empty() {
return Err(RunCurateFundamentalsError::EmptyMappingSource);
}
if args.k == 0 {
return Err(RunCurateFundamentalsError::InvalidPeriodLimit { k: args.k });
}
let mapping_rows = load_provider_mapping_tsv(&args.provider_mapping)
.map_err(|err| map_tsv_error(&args.provider_mapping, err))?;
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
RunCurateFundamentalsError::ProviderMapping {
path: args.provider_mapping.clone(),
source,
}
})?;
let venues = load_listing_venues_tsv(&args.listing_venues)?;
let mut key_interner: HashSet<Arc<str>> = HashSet::new();
// Stream and decode qmFinancials, releasing the chunk reader immediately afterward.
let (
observations,
mut financials_docs_framed,
mut financials_bytes_read,
mut financials_peak_chunk_bytes,
mut financials_decode,
) = {
let financials_stream = open_financials()?;
let mut financials_reader =
RawBsonChunkReader::with_options(financials_stream, BsonStreamOptions::default())
.map_err(|source| RunCurateFundamentalsError::BsonStream {
label: "qm-financials",
path: args.qm_financials.clone(),
source,
})?;
let mut observations: Vec<FinancialObservation<Arc<str>>> = Vec::new();
let decode = args.fiscal_period.with_borrowed(|fp| {
decode_qm_financials_chunks(&mut financials_reader, &financials_fields, fp, |obs| {
let key = intern_key(&mut key_interner, obs.key);
observations.push(FinancialObservation {
key,
period_end: obs.period_end,
fiscal_period: obs.fiscal_period,
currency: obs.currency,
report_date: obs.report_date,
fields: obs.fields,
});
})
})
.map_err(|err| map_financials_stream_error("qm-financials", &args.qm_financials, err))?;
(
observations,
financials_reader.docs_framed(),
financials_reader.bytes_read(),
financials_reader.buffer_capacity(),
decode,
)
};
// Optionally stream and decode legacy qmFinancials-old, accumulating framing & decode stats.
let mut legacy_observations: Vec<FinancialObservation<Arc<str>>> = Vec::new();
if let Some((old_path, open_old)) = open_financials_old {
let old_stream = open_old()?;
let mut old_reader =
RawBsonChunkReader::with_options(old_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateFundamentalsError::BsonStream {
label: "qm-financials-old",
path: old_path.to_path_buf(),
source,
},
)?;
let old_decode = args
.fiscal_period
.with_borrowed(|fp| {
decode_qm_financials_chunks(&mut old_reader, &financials_fields, fp, |obs| {
let key = intern_key(&mut key_interner, obs.key);
legacy_observations.push(FinancialObservation {
key,
period_end: obs.period_end,
fiscal_period: obs.fiscal_period,
currency: obs.currency,
report_date: obs.report_date,
fields: obs.fields,
});
})
})
.map_err(|err| map_financials_stream_error("qm-financials-old", old_path, err))?;
financials_docs_framed += old_reader.docs_framed();
financials_bytes_read += old_reader.bytes_read();
financials_peak_chunk_bytes = financials_peak_chunk_bytes.max(old_reader.buffer_capacity());
financials_decode.merge(&old_decode);
}
// Stream and decode qmFilings, reusing the same key interner and releasing the chunk reader.
let (filings, filings_docs_framed, filings_bytes_read, filings_peak_chunk_bytes, filings_decode) = {
let filings_stream = open_filings()?;
let mut filings_reader =
RawBsonChunkReader::with_options(filings_stream, BsonStreamOptions::default())
.map_err(|source| RunCurateFundamentalsError::BsonStream {
label: "qm-filings",
path: args.qm_filings.clone(),
source,
})?;
let mut filings: Vec<QmFiling<Arc<str>>> = Vec::new();
let decode = decode_qm_filings_chunks(&mut filings_reader, &filings_fields, |raw| {
let key = intern_key(&mut key_interner, raw.key);
filings.push(raw.to_qm_filing(key));
})
.map_err(|err| map_filings_stream_error(&args.qm_filings, err))?;
(
filings,
filings_reader.docs_framed(),
filings_reader.bytes_read(),
filings_reader.buffer_capacity(),
decode,
)
};
Ok(DecodedFundamentalsInputs {
mapping,
venues,
observations,
legacy_observations,
filings,
financials_docs_framed,
financials_bytes_read,
financials_peak_chunk_bytes,
financials_decode,
filings_docs_framed,
filings_bytes_read,
filings_peak_chunk_bytes,
filings_decode,
})
}
fn run_curate_fundamentals_from_openers<RF, FF, RO, FO, RL, FL>(
args: &CurateFundamentalsArgs,
open_financials: FF,
open_financials_old: Option<(&Path, FO)>,
open_filings: FL,
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError>
where
RF: io::Read,
FF: FnOnce() -> Result<RF, RunCurateFundamentalsError>,
RO: io::Read,
FO: FnOnce() -> Result<RO, RunCurateFundamentalsError>,
RL: io::Read,
FL: FnOnce() -> Result<RL, RunCurateFundamentalsError>,
{
let start = Instant::now();
validate_out_dir_and_inputs(args)?;
let decoded = decode_inputs_from_openers(args, open_financials, open_financials_old, open_filings)?;
let write_report = curate_and_write_fundamentals_with_legacy(
&args.out_dir,
decoded.observations,
decoded.legacy_observations,
decoded.filings,
&args.mapping_source,
&decoded.mapping,
&decoded.venues,
args.k,
FundamentalsPitWriteOptions::default(),
)
.map_err(|source| RunCurateFundamentalsError::CurateWrite {
out_dir: args.out_dir.clone(),
source,
})?;
Ok(CurateFundamentalsRunReport {
financials_docs_framed: decoded.financials_docs_framed,
financials_bytes_read: decoded.financials_bytes_read,
financials_peak_chunk_bytes: decoded.financials_peak_chunk_bytes,
financials_decode: decoded.financials_decode,
filings_docs_framed: decoded.filings_docs_framed,
filings_bytes_read: decoded.filings_bytes_read,
filings_peak_chunk_bytes: decoded.filings_peak_chunk_bytes,
filings_decode: decoded.filings_decode,
curate_stats: write_report.curate_stats,
write_stats: write_report.write_stats,
elapsed_secs: start.elapsed().as_secs_f64(),
})
}
/// Runs the end-to-end `curate-fundamentals` file-to-Parquet pipeline via
/// [`curate_and_write_fundamentals_with_legacy`].
///
/// Any validation, path-alias, I/O, TSV, mapping, BSON framing/corruption, or curation error
/// returns before touching `args.out_dir`, leaving any pre-existing
/// `<out_dir>/fundamentals_pit/` partitions byte-identical.
pub fn run_curate_fundamentals(
args: &CurateFundamentalsArgs,
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError> {
let open_old = args.qm_financials_old.as_deref().map(|old_path| {
let opener = move || {
File::open(old_path).map_err(|source| RunCurateFundamentalsError::OpenInput {
label: "qm-financials-old",
path: old_path.to_path_buf(),
source,
})
};
(old_path, opener)
});
run_curate_fundamentals_from_openers(
args,
|| {
File::open(&args.qm_financials).map_err(|source| {
RunCurateFundamentalsError::OpenInput {
label: "qm-financials",
path: args.qm_financials.clone(),
source,
}
})
},
open_old,
|| {
File::open(&args.qm_filings).map_err(|source| RunCurateFundamentalsError::OpenInput {
label: "qm-filings",
path: args.qm_filings.clone(),
source,
})
},
)
}
/// Runs `curate-fundamentals` from arbitrary raw-BSON [`io::Read`] streams while still running
/// full preflight validation (including output/input path safety against the diagnostic paths in
/// `args`) and loading `provider_mapping.tsv` / `listing_venues.tsv` from disk.
pub fn run_curate_fundamentals_with_readers<RF: io::Read, RL: io::Read>(
args: &CurateFundamentalsArgs,
financials_reader: RF,
filings_reader: RL,
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError> {
run_curate_fundamentals_with_optional_old_readers(
args,
financials_reader,
None::<io::Empty>,
filings_reader,
)
}
/// Runs `curate-fundamentals` from arbitrary raw-BSON [`io::Read`] streams with an optional
/// legacy `qmFinancials-old` stream, running full preflight validation and loading
/// `provider_mapping.tsv` / `listing_venues.tsv` from disk.
pub fn run_curate_fundamentals_with_optional_old_readers<RF: io::Read, RO: io::Read, RL: io::Read>(
args: &CurateFundamentalsArgs,
financials_reader: RF,
financials_old_reader: Option<RO>,
filings_reader: RL,
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError> {
let fallback_old_path = Path::new("qmFinancials-old");
let old_path = args
.qm_financials_old
.as_deref()
.unwrap_or(fallback_old_path);
let open_old = financials_old_reader.map(|r| (old_path, move || Ok(r)));
run_curate_fundamentals_from_openers(
args,
|| Ok(financials_reader),
open_old,
|| Ok(filings_reader),
)
}
/// Formats [`CurateFundamentalsRunReport`] into a deterministic machine-readable `key=value`
/// summary.
///
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
pub fn format_curate_fundamentals_report(report: &CurateFundamentalsRunReport) -> String {
let fin = &report.financials_decode;
let fil = &report.filings_decode;
let b = &report.curate_stats.build;
let c = &report.curate_stats;
let w = &report.write_stats;
let mut years = String::new();
for (idx, (year, count)) in w.rows_by_year.iter().enumerate() {
if idx > 0 {
years.push(' ');
}
let _ = write!(years, "{year:04}={count}");
}
if years.is_empty() {
years.push_str("none");
}
format!(
"curate-etl curate-fundamentals\n\
\x20 financials_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_period_end={} wrong_period_end_type={} invalid_period_end={} period_end_oor={} missing_report_period={} wrong_report_period_type={} unmapped_report_period={} wrong_report_date_type={} invalid_report_date={} report_date_oor={} missing_currency={} wrong_currency_type={} empty_currency={}) nulled=(missing_path={} wrong_type={} unparsable_string={} non_finite={})\n\
\x20 filings_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_timefiled={} wrong_timefiled_type={} empty_timefiled={} missing_form_type={} wrong_form_type_type={} empty_form_type={}) nulled_wrong_type=(filing_id={} url={})\n\
\x20 builder: observations_in={} rows_out={} keys_out={} linked={} statutory_lag={} dropped=(unknown_key={} non_finite={} date_oor={} report_date_not_after_period_end={} unanchored_vintage={} stale_estimate={}) dup_collapsed={} dup_conflict={} filings_in={} filings_eligible={} filings_dropped=(unknown_key={} non_periodic={} invalid_ts={} date_oor={} before_period_end={})\n\
\x20 curate: observations_in={} obs_unmapped={} filings_in={} filings_unmapped={} filings_invalid_ts={} rows_out={} listings_out={}\n\
\x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\
\x20 years: {}\n\
\x20 timing: elapsed_secs={:.6}",
report.financials_docs_framed,
report.financials_bytes_read,
report.financials_peak_chunk_bytes,
fin.docs_in,
fin.rows_out,
fin.skipped_total(),
fin.skipped_missing_key,
fin.skipped_wrong_key_type,
fin.skipped_empty_key,
fin.skipped_missing_period_end,
fin.skipped_wrong_period_end_type,
fin.skipped_invalid_period_end,
fin.skipped_period_end_out_of_range,
fin.skipped_missing_report_period,
fin.skipped_wrong_report_period_type,
fin.skipped_unmapped_report_period,
fin.skipped_wrong_report_date_type,
fin.skipped_invalid_report_date,
fin.skipped_report_date_out_of_range,
fin.skipped_missing_currency,
fin.skipped_wrong_currency_type,
fin.skipped_empty_currency,
fin.nulled_missing_path,
fin.nulled_wrong_type,
fin.nulled_unparsable_string,
fin.nulled_non_finite,
report.filings_docs_framed,
report.filings_bytes_read,
report.filings_peak_chunk_bytes,
fil.docs_in,
fil.rows_out,
fil.skipped_total(),
fil.skipped_missing_key,
fil.skipped_wrong_key_type,
fil.skipped_empty_key,
fil.skipped_missing_timefiled,
fil.skipped_wrong_timefiled_type,
fil.skipped_empty_timefiled,
fil.skipped_missing_form_type,
fil.skipped_wrong_form_type_type,
fil.skipped_empty_form_type,
fil.nulled_wrong_type_filing_id,
fil.nulled_wrong_type_url,
b.observations_in,
b.rows_out,
b.keys_out,
b.rows_linked_to_filing,
b.rows_statutory_lag_estimate,
b.observations_dropped_unknown_key,
b.observations_dropped_non_finite,
b.observations_dropped_date_out_of_range,
b.observations_dropped_report_date_not_after_period_end,
b.observations_dropped_unanchored_vintage,
b.observations_dropped_stale_estimate,
b.duplicate_collapsed,
b.duplicate_conflict_dropped,
b.filings_in,
b.filings_eligible,
b.filings_dropped_unknown_key,
b.filings_ignored_non_periodic,
b.filings_dropped_invalid_timestamp,
b.filings_dropped_date_out_of_range,
b.filings_dropped_before_period_end,
c.observations_in,
c.observations_dropped_unmapped,
c.filings_in,
c.filings_dropped_unmapped,
c.filings_dropped_invalid_timestamp,
c.rows_out,
c.listings_out,
w.files_written,
w.row_groups_written,
w.rows_written,
w.bytes_written,
years,
report.elapsed_secs,
)
}
#[cfg(test)]
#[path = "run_curate_fundamentals_tests.rs"]
mod tests;