diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 1a1bda25..ba3e2c43 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1466,5 +1466,5 @@ Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs wi ```bash bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --collections qmFilings,qmEarnings --out ``` -- **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. On Canadian tickers (e.g. `SHOP` vs. `SHOP:CA`), pass `--filings-key-field` or `--earnings-key-field` so both collections share the same key namespace as `provider_mapping` for same-day earnings↔filing linking. +- **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the `provider_mapping` namespace (for example, the QuoteMedia security ID, not a bare ticker — the security master records distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` for the same symbol and exchange, so switching earnings to bare `symbol` can merge distinct identities or drop rows). If a live `qmFilings` export lacks that unambiguous key, prepare the export with verified QuoteMedia IDs and exclude unresolved rows rather than downgrading `qmEarnings` to bare tickers. - **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope. diff --git a/tools/curate-etl/src/bson_qm_events.rs b/tools/curate-etl/src/bson_qm_events.rs index bb2c2117..147a62ac 100644 --- a/tools/curate-etl/src/bson_qm_events.rs +++ b/tools/curate-etl/src/bson_qm_events.rs @@ -28,9 +28,12 @@ //! `apps/stock/data-pipeline/src/security-master/source-field-shapes.ts` //! (`probe-source-field-shapes.ts --collections qmFilings,qmEarnings`). //! - **Key-namespace alignment note:** `qmFilings` defaults to `symbol` while `qmEarnings` -//! defaults to `qmSearchCode`. On Canadian tickers (e.g. `SHOP` vs. `SHOP:CA`), operators must -//! pass `--filings-key-field` or `--earnings-key-field` as needed so both collections share the -//! same key namespace as `provider_mapping` for same-day earnings↔filing linking. +//! defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the +//! `provider_mapping` namespace (for example, the QuoteMedia security ID rather than a bare +//! ticker, since distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` can share the same +//! symbol and exchange). Where a `qmFilings` export lacks that unambiguous key, prepare the +//! export with verified IDs and exclude unresolved rows instead of switching `qmEarnings` to +//! bare tickers. //! - **Point-in-time safety (`consensusEps`):** `consensusEps` is structurally omitted from //! [`RawQmEarning`] and [`QmEarning`], never decoded from BSON, and explicitly rejected by //! [`QmEarningsFieldNames::validate`] if configured on any role. diff --git a/tools/curate-etl/src/run_curate_events.rs b/tools/curate-etl/src/run_curate_events.rs index 5512c70c..6f4833a6 100644 --- a/tools/curate-etl/src/run_curate_events.rs +++ b/tools/curate-etl/src/run_curate_events.rs @@ -252,9 +252,15 @@ impl Error for RunCurateEventsError { } } -/// Resolves `path` to an absolute normalized path by canonicalizing its deepest existing ancestor -/// (resolving symlinks) and lexically normalizing any remaining non-existent components. +/// 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() { @@ -263,39 +269,38 @@ fn resolve_normalized_path(path: &Path) -> PathBuf { path.to_path_buf() }; - // Lexically normalize `.` and `..` first so ancestor lookups walk real parents. - let mut lex = PathBuf::new(); + 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::ParentDir => { - if !lex.pop() { - lex.push(comp.as_os_str()); + 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(); + } } } - other => lex.push(other.as_os_str()), } } - // Walk upward until we find an existing ancestor that can be canonicalized. - let mut tail: Vec = Vec::new(); - let mut cur = lex.as_path(); - loop { - if let Ok(canon) = cur.canonicalize() { - let mut out = canon; - for seg in tail.into_iter().rev() { - out.push(seg); - } - return out; - } - match (cur.parent(), cur.file_name()) { - (Some(parent), Some(name)) => { - tail.push(name.to_os_string()); - cur = parent; - } - _ => return lex, - } - } + resolved } fn validate_out_dir_and_inputs(args: &CurateEventsArgs) -> Result<(), RunCurateEventsError> { diff --git a/tools/curate-etl/src/run_curate_events_tests.rs b/tools/curate-etl/src/run_curate_events_tests.rs index 84327cc7..f2421680 100644 --- a/tools/curate-etl/src/run_curate_events_tests.rs +++ b/tools/curate-etl/src/run_curate_events_tests.rs @@ -612,6 +612,72 @@ fn failure_modes_publish_nothing_and_preserve_sentinel() { assert_sentinel_untouched(); } +#[cfg(unix)] +#[test] +fn symlink_followed_by_parent_dir_into_events_output_is_rejected_without_modifying_input() { + use std::os::unix::fs::symlink; + + let tmp = TempDirGuard::new("symlink_parent_clobber"); + let dir = tmp.path(); + + fs::write( + dir.join("provider_mapping.tsv"), + "qm\tAAPL\t2020-01-01\t\t101\n", + ) + .unwrap(); + let valid_filing = rawdoc! { + "symbol": "AAPL", + "timefiled": "2025-02-10 16:30:00 EST", + "formType": "10-K", + }; + let filing_bytes = valid_filing.as_bytes().to_vec(); + let valid_earning = rawdoc! { + "qmSearchCode": "AAPL", + "reportDate": "2025-02-10", + "announceTime": "AMC", + }; + fs::write(dir.join("qmEarnings.bson"), valid_earning.as_bytes()).unwrap(); + + // Place the real input at `/events/year=2025/part.parquet` and expose it via + // `exports/latest/../part.parquet`, where `exports/latest` symlinks to + // `/events/year=2025/staging`. + let year_dir = dir.join("out/events/year=2025"); + let staging_dir = year_dir.join("staging"); + fs::create_dir_all(&staging_dir).unwrap(); + let real_input = year_dir.join("part.parquet"); + fs::write(&real_input, &filing_bytes).unwrap(); + + let exports_dir = dir.join("exports"); + fs::create_dir_all(&exports_dir).unwrap(); + let latest_link = exports_dir.join("latest"); + symlink(&staging_dir, &latest_link).unwrap(); + + let mut args = default_args(dir); + args.qm_filings = latest_link.join("../part.parquet"); + + let err = run_curate_events(&args).unwrap_err(); + assert!( + matches!(err, RunCurateEventsError::InvalidOutDir { .. }), + "expected InvalidOutDir for symlink+`..` input inside events/, got: {err:?}" + ); + assert!(!err.to_string().contains('\n')); + assert_eq!( + fs::read(&real_input).unwrap(), + filing_bytes, + "input file bytes must remain untouched" + ); + + // Also verify a non-existent file reached through the same symlink+`..` is rejected as + // InvalidOutDir before opening inputs. + args.qm_filings = latest_link.join("../future.parquet"); + let err = run_curate_events(&args).unwrap_err(); + assert!( + matches!(err, RunCurateEventsError::InvalidOutDir { .. }), + "expected InvalidOutDir for non-existent symlink+`..` path inside events/, got: {err:?}" + ); + assert_eq!(fs::read(&real_input).unwrap(), filing_bytes); +} + #[test] fn empty_inputs_return_ok_without_creating_events_dir() { let tmp = TempDirGuard::new("empty");