T-171: M2.2m — tools/curate-etl: file-to-file fundamentals_pit runner (decode_qm_financials_chunks in bson_stream.rs + run_curate_fundamentals.rs: raw qmFinancials + qmFilings BSON dumps + provider_mapping.tsv + listing-venue TSV → curate_and_write_fundamentals → fundamentals_pit Zstd Parquet) with tests (no new crates, no CLI/bench changes, no live Mongo)

This commit is contained in:
Studio 2026-12-02 14:15:48 -05:00
parent 74ac9dce8d
commit 1409805206
2 changed files with 335 additions and 45 deletions

View file

@ -255,9 +255,11 @@ pub enum RunCurateFundamentalsError {
source: io::Error,
},
InvalidFinancialsConfig {
path: PathBuf,
source: BsonQmFinancialsError,
},
InvalidFilingsFieldNames {
path: PathBuf,
source: BsonQmEventsError,
},
EmptyMappingSource,
@ -345,8 +347,20 @@ impl fmt::Display for RunCurateFundamentalsError {
path.display()
)
}
Self::InvalidFinancialsConfig { source } => write!(w, "{source}"),
Self::InvalidFilingsFieldNames { source } => write!(w, "{source}"),
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")
}
@ -403,8 +417,8 @@ 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::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),
@ -642,9 +656,11 @@ fn validate_out_dir_and_inputs(
}
}
// Check existing `year=YYYY` partition directories and their `part.parquet` targets for
// aliases to any input path, catching symlinked year directories whose resolved targets live
// outside `<out_dir>/fundamentals_pit`.
// Check existing `year=YYYY` partition directories and their `part.parquet` targets for:
// 1. 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
// 2. 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 {
@ -652,20 +668,53 @@ fn validate_out_dir_and_inputs(
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=") {
continue;
if name.to_string_lossy().starts_with("year=") {
year_dirs.push(entry.path());
}
let year_dir = 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 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"));
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
@ -720,7 +769,10 @@ fn map_financials_stream_error(
BsonQmFinancialsStreamError::Decode(source) => match &source {
BsonQmFinancialsError::InvalidFieldNames { .. }
| BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. } => {
RunCurateFundamentalsError::InvalidFinancialsConfig { source }
RunCurateFundamentalsError::InvalidFinancialsConfig {
path: path.to_path_buf(),
source,
}
}
_ => {
let offset = financials_bson_error_offset(&source);
@ -746,7 +798,10 @@ fn map_filings_stream_error(
},
BsonQmEventsStreamError::Decode(source) => match &source {
BsonQmEventsError::InvalidFieldNames { .. } => {
RunCurateFundamentalsError::InvalidFilingsFieldNames { source }
RunCurateFundamentalsError::InvalidFilingsFieldNames {
path: path.to_path_buf(),
source,
}
}
_ => {
let offset = filings_bson_error_offset(&source);
@ -798,18 +853,27 @@ where
FL: FnOnce() -> Result<RL, RunCurateFundamentalsError>,
{
let financials_fields = args.financials_field_names();
financials_fields
.validate()
.map_err(|source| RunCurateFundamentalsError::InvalidFinancialsConfig { source })?;
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 { source })?;
.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 { source })?;
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);

View file

@ -862,6 +862,39 @@ fn fundamentals_late_q1_restatement_preserves_q2() {
fs::write(&map_path, "qm\tACME\t2020-01-01\t\t301\n").unwrap();
fs::write(&venues_path, "301\tus_tsx\n").unwrap();
// Four contiguous quarters ending in Q2 2024 so Q2 and the late Q1 amendment both carry
// a 4-quarter TTM sum; the Q1 revenue revision (-12.0) must show up in TTM revenue first
// at the amendment timestamp while leaving all earlier rows and Q2's latest fields intact.
let q3_2023 = make_financials_doc(
Some("ACME"),
"2023-09-30",
Some("2023-11-05"),
"Q3",
"USD",
FundamentalsFields {
revenue: Some(90.0),
net_income: Some(8.0),
operating_cash_flow: Some(10.0),
total_assets: Some(460.0),
total_equity: Some(275.0),
shares_outstanding: Some(20.0),
},
);
let q4_2023 = make_financials_doc(
Some("ACME"),
"2023-12-31",
Some("2024-02-20"),
"Q4",
"USD",
FundamentalsFields {
revenue: Some(110.0),
net_income: Some(11.0),
operating_cash_flow: Some(14.0),
total_assets: Some(480.0),
total_equity: Some(288.0),
shares_outstanding: Some(20.0),
},
);
let q1_orig = make_financials_doc(
Some("ACME"),
"2024-03-31",
@ -908,6 +941,20 @@ fn fundamentals_late_q1_restatement_preserves_q2() {
},
);
let f_q3_2023 = make_filing_doc(
Some("ACME"),
"2023-11-05T16:10:00 EST",
"10-Q",
Some("q3-2023-1"),
None,
);
let f_q4_2023 = make_filing_doc(
Some("ACME"),
"2024-02-20T16:10:00 EST",
"10-Q",
Some("q4-2023-1"),
None,
);
let f_q1 = make_filing_doc(
Some("ACME"),
"2024-05-05T16:10:00 EDT",
@ -930,12 +977,20 @@ fn fundamentals_late_q1_restatement_preserves_q2() {
None,
);
// Run 1: Q1 + Q2 only.
// Run 1: Q3 2023 + Q4 2023 + Q1 2024 + Q2 2024 only.
let fin_before = tmp.path().join("fin_before.bson");
let fil_before = tmp.path().join("fil_before.bson");
let out_before = tmp.path().join("out_before");
fs::write(&fin_before, [&q1_orig[..], &q2_orig[..]].concat()).unwrap();
fs::write(&fil_before, [&f_q1[..], &f_q2[..]].concat()).unwrap();
fs::write(
&fin_before,
[&q3_2023[..], &q4_2023[..], &q1_orig[..], &q2_orig[..]].concat(),
)
.unwrap();
fs::write(
&fil_before,
[&f_q3_2023[..], &f_q4_2023[..], &f_q1[..], &f_q2[..]].concat(),
)
.unwrap();
let args_before = default_test_args(
fin_before,
fil_before,
@ -944,24 +999,39 @@ fn fundamentals_late_q1_restatement_preserves_q2() {
out_before.clone(),
);
let rep_before = run_curate_fundamentals(&args_before).unwrap();
assert_eq!(rep_before.write_stats.rows_written, 2);
let rows_before = read_dataset_by_year(&out_before)
.remove(&2024)
.expect("2024 partition");
assert_eq!(rows_before.len(), 2);
assert_eq!(rep_before.write_stats.rows_written, 4);
let by_year_before = read_dataset_by_year(&out_before);
let rows_2023_before = by_year_before.get(&2023).expect("2023 partition");
let rows_2024_before = by_year_before.get(&2024).expect("2024 partition");
assert_eq!(rows_2023_before.len(), 1);
assert_eq!(rows_2024_before.len(), 3);
// Run 2: Q1 + Q2 + late Q1 restatement (known_at > Q2's known_at).
// Run 2: same four quarters + late Q1 2024 restatement (known_at > Q2's known_at).
let fin_after = tmp.path().join("fin_after.bson");
let fil_after = tmp.path().join("fil_after.bson");
let out_after = tmp.path().join("out_after");
fs::write(
&fin_after,
[&q1_orig[..], &q2_orig[..], &q1_restated[..]].concat(),
[
&q3_2023[..],
&q4_2023[..],
&q1_orig[..],
&q2_orig[..],
&q1_restated[..],
]
.concat(),
)
.unwrap();
fs::write(
&fil_after,
[&f_q1[..], &f_q2[..], &f_q1_amend[..]].concat(),
[
&f_q3_2023[..],
&f_q4_2023[..],
&f_q1[..],
&f_q2[..],
&f_q1_amend[..],
]
.concat(),
)
.unwrap();
let args_after = default_test_args(
@ -972,19 +1042,22 @@ fn fundamentals_late_q1_restatement_preserves_q2() {
out_after.clone(),
);
let rep_after = run_curate_fundamentals(&args_after).unwrap();
assert_eq!(rep_after.write_stats.rows_written, 3);
let rows_after = read_dataset_by_year(&out_after)
.remove(&2024)
.expect("2024 partition");
assert_eq!(rows_after.len(), 3);
assert_eq!(rep_after.write_stats.rows_written, 5);
let by_year_after = read_dataset_by_year(&out_after);
let rows_2023_after = by_year_after.get(&2023).expect("2023 partition");
let rows_2024_after = by_year_after.get(&2024).expect("2024 partition");
assert_eq!(rows_2023_after.len(), 1);
assert_eq!(rows_2024_after.len(), 4);
// Entire pre-amendment prefix is byte/value-identical (zero look-ahead leakage).
assert_eq!(&rows_after[..2], &rows_before[..]);
// Entire pre-amendment prefix across both years is byte/value-identical (zero leakage).
assert_eq!(rows_2023_after, rows_2023_before);
assert_eq!(&rows_2024_after[..3], &rows_2024_before[..]);
// Third snapshot is at the amendment's UTC known_at (2024-09-15 17:00 EDT = 21:00 UTC),
// and Q2 remains the latest period (period_end, values, and period_known_at unchanged).
let amend_row = &rows_after[2];
let q2_row = &rows_before[1];
// Fourth 2024 snapshot is at the amendment's UTC known_at (2024-09-15 17:00 EDT = 21:00 UTC),
// Q2 remains the latest period (period_end, values, and period_known_at unchanged), and
// 4-quarter TTM revenue changes first at this snapshot by exactly the Q1 revision (-12.0).
let q2_row = &rows_2024_before[2];
let amend_row = &rows_2024_after[3];
let expected_amend_utc = et_to_utc_micros(day(2024, 9, 15), 17, 0, 0).unwrap();
assert_eq!(amend_row.effective_known_at, expected_amend_utc);
assert!(amend_row.effective_known_at > q2_row.effective_known_at);
@ -997,6 +1070,20 @@ fn fundamentals_late_q1_restatement_preserves_q2() {
assert_eq!(amend_row.total_assets, q2_row.total_assets);
assert_eq!(amend_row.total_equity, q2_row.total_equity);
assert_eq!(amend_row.shares_outstanding, q2_row.shares_outstanding);
// TTM assertions: 90 + 110 + 100 + 250 = 550 before amendment; 90 + 110 + 88 + 250 = 538 after.
assert_eq!(q2_row.ttm_period_end, Some(day(2024, 6, 30)));
assert_eq!(amend_row.ttm_period_end, Some(day(2024, 6, 30)));
assert_eq!(q2_row.ttm_revenue, Some(550.0));
assert_eq!(amend_row.ttm_revenue, Some(538.0));
assert_eq!(
amend_row.ttm_revenue.unwrap() - q2_row.ttm_revenue.unwrap(),
88.0 - 100.0
);
assert_eq!(q2_row.ttm_net_income, Some(59.0));
assert_eq!(amend_row.ttm_net_income, Some(53.0));
assert_eq!(q2_row.ttm_operating_cash_flow, Some(71.0));
assert_eq!(amend_row.ttm_operating_cash_flow, Some(68.0));
}
#[test]
@ -1307,8 +1394,10 @@ fn fundamentals_failures_preserve_output_tree() {
let err = run_curate_fundamentals(&a).unwrap_err();
assert!(matches!(
err,
RunCurateFundamentalsError::InvalidFinancialsConfig { .. }
RunCurateFundamentalsError::InvalidFinancialsConfig { ref path, .. }
if path == &valid_fin
));
assert!(err.to_string().contains(&valid_fin.display().to_string()));
assert_single_line(&err.to_string());
assert_preserved(out_dir, &before);
@ -1318,8 +1407,10 @@ fn fundamentals_failures_preserve_output_tree() {
let err = run_curate_fundamentals(&a).unwrap_err();
assert!(matches!(
err,
RunCurateFundamentalsError::InvalidFilingsFieldNames { .. }
RunCurateFundamentalsError::InvalidFilingsFieldNames { ref path, .. }
if path == &valid_fil
));
assert!(err.to_string().contains(&valid_fil.display().to_string()));
assert_single_line(&err.to_string());
assert_preserved(out_dir, &before);
@ -1332,8 +1423,10 @@ fn fundamentals_failures_preserve_output_tree() {
let err = run_curate_fundamentals(&a).unwrap_err();
assert!(matches!(
err,
RunCurateFundamentalsError::InvalidFinancialsConfig { .. }
RunCurateFundamentalsError::InvalidFinancialsConfig { ref path, .. }
if path == &valid_fin
));
assert!(err.to_string().contains(&valid_fin.display().to_string()));
assert_single_line(&err.to_string());
assert_preserved(out_dir, &before);
@ -1345,8 +1438,10 @@ fn fundamentals_failures_preserve_output_tree() {
let err = run_curate_fundamentals(&a).unwrap_err();
assert!(matches!(
err,
RunCurateFundamentalsError::InvalidFinancialsConfig { .. }
RunCurateFundamentalsError::InvalidFinancialsConfig { ref path, .. }
if path == &valid_fin
));
assert!(err.to_string().contains(&valid_fin.display().to_string()));
assert_single_line(&err.to_string());
assert_preserved(out_dir, &before);
@ -1854,6 +1949,137 @@ fn fundamentals_rejects_output_files_and_input_aliases() {
}
}
#[cfg(unix)]
#[test]
fn fundamentals_rejects_aliased_year_partitions() {
use std::os::unix::fs::symlink;
let tmp = TempDirGuard::new("aliased-years");
let map_path = tmp.path().join("map.tsv");
let venues_path = tmp.path().join("venues.tsv");
fs::write(&map_path, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap();
fs::write(&venues_path, "101\tus_tsx\n").unwrap();
// Seed a valid 2023 partition in a shared target directory.
let fin_2023 = tmp.path().join("fin_2023.bson");
let fil_2023 = tmp.path().join("fil_2023.bson");
fs::write(
&fin_2023,
make_financials_doc(
Some("NVDA"),
"2023-03-31",
Some("2023-05-01"),
"Q1",
"USD",
FundamentalsFields {
revenue: Some(80.0),
..Default::default()
},
),
)
.unwrap();
fs::write(
&fil_2023,
make_filing_doc(
Some("NVDA"),
"2023-05-01T16:10:00 EDT",
"10-Q",
Some("f2023"),
None,
),
)
.unwrap();
let seed_out = tmp.path().join("seed_out");
let seed_args = default_test_args(
fin_2023,
fil_2023,
map_path.clone(),
venues_path.clone(),
seed_out.clone(),
);
let seed_report = run_curate_fundamentals(&seed_args).expect("seed 2023 partition");
assert_eq!(seed_report.write_stats.rows_written, 1);
let shared_target = tmp.path().join("shared_archive");
fs::create_dir_all(&shared_target).unwrap();
let seeded_part = seed_out
.join("fundamentals_pit")
.join("year=2023")
.join("part.parquet");
let shared_part = shared_target.join("part.parquet");
fs::copy(&seeded_part, &shared_part).unwrap();
let shared_target_before = snapshot_tree(&shared_target);
let shared_part_bytes_before = fs::read(&shared_part).unwrap();
// Point both year=2023 and year=2024 at the same shared target directory.
let aliased_out = tmp.path().join("aliased_out");
let aliased_ds = aliased_out.join("fundamentals_pit");
fs::create_dir_all(&aliased_ds).unwrap();
symlink(&shared_target, aliased_ds.join("year=2023")).unwrap();
symlink(&shared_target, aliased_ds.join("year=2024")).unwrap();
let aliased_out_before = snapshot_tree(&aliased_out);
// Prepare a 2024-only rerun that would overwrite 2023's part.parquet if allowed.
let fin_2024 = tmp.path().join("fin_2024.bson");
let fil_2024 = tmp.path().join("fil_2024.bson");
let fin_2024_bytes = make_financials_doc(
Some("NVDA"),
"2024-03-31",
Some("2024-05-01"),
"Q1",
"USD",
FundamentalsFields {
revenue: Some(120.0),
..Default::default()
},
);
let fil_2024_bytes = make_filing_doc(
Some("NVDA"),
"2024-05-01T16:10:00 EDT",
"10-Q",
Some("f2024"),
None,
);
fs::write(&fin_2024, &fin_2024_bytes).unwrap();
fs::write(&fil_2024, &fil_2024_bytes).unwrap();
let rerun_args = default_test_args(
fin_2024.clone(),
fil_2024.clone(),
map_path.clone(),
venues_path.clone(),
aliased_out.clone(),
);
let err_file = run_curate_fundamentals(&rerun_args).unwrap_err();
assert!(matches!(
err_file,
RunCurateFundamentalsError::InvalidOutDir { .. }
));
let msg_file = err_file.to_string();
assert_single_line(&msg_file);
assert!(msg_file.contains("year=2024") && msg_file.contains("year=2023"));
assert_eq!(snapshot_tree(&aliased_out), aliased_out_before);
assert_eq!(snapshot_tree(&shared_target), shared_target_before);
assert_eq!(fs::read(&shared_part).unwrap(), shared_part_bytes_before);
let err_reader = run_curate_fundamentals_with_readers(
&rerun_args,
Cursor::new(fin_2024_bytes.as_slice()),
Cursor::new(fil_2024_bytes.as_slice()),
)
.unwrap_err();
assert!(matches!(
err_reader,
RunCurateFundamentalsError::InvalidOutDir { .. }
));
assert_single_line(&err_reader.to_string());
assert_eq!(snapshot_tree(&aliased_out), aliased_out_before);
assert_eq!(snapshot_tree(&shared_target), shared_target_before);
assert_eq!(fs::read(&shared_part).unwrap(), shared_part_bytes_before);
}
#[test]
fn fundamentals_empty_inputs_publish_nothing() {
let tmp = TempDirGuard::new("empty");