970 lines
35 KiB
Rust
970 lines
35 KiB
Rust
//! File-to-file `curate-events` command runner (`M1.2ae`).
|
|
//!
|
|
//! Streams concatenated raw BSON `qmFilings` and `qmEarnings` dump files alongside
|
|
//! `provider_mapping.tsv` into atomically published `<out_dir>/events/year=YYYY/part.parquet`
|
|
//! partitions via [`curate_events`] and [`write_events_dataset`].
|
|
//!
|
|
//! # Contract & Point-in-Time Rules
|
|
//! - Verified defaults match in-repo evidence (`symbol` / `timefiled` on `qmFilings`;
|
|
//! `qmSearchCode` / `reportDate` / `announceTime` on `qmEarnings`). Unverified fields
|
|
//! (`--filings-form-type-field`, plus optional `filing_id`, `url`, `fiscal_period_end`,
|
|
//! `actual_eps`, `revenue`) have no defaults and are validated up front before touching disk.
|
|
//! - `consensusEps` is structurally excluded from decoding and explicitly rejected by
|
|
//! [`QmEarningsFieldNames::validate`] on any earnings field flag.
|
|
//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from
|
|
//! [`crate::run_curate_bars::load_provider_mapping_tsv`].
|
|
//! - All decoded [`QmFiling`] and [`QmEarning`] rows are passed directly to
|
|
//! [`curate_events`], which links same-day `8-K` / `News release` filings to
|
|
//! earnings, falls back unlinked earnings to `16:05 ET`, resolves `provider_mapping` on each
|
|
//! event's exact Eastern local calendar date (never UTC or `known_at` date), and counts
|
|
//! unmapped keys in [`CurateEventsStats::dropped_unmapped`].
|
|
//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_events`] /
|
|
//! [`write_events_dataset`], returning `Ok` with `rows_written == 0` and `files_written == 0`
|
|
//! without creating `<out_dir>/events` or modifying any pre-existing partitions.
|
|
//! - **Fail-closed safety:** invalid `--out` (including `--out` or `<out>/events` being a regular
|
|
//! file, any input path resolving to `--out` or inside `<out>/events`, or a destination
|
|
//! `year=YYYY` partition directory symlink resolving a `part.parquet` output onto an input),
|
|
//! invalid field names, empty `--mapping-source`, unreadable inputs, malformed/overlapping
|
|
//! `provider_mapping.tsv`, and truncated/corrupt BSON framing or element bytes return a typed
|
|
//! [`RunCurateEventsError`] before touching `args.out_dir`.
|
|
//!
|
|
//! # Counter Conservation Invariants
|
|
//! Every successful [`CurateEventsRunReport`] satisfies:
|
|
//! - `filings_docs_framed as usize == filings_decode.docs_in == filings_decode.rows_out + filings_decode.skipped_total()`
|
|
//! - `earnings_docs_framed as usize == earnings_decode.docs_in == earnings_decode.rows_out + earnings_decode.skipped_total()`
|
|
//! - `filings_decode.rows_out == curate_stats.builder.filings_in`
|
|
//! - `earnings_decode.rows_out == curate_stats.builder.earnings_in`
|
|
//! - `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_duplicate_collapsed`
|
|
//! - `write_stats.rows_written == curate_stats.rows_out`
|
|
|
|
use std::collections::{BTreeSet, HashSet};
|
|
use std::error::Error;
|
|
use std::fmt::{self, Write as _};
|
|
use std::fs::File;
|
|
use std::io;
|
|
use std::path::{Component, Path, PathBuf};
|
|
use std::sync::Arc;
|
|
use std::time::Instant;
|
|
|
|
use crate::bson_qm_events::{
|
|
BsonQmEarningsDecodeStats, BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames,
|
|
QmFilingsFieldNames,
|
|
};
|
|
use crate::bson_stream::{
|
|
decode_qm_earnings_chunks, decode_qm_filings_chunks, BsonQmEventsStreamError, BsonStreamError,
|
|
BsonStreamOptions, RawBsonChunkReader,
|
|
};
|
|
use crate::curate_events::{curate_events, CurateEventsStats, CurateEventsWriteError};
|
|
use crate::events::{partition_year_utc, QmEarning, QmFiling};
|
|
use crate::parquet_events::{
|
|
write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats,
|
|
};
|
|
use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable};
|
|
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
|
|
|
|
/// Default `--mapping-source` passed to `provider_mapping` lookups for `qmFilings` / `qmEarnings`.
|
|
pub const DEFAULT_EVENTS_MAPPING_SOURCE: &str = "qm";
|
|
|
|
/// Parsed arguments for the `curate-events` CLI command.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct CurateEventsArgs {
|
|
pub qm_filings: PathBuf,
|
|
pub qm_earnings: PathBuf,
|
|
pub provider_mapping: PathBuf,
|
|
pub out_dir: PathBuf,
|
|
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 earnings_key_field: String,
|
|
pub earnings_report_date_field: String,
|
|
pub earnings_announce_time_field: String,
|
|
pub earnings_fiscal_period_end_field: Option<String>,
|
|
pub earnings_actual_eps_field: Option<String>,
|
|
pub earnings_revenue_field: Option<String>,
|
|
pub mapping_source: String,
|
|
}
|
|
|
|
impl CurateEventsArgs {
|
|
/// 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(),
|
|
}
|
|
}
|
|
|
|
/// Borrows the configured `qmEarnings` BSON field names as [`QmEarningsFieldNames`].
|
|
#[inline]
|
|
pub fn earnings_field_names(&self) -> QmEarningsFieldNames<'_> {
|
|
QmEarningsFieldNames {
|
|
key: self.earnings_key_field.as_str(),
|
|
report_date: self.earnings_report_date_field.as_str(),
|
|
announce_time: self.earnings_announce_time_field.as_str(),
|
|
fiscal_period_end: self.earnings_fiscal_period_end_field.as_deref(),
|
|
actual_eps: self.earnings_actual_eps_field.as_deref(),
|
|
revenue: self.earnings_revenue_field.as_deref(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Full run report produced by [`run_curate_events`].
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct CurateEventsRunReport {
|
|
pub filings_docs_framed: u64,
|
|
pub filings_bytes_read: u64,
|
|
pub filings_peak_chunk_bytes: usize,
|
|
pub filings_decode: BsonQmFilingsDecodeStats,
|
|
pub earnings_docs_framed: u64,
|
|
pub earnings_bytes_read: u64,
|
|
pub earnings_peak_chunk_bytes: usize,
|
|
pub earnings_decode: BsonQmEarningsDecodeStats,
|
|
pub curate_stats: CurateEventsStats,
|
|
pub write_stats: EventsWriteStats,
|
|
pub elapsed_secs: f64,
|
|
}
|
|
|
|
/// Stage-timed run output used internally by `bench-curate-events-cmd`.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub(crate) struct CurateEventsTimedRun {
|
|
pub report: CurateEventsRunReport,
|
|
pub decode_elapsed_secs: f64,
|
|
pub curate_elapsed_secs: f64,
|
|
pub write_elapsed_secs: f64,
|
|
pub checksum: u64,
|
|
}
|
|
|
|
/// Typed errors returned by [`run_curate_events`].
|
|
///
|
|
/// 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 RunCurateEventsError {
|
|
InvalidOutDir {
|
|
path: PathBuf,
|
|
detail: String,
|
|
},
|
|
InvalidFieldNames {
|
|
source: BsonQmEventsError,
|
|
},
|
|
EmptyMappingSource,
|
|
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,
|
|
},
|
|
CorruptBson {
|
|
label: &'static str,
|
|
path: PathBuf,
|
|
offset: u64,
|
|
source: BsonQmEventsError,
|
|
},
|
|
CurateWrite {
|
|
out_dir: PathBuf,
|
|
source: CurateEventsWriteError,
|
|
},
|
|
}
|
|
|
|
impl fmt::Display for RunCurateEventsError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::InvalidOutDir { path, detail } => {
|
|
write!(f, "invalid --out '{}': {detail}", path.display())
|
|
}
|
|
Self::InvalidFieldNames { source } => write!(f, "{source}"),
|
|
Self::EmptyMappingSource => {
|
|
write!(f, "invalid --mapping-source: must not be empty or blank")
|
|
}
|
|
Self::OpenInput {
|
|
label,
|
|
path,
|
|
source,
|
|
} => write!(f, "failed to open {label} '{}': {source}", path.display()),
|
|
Self::ReadInput {
|
|
label,
|
|
path,
|
|
source,
|
|
} => write!(f, "failed to read {label} '{}': {source}", path.display()),
|
|
Self::TsvParse { path, line, detail } => {
|
|
write!(f, "{}:{line}: {detail}", path.display())
|
|
}
|
|
Self::ProviderMapping { path, source } => {
|
|
write!(f, "invalid provider_mapping '{}': {source}", path.display())
|
|
}
|
|
Self::BsonStream {
|
|
label,
|
|
path,
|
|
source,
|
|
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
|
|
Self::CorruptBson {
|
|
label,
|
|
path,
|
|
offset,
|
|
source,
|
|
} => write!(
|
|
f,
|
|
"corrupt {label} BSON '{}' at byte offset {offset}: {source}",
|
|
path.display()
|
|
),
|
|
Self::CurateWrite { out_dir, source } => {
|
|
write!(f, "curate/write to '{}' failed: {source}", out_dir.display())
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Error for RunCurateEventsError {
|
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
match self {
|
|
Self::InvalidFieldNames { source } => Some(source),
|
|
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
|
|
Self::ProviderMapping { source, .. } => Some(source),
|
|
Self::BsonStream { source, .. } => Some(source),
|
|
Self::CorruptBson { source, .. } => Some(source),
|
|
Self::CurateWrite { source, .. } => Some(source),
|
|
Self::InvalidOutDir { .. } | Self::EmptyMappingSource | Self::TsvParse { .. } => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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 {
|
|
// Remove the `..` we just pushed, then lexically pop a non-existent normal segment.
|
|
resolved.pop();
|
|
if matches!(resolved.components().next_back(), Some(Component::Normal(_))) {
|
|
resolved.pop();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
resolved
|
|
}
|
|
|
|
fn validate_out_dir_and_inputs(args: &CurateEventsArgs) -> Result<(), RunCurateEventsError> {
|
|
if args.out_dir.exists() && !args.out_dir.is_dir() {
|
|
return Err(RunCurateEventsError::InvalidOutDir {
|
|
path: args.out_dir.clone(),
|
|
detail: "path exists and is not a directory".to_string(),
|
|
});
|
|
}
|
|
|
|
let events_dir = args.out_dir.join("events");
|
|
if events_dir.exists() && !events_dir.is_dir() {
|
|
return Err(RunCurateEventsError::InvalidOutDir {
|
|
path: events_dir,
|
|
detail: "events output path exists and is not a directory".to_string(),
|
|
});
|
|
}
|
|
|
|
let resolved_out = resolve_normalized_path(&args.out_dir);
|
|
let resolved_events = resolve_normalized_path(&events_dir);
|
|
|
|
for (label, input_path) in [
|
|
("qm-filings", &args.qm_filings),
|
|
("qm-earnings", &args.qm_earnings),
|
|
("provider-mapping", &args.provider_mapping),
|
|
] {
|
|
let resolved_in = resolve_normalized_path(input_path);
|
|
if resolved_in == resolved_out
|
|
|| resolved_in == resolved_events
|
|
|| resolved_in.starts_with(&resolved_events)
|
|
{
|
|
return Err(RunCurateEventsError::InvalidOutDir {
|
|
path: args.out_dir.clone(),
|
|
detail: format!(
|
|
"output directory would overlap {label} input '{}'",
|
|
input_path.display()
|
|
),
|
|
});
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Checks each destination `year=YYYY` partition directory and its `part.parquet` path against
|
|
/// all resolved input paths before publishing.
|
|
///
|
|
/// This catches symlinked year directories (e.g. `<out>/events/year=2025 -> /external/dir`)
|
|
/// whose resolved target lies outside `<out>/events` and would otherwise let `write_events_dataset`
|
|
/// overwrite an input located at `/external/dir/part.parquet`.
|
|
fn validate_partition_outputs_and_inputs(
|
|
args: &CurateEventsArgs,
|
|
rows: &[EventsParquetRow],
|
|
) -> Result<(), RunCurateEventsError> {
|
|
if rows.is_empty() {
|
|
return Ok(());
|
|
}
|
|
|
|
let mut years = BTreeSet::new();
|
|
for row in rows {
|
|
years.insert(partition_year_utc(row.ts_micros));
|
|
}
|
|
|
|
let resolved_inputs = [
|
|
("qm-filings", &args.qm_filings, resolve_normalized_path(&args.qm_filings)),
|
|
("qm-earnings", &args.qm_earnings, resolve_normalized_path(&args.qm_earnings)),
|
|
(
|
|
"provider-mapping",
|
|
&args.provider_mapping,
|
|
resolve_normalized_path(&args.provider_mapping),
|
|
),
|
|
];
|
|
|
|
let events_dir = args.out_dir.join("events");
|
|
for year in years {
|
|
let year_dir = events_dir.join(format!("year={year:04}"));
|
|
let resolved_year_dir = 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"));
|
|
|
|
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
|
|
{
|
|
return Err(RunCurateEventsError::InvalidOutDir {
|
|
path: year_dir,
|
|
detail: format!(
|
|
"partition output '{}' would overlap {label} input '{}'",
|
|
resolved_part_via_dir.display(),
|
|
input_path.display()
|
|
),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateEventsError {
|
|
match err {
|
|
RunCurateBarsError::OpenInput {
|
|
label,
|
|
path,
|
|
source,
|
|
} => RunCurateEventsError::OpenInput {
|
|
label,
|
|
path,
|
|
source,
|
|
},
|
|
RunCurateBarsError::ReadInput {
|
|
label,
|
|
path,
|
|
source,
|
|
} => RunCurateEventsError::ReadInput {
|
|
label,
|
|
path,
|
|
source,
|
|
},
|
|
RunCurateBarsError::TsvParse { path, line, detail } => {
|
|
RunCurateEventsError::TsvParse { path, line, detail }
|
|
}
|
|
RunCurateBarsError::ProviderMapping { path, source } => {
|
|
RunCurateEventsError::ProviderMapping { path, source }
|
|
}
|
|
other => RunCurateEventsError::TsvParse {
|
|
path: path.to_path_buf(),
|
|
line: 0,
|
|
detail: other.to_string(),
|
|
},
|
|
}
|
|
}
|
|
|
|
fn bson_error_offset(err: &BsonQmEventsError) -> u64 {
|
|
match err {
|
|
BsonQmEventsError::TruncatedDocument { offset, .. }
|
|
| BsonQmEventsError::CorruptDocumentLength { offset, .. }
|
|
| BsonQmEventsError::CorruptBson { offset, .. } => *offset,
|
|
BsonQmEventsError::InvalidFieldNames { .. } => 0,
|
|
}
|
|
}
|
|
|
|
fn map_stream_error(
|
|
label: &'static str,
|
|
path: &Path,
|
|
err: BsonQmEventsStreamError,
|
|
) -> RunCurateEventsError {
|
|
match err {
|
|
BsonQmEventsStreamError::Stream(source) => RunCurateEventsError::BsonStream {
|
|
label,
|
|
path: path.to_path_buf(),
|
|
source,
|
|
},
|
|
BsonQmEventsStreamError::Decode(source) => match &source {
|
|
BsonQmEventsError::InvalidFieldNames { .. } => {
|
|
RunCurateEventsError::InvalidFieldNames { source }
|
|
}
|
|
_ => {
|
|
let offset = bson_error_offset(&source);
|
|
RunCurateEventsError::CorruptBson {
|
|
label,
|
|
path: path.to_path_buf(),
|
|
offset,
|
|
source,
|
|
}
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn is_canadian_qm_exchange(exchange: &str) -> bool {
|
|
matches!(
|
|
exchange.trim().to_ascii_uppercase().as_str(),
|
|
"TSX"
|
|
| "TSXC"
|
|
| "CDX"
|
|
| "TSXVC"
|
|
| "CNQ"
|
|
| "CNX"
|
|
| "CSE"
|
|
| "CVE"
|
|
| "AQL"
|
|
| "AQLL"
|
|
| "NEO"
|
|
| "NEOE"
|
|
| "MOE"
|
|
)
|
|
}
|
|
|
|
#[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 DecodedEventsInputs {
|
|
mapping: ProviderMappingTable,
|
|
filings: Vec<QmFiling<Arc<str>>>,
|
|
earnings: Vec<QmEarning<Arc<str>>>,
|
|
filings_docs_framed: u64,
|
|
filings_bytes_read: u64,
|
|
filings_peak_chunk_bytes: usize,
|
|
filings_decode: BsonQmFilingsDecodeStats,
|
|
earnings_docs_framed: u64,
|
|
earnings_bytes_read: u64,
|
|
earnings_peak_chunk_bytes: usize,
|
|
earnings_decode: BsonQmEarningsDecodeStats,
|
|
}
|
|
|
|
fn decode_all_inputs(args: &CurateEventsArgs) -> Result<DecodedEventsInputs, RunCurateEventsError> {
|
|
decode_inputs_from_openers(
|
|
&args.provider_mapping,
|
|
&args.mapping_source,
|
|
&args.filings_field_names(),
|
|
&args.earnings_field_names(),
|
|
&args.qm_filings,
|
|
|| {
|
|
File::open(&args.qm_filings).map_err(|source| RunCurateEventsError::OpenInput {
|
|
label: "qm-filings",
|
|
path: args.qm_filings.clone(),
|
|
source,
|
|
})
|
|
},
|
|
&args.qm_earnings,
|
|
|| {
|
|
File::open(&args.qm_earnings).map_err(|source| RunCurateEventsError::OpenInput {
|
|
label: "qm-earnings",
|
|
path: args.qm_earnings.clone(),
|
|
source,
|
|
})
|
|
},
|
|
)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn decode_inputs_from_openers<RF, FF, RE, FE>(
|
|
provider_mapping_path: &Path,
|
|
mapping_source: &str,
|
|
filings_fields: &QmFilingsFieldNames<'_>,
|
|
earnings_fields: &QmEarningsFieldNames<'_>,
|
|
qm_filings_path: &Path,
|
|
open_filings: FF,
|
|
qm_earnings_path: &Path,
|
|
open_earnings: FE,
|
|
) -> Result<DecodedEventsInputs, RunCurateEventsError>
|
|
where
|
|
RF: io::Read,
|
|
FF: FnOnce() -> Result<RF, RunCurateEventsError>,
|
|
RE: io::Read,
|
|
FE: FnOnce() -> Result<RE, RunCurateEventsError>,
|
|
{
|
|
filings_fields
|
|
.validate()
|
|
.map_err(|source| RunCurateEventsError::InvalidFieldNames { source })?;
|
|
|
|
earnings_fields
|
|
.validate()
|
|
.map_err(|source| RunCurateEventsError::InvalidFieldNames { source })?;
|
|
|
|
if mapping_source.trim().is_empty() {
|
|
return Err(RunCurateEventsError::EmptyMappingSource);
|
|
}
|
|
|
|
let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)
|
|
.map_err(|err| map_tsv_error(provider_mapping_path, err))?;
|
|
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
|
RunCurateEventsError::ProviderMapping {
|
|
path: provider_mapping_path.to_path_buf(),
|
|
source,
|
|
}
|
|
})?;
|
|
|
|
let mut key_interner: HashSet<Arc<str>> = HashSet::new();
|
|
|
|
// Stream and decode qmFilings.
|
|
let filings_stream = open_filings()?;
|
|
let mut filings_reader =
|
|
RawBsonChunkReader::with_options(filings_stream, BsonStreamOptions::default()).map_err(
|
|
|source| RunCurateEventsError::BsonStream {
|
|
label: "qm-filings",
|
|
path: qm_filings_path.to_path_buf(),
|
|
source,
|
|
},
|
|
)?;
|
|
|
|
let mut filings: Vec<QmFiling<Arc<str>>> = Vec::new();
|
|
let mut ca_key_buf = String::with_capacity(32);
|
|
let filings_decode =
|
|
decode_qm_filings_chunks(&mut filings_reader, filings_fields, |raw| {
|
|
let resolved_key_str = if !raw.key.contains(':')
|
|
&& raw.exchange.is_some_and(is_canadian_qm_exchange)
|
|
{
|
|
ca_key_buf.clear();
|
|
ca_key_buf.push_str(raw.key);
|
|
ca_key_buf.push_str(":CA");
|
|
if !mapping
|
|
.cursor_for(mapping_source, ca_key_buf.as_str())
|
|
.ranges()
|
|
.is_empty()
|
|
{
|
|
ca_key_buf.as_str()
|
|
} else {
|
|
raw.key
|
|
}
|
|
} else {
|
|
raw.key
|
|
};
|
|
let key = intern_key(&mut key_interner, resolved_key_str);
|
|
filings.push(raw.to_qm_filing(key));
|
|
})
|
|
.map_err(|err| map_stream_error("qm-filings", qm_filings_path, err))?;
|
|
|
|
// Stream and decode qmEarnings (reusing the same key interner).
|
|
let earnings_stream = open_earnings()?;
|
|
let mut earnings_reader =
|
|
RawBsonChunkReader::with_options(earnings_stream, BsonStreamOptions::default()).map_err(
|
|
|source| RunCurateEventsError::BsonStream {
|
|
label: "qm-earnings",
|
|
path: qm_earnings_path.to_path_buf(),
|
|
source,
|
|
},
|
|
)?;
|
|
|
|
let mut earnings: Vec<QmEarning<Arc<str>>> = Vec::new();
|
|
let earnings_decode =
|
|
decode_qm_earnings_chunks(&mut earnings_reader, earnings_fields, |raw| {
|
|
let key = intern_key(&mut key_interner, raw.key);
|
|
earnings.push(raw.to_qm_earning(key));
|
|
})
|
|
.map_err(|err| map_stream_error("qm-earnings", qm_earnings_path, err))?;
|
|
|
|
Ok(DecodedEventsInputs {
|
|
mapping,
|
|
filings,
|
|
earnings,
|
|
filings_docs_framed: filings_reader.docs_framed(),
|
|
filings_bytes_read: filings_reader.bytes_read(),
|
|
filings_peak_chunk_bytes: filings_reader.buffer_capacity(),
|
|
filings_decode,
|
|
earnings_docs_framed: earnings_reader.docs_framed(),
|
|
earnings_bytes_read: earnings_reader.bytes_read(),
|
|
earnings_peak_chunk_bytes: earnings_reader.buffer_capacity(),
|
|
earnings_decode,
|
|
})
|
|
}
|
|
|
|
/// Runs the end-to-end `curate-events` file-to-Parquet pipeline via [`curate_events`] and
|
|
/// [`write_events_dataset`].
|
|
///
|
|
/// Any validation, I/O, TSV, mapping, BSON framing/corruption, or curation error returns before
|
|
/// touching `args.out_dir`, leaving any pre-existing `<out_dir>/events/` partitions
|
|
/// byte-identical.
|
|
pub fn run_curate_events(
|
|
args: &CurateEventsArgs,
|
|
) -> Result<CurateEventsRunReport, RunCurateEventsError> {
|
|
let start = Instant::now();
|
|
validate_out_dir_and_inputs(args)?;
|
|
|
|
let decoded = decode_all_inputs(args)?;
|
|
|
|
let curated = curate_events(
|
|
decoded.filings,
|
|
decoded.earnings,
|
|
&args.mapping_source,
|
|
&decoded.mapping,
|
|
)
|
|
.map_err(|source| RunCurateEventsError::CurateWrite {
|
|
out_dir: args.out_dir.clone(),
|
|
source: CurateEventsWriteError::Curate(source),
|
|
})?;
|
|
|
|
validate_partition_outputs_and_inputs(args, &curated.rows)?;
|
|
|
|
let write_stats =
|
|
write_events_dataset(&args.out_dir, &curated.rows, EventsWriteOptions::default()).map_err(
|
|
|source| RunCurateEventsError::CurateWrite {
|
|
out_dir: args.out_dir.clone(),
|
|
source: CurateEventsWriteError::Parquet(source),
|
|
},
|
|
)?;
|
|
|
|
Ok(CurateEventsRunReport {
|
|
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,
|
|
earnings_docs_framed: decoded.earnings_docs_framed,
|
|
earnings_bytes_read: decoded.earnings_bytes_read,
|
|
earnings_peak_chunk_bytes: decoded.earnings_peak_chunk_bytes,
|
|
earnings_decode: decoded.earnings_decode,
|
|
curate_stats: curated.stats,
|
|
write_stats,
|
|
elapsed_secs: start.elapsed().as_secs_f64(),
|
|
})
|
|
}
|
|
|
|
/// Runs `curate-events` from arbitrary raw-BSON [`io::Read`] streams.
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn run_curate_events_with_readers<RF: io::Read, RE: io::Read>(
|
|
provider_mapping_path: &Path,
|
|
mapping_source: &str,
|
|
filings_fields: &QmFilingsFieldNames<'_>,
|
|
earnings_fields: &QmEarningsFieldNames<'_>,
|
|
qm_filings_input: (&Path, RF),
|
|
qm_earnings_input: (&Path, RE),
|
|
out_dir: &Path,
|
|
) -> Result<CurateEventsRunReport, RunCurateEventsError> {
|
|
let start = Instant::now();
|
|
if out_dir.exists() && !out_dir.is_dir() {
|
|
return Err(RunCurateEventsError::InvalidOutDir {
|
|
path: out_dir.to_path_buf(),
|
|
detail: "path exists and is not a directory".to_string(),
|
|
});
|
|
}
|
|
let events_dir = out_dir.join("events");
|
|
if events_dir.exists() && !events_dir.is_dir() {
|
|
return Err(RunCurateEventsError::InvalidOutDir {
|
|
path: events_dir,
|
|
detail: "events output path exists and is not a directory".to_string(),
|
|
});
|
|
}
|
|
|
|
let (filings_path, filings_stream) = qm_filings_input;
|
|
let (earnings_path, earnings_stream) = qm_earnings_input;
|
|
let decoded = decode_inputs_from_openers(
|
|
provider_mapping_path,
|
|
mapping_source,
|
|
filings_fields,
|
|
earnings_fields,
|
|
filings_path,
|
|
|| Ok(filings_stream),
|
|
earnings_path,
|
|
|| Ok(earnings_stream),
|
|
)?;
|
|
|
|
let curated = curate_events(
|
|
decoded.filings,
|
|
decoded.earnings,
|
|
mapping_source,
|
|
&decoded.mapping,
|
|
)
|
|
.map_err(|source| RunCurateEventsError::CurateWrite {
|
|
out_dir: out_dir.to_path_buf(),
|
|
source: CurateEventsWriteError::Curate(source),
|
|
})?;
|
|
|
|
let write_stats =
|
|
write_events_dataset(out_dir, &curated.rows, EventsWriteOptions::default()).map_err(
|
|
|source| RunCurateEventsError::CurateWrite {
|
|
out_dir: out_dir.to_path_buf(),
|
|
source: CurateEventsWriteError::Parquet(source),
|
|
},
|
|
)?;
|
|
|
|
Ok(CurateEventsRunReport {
|
|
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,
|
|
earnings_docs_framed: decoded.earnings_docs_framed,
|
|
earnings_bytes_read: decoded.earnings_bytes_read,
|
|
earnings_peak_chunk_bytes: decoded.earnings_peak_chunk_bytes,
|
|
earnings_decode: decoded.earnings_decode,
|
|
curate_stats: curated.stats,
|
|
write_stats,
|
|
elapsed_secs: start.elapsed().as_secs_f64(),
|
|
})
|
|
}
|
|
|
|
fn compute_rows_checksum(rows: &[EventsParquetRow]) -> u64 {
|
|
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
|
|
let mix = |mut h: u64, v: u64| -> u64 {
|
|
h ^= v;
|
|
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
|
h
|
|
};
|
|
let mix_str = |mut h: u64, s: &str| -> u64 {
|
|
h = mix(h, s.len() as u64);
|
|
for &b in s.as_bytes() {
|
|
h = mix(h, u64::from(b));
|
|
}
|
|
h
|
|
};
|
|
for row in rows {
|
|
hash = mix(hash, row.listing_id as u64);
|
|
hash = mix(hash, row.ts_micros as u64);
|
|
hash = mix(hash, row.known_at_micros as u64);
|
|
hash = mix_str(hash, row.known_at_source.as_ref());
|
|
hash = mix_str(hash, row.kind.as_ref());
|
|
hash = mix_str(hash, &row.subtype);
|
|
hash = mix_str(hash, &row.payload_json);
|
|
}
|
|
hash
|
|
}
|
|
|
|
/// Stage-timed variant of [`run_curate_events`] used internally by `bench-curate-events-cmd`.
|
|
///
|
|
/// Separately times `decode` (TSV load + both BSON streams), `curate` (`curate_events`), and
|
|
/// `write` (`write_events_dataset`), and computes a deterministic FNV-1a checksum over all 7
|
|
/// columns of the curated rows.
|
|
pub(crate) fn run_curate_events_timed(
|
|
args: &CurateEventsArgs,
|
|
) -> Result<CurateEventsTimedRun, RunCurateEventsError> {
|
|
let total_start = Instant::now();
|
|
validate_out_dir_and_inputs(args)?;
|
|
|
|
let decode_start = Instant::now();
|
|
let decoded = decode_all_inputs(args)?;
|
|
let decode_elapsed_secs = decode_start.elapsed().as_secs_f64();
|
|
|
|
let curate_start = Instant::now();
|
|
let curated = curate_events(
|
|
decoded.filings,
|
|
decoded.earnings,
|
|
&args.mapping_source,
|
|
&decoded.mapping,
|
|
)
|
|
.map_err(|source| RunCurateEventsError::CurateWrite {
|
|
out_dir: args.out_dir.clone(),
|
|
source: CurateEventsWriteError::Curate(source),
|
|
})?;
|
|
let curate_elapsed_secs = curate_start.elapsed().as_secs_f64();
|
|
|
|
validate_partition_outputs_and_inputs(args, &curated.rows)?;
|
|
|
|
let checksum = compute_rows_checksum(&curated.rows);
|
|
|
|
let write_start = Instant::now();
|
|
let write_stats =
|
|
write_events_dataset(&args.out_dir, &curated.rows, EventsWriteOptions::default()).map_err(
|
|
|source| RunCurateEventsError::CurateWrite {
|
|
out_dir: args.out_dir.clone(),
|
|
source: CurateEventsWriteError::Parquet(source),
|
|
},
|
|
)?;
|
|
let write_elapsed_secs = write_start.elapsed().as_secs_f64();
|
|
|
|
let report = CurateEventsRunReport {
|
|
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,
|
|
earnings_docs_framed: decoded.earnings_docs_framed,
|
|
earnings_bytes_read: decoded.earnings_bytes_read,
|
|
earnings_peak_chunk_bytes: decoded.earnings_peak_chunk_bytes,
|
|
earnings_decode: decoded.earnings_decode,
|
|
curate_stats: curated.stats,
|
|
write_stats,
|
|
elapsed_secs: total_start.elapsed().as_secs_f64(),
|
|
};
|
|
|
|
Ok(CurateEventsTimedRun {
|
|
report,
|
|
decode_elapsed_secs,
|
|
curate_elapsed_secs,
|
|
write_elapsed_secs,
|
|
checksum,
|
|
})
|
|
}
|
|
|
|
/// Formats [`CurateEventsRunReport`] into a deterministic machine-readable `key=value` summary.
|
|
///
|
|
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
|
pub fn format_curate_events_report(report: &CurateEventsRunReport) -> String {
|
|
let fd = &report.filings_decode;
|
|
let ed = &report.earnings_decode;
|
|
let b = &report.curate_stats.builder;
|
|
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-events\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 earnings_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_date={} wrong_date_type={} invalid_date={} date_oor={} missing_announce={} wrong_announce_type={} empty_announce={}) nulled=(wrong_fiscal_end={} invalid_fiscal_end={} wrong_eps={} wrong_revenue={})\n\
|
|
\x20 builder: filings_in={} filings_out={} malformed_ts={} unknown_zone={} invalid_dt={} filing_dup={} earnings_in={} earnings_out={} linked={} lagged_1605={} earnings_oor={} earnings_dup={} earnings_conflict={} rows_out={} keys_out={}\n\
|
|
\x20 curate: rows_in={} rows_out={} filings_out={} earnings_out={} listings_out={} dropped_unmapped={} listing_dup_collapsed={}\n\
|
|
\x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\
|
|
\x20 years: {}\n\
|
|
\x20 timing: elapsed_secs={:.6}",
|
|
report.filings_docs_framed,
|
|
report.filings_bytes_read,
|
|
report.filings_peak_chunk_bytes,
|
|
fd.docs_in,
|
|
fd.rows_out,
|
|
fd.skipped_total(),
|
|
fd.skipped_missing_key,
|
|
fd.skipped_wrong_key_type,
|
|
fd.skipped_empty_key,
|
|
fd.skipped_missing_timefiled,
|
|
fd.skipped_wrong_timefiled_type,
|
|
fd.skipped_empty_timefiled,
|
|
fd.skipped_missing_form_type,
|
|
fd.skipped_wrong_form_type_type,
|
|
fd.skipped_empty_form_type,
|
|
fd.nulled_wrong_type_filing_id,
|
|
fd.nulled_wrong_type_url,
|
|
report.earnings_docs_framed,
|
|
report.earnings_bytes_read,
|
|
report.earnings_peak_chunk_bytes,
|
|
ed.docs_in,
|
|
ed.rows_out,
|
|
ed.skipped_total(),
|
|
ed.skipped_missing_key,
|
|
ed.skipped_wrong_key_type,
|
|
ed.skipped_empty_key,
|
|
ed.skipped_missing_report_date,
|
|
ed.skipped_wrong_report_date_type,
|
|
ed.skipped_invalid_report_date,
|
|
ed.skipped_report_date_out_of_range,
|
|
ed.skipped_missing_announce_time,
|
|
ed.skipped_wrong_announce_time_type,
|
|
ed.skipped_empty_announce_time,
|
|
ed.nulled_wrong_type_fiscal_period_end,
|
|
ed.nulled_invalid_fiscal_period_end,
|
|
ed.nulled_wrong_type_actual_eps,
|
|
ed.nulled_wrong_type_revenue,
|
|
b.filings_in,
|
|
b.filings_out,
|
|
b.filings_skipped_malformed_timestamp,
|
|
b.filings_skipped_unknown_zone,
|
|
b.filings_skipped_invalid_date_time,
|
|
b.filings_duplicate_collapsed,
|
|
b.earnings_in,
|
|
b.earnings_out,
|
|
b.earnings_linked_to_filing,
|
|
b.earnings_lagged_1605,
|
|
b.earnings_skipped_out_of_range,
|
|
b.earnings_duplicate_collapsed,
|
|
b.earnings_duplicate_conflict_dropped,
|
|
b.rows_out,
|
|
b.keys_out,
|
|
c.rows_in,
|
|
c.rows_out,
|
|
c.filings_out,
|
|
c.earnings_out,
|
|
c.listings_out,
|
|
c.dropped_unmapped,
|
|
c.listing_duplicate_collapsed,
|
|
w.files_written,
|
|
w.row_groups_written,
|
|
w.rows_written,
|
|
w.bytes_written,
|
|
years,
|
|
report.elapsed_secs,
|
|
)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "run_curate_events_tests.rs"]
|
|
mod tests;
|