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

1823 lines
69 KiB
Rust

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf};
use bson::{Bson, DateTime};
use parquet::column::reader::ColumnReader;
use parquet::file::reader::{FileReader, SerializedFileReader};
use super::{
bars_1m_read_specs, fundamentals_read_specs, fx_1m_read_spec, macro_read_spec, posts_read_spec,
qm_bars_1m_read_spec, run_curate_bars_1m_mongo, run_curate_bars_1m_mongo_with_readers,
run_curate_fundamentals_mongo, run_curate_fundamentals_mongo_with_readers,
run_curate_fx_1m_mongo, run_curate_fx_1m_mongo_with_reader, run_curate_macro_mongo,
run_curate_macro_mongo_with_reader, run_curate_posts_mongo,
run_curate_posts_mongo_with_reader, run_curate_qm_bars_1m_mongo,
run_curate_qm_bars_1m_mongo_with_reader, unique_mapping_keys_for_source, CurateBars1mMongoArgs,
CurateFundamentalsMongoArgs, CurateFx1mMongoArgs, CurateMacroMongoArgs, CuratePostsMongoArgs,
CurateQmBars1mMongoArgs, RunMongoCurateError,
};
use crate::bson_ceo_posts::{
CeoPostsTimestampUnit, DEFAULT_BOT_FIELD, DEFAULT_EDITED_FIELD, DEFAULT_KEY_FIELD,
DEFAULT_SPIEL_ID_FIELD, DEFAULT_TEXT_FIELD, DEFAULT_TIMESTAMP_FIELD, DEFAULT_USER_ID_FIELD,
};
use crate::bson_qm_events::{DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD};
use crate::bson_qm_financials::{
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::BsonStreamOptions;
use crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP;
use crate::fundamentals::FiscalPeriod;
use crate::ilp::{IlpWriterOptions, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M};
use crate::mongo_stream::{
build_filter_document, MongoCliOptions, MongoStreamError, MongoUriSource, RawBsonCursorReader,
SliceRawDocumentSource, SourceCollection, VecRawDocumentSource,
};
use crate::run_curate_bars_1m::{
run_curate_bars_1m, CurateBars1mArgs, DEFAULT_BARS_1M_MAPPING_SOURCE,
};
use crate::run_curate_fundamentals::{
run_curate_fundamentals, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod,
DEFAULT_FUNDAMENTALS_MAPPING_SOURCE,
};
use crate::run_curate_fx_1m::{run_curate_fx_1m, CurateFx1mArgs};
use crate::run_curate_macro::{run_curate_macro, CurateMacroArgs, MACRO_SERIES_MAP_HEADER};
use crate::run_curate_posts::{
run_curate_posts, CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE,
};
use crate::run_curate_qm_bars_1m::{
run_curate_qm_bars_1m, CurateQmBars1mArgs, DEFAULT_QM_BARS_1M_MAPPING_SOURCE,
};
use crate::shorts::et_to_utc_micros;
use crate::split::ymd_to_epoch_days;
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
struct TempDirGuard {
path: PathBuf,
}
impl TempDirGuard {
fn new(label: &str) -> Self {
let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"curate-etl-run-mongo-test-{label}-{}-{seq}",
std::process::id()
));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create temp test dir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempDirGuard {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
struct CappedRead<R> {
inner: R,
max_step: usize,
}
impl<R> CappedRead<R> {
fn new(inner: R, max_step: usize) -> Self {
Self { inner, max_step }
}
}
impl<R: Read> Read for CappedRead<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let cap = buf.len().min(self.max_step);
self.inner.read(&mut buf[..cap])
}
}
fn concat_docs(docs: &[Vec<u8>]) -> Vec<u8> {
let mut out = Vec::new();
for d in docs {
out.extend_from_slice(d);
}
out
}
fn snapshot_files(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<PathBuf, Vec<u8>>) {
if !dir.exists() {
return;
}
for entry in fs::read_dir(dir).expect("read_dir") {
let entry = entry.expect("dir entry");
let path = entry.path();
if path.is_dir() {
walk(base, &path, out);
} else {
let rel = path.strip_prefix(base).expect("strip_prefix").to_path_buf();
out.insert(rel, fs::read(&path).expect("read file"));
}
}
}
let mut out = BTreeMap::new();
walk(root, root, &mut out);
out
}
fn make_fin_doc(
key: &str,
period_end: &str,
report_date: &str,
report_period: &str,
rev: f64,
) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), key);
doc.append(cstr!("periodEndDate"), period_end);
doc.append(cstr!("reportDate"), report_date);
doc.append(cstr!("reportPeriod"), report_period);
doc.append(cstr!("currency"), "USD");
doc.append(cstr!("revenue"), rev);
doc.into_bytes()
}
fn make_filing_doc(key: &str, timefiled: &str, form_type: &str) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), key);
doc.append(cstr!("timefiled"), timefiled);
doc.append(cstr!("formType"), form_type);
doc.into_bytes()
}
#[test]
fn parity_curate_fundamentals_mongo_cursor_matches_file_mode_with_and_without_old() {
let tmp = TempDirGuard::new("parity-fundamentals");
let map_path = tmp.path().join("provider_mapping.tsv");
let ven_path = tmp.path().join("listing_venues.tsv");
fs::write(&map_path, "qm\tACME:US\t2020-01-01\t\t101\n").unwrap();
fs::write(&ven_path, "101\tus_tsx\n").unwrap();
let fin_docs = vec![
make_fin_doc("ACME:US", "2024-06-30", "2024-08-05", "Q2", 130.0),
make_fin_doc("ACME:US", "2024-03-31", "2024-09-10", "Q1", 125.0),
];
let old_docs = vec![
make_fin_doc("ACME:US", "2023-09-30", "2023-11-05", "Q3", 100.0),
make_fin_doc("ACME:US", "2023-12-31", "2024-02-20", "Q4", 110.0),
make_fin_doc("ACME:US", "2024-03-31", "2024-05-05", "Q1", 120.0),
];
let fil_docs = vec![
make_filing_doc("ACME:US", "2023-11-05T16:30:00 EST", "10-Q"),
make_filing_doc("ACME:US", "2024-02-20T16:30:00 EST", "10-Q"),
make_filing_doc("ACME:US", "2024-05-05T16:30:00 EDT", "10-Q"),
make_filing_doc("ACME:US", "2024-08-05T16:30:00 EDT", "10-Q"),
make_filing_doc("ACME:US", "2024-09-10T16:30:00 EDT", "10-Q/A"),
];
let fin_path = tmp.path().join("qmFinancials.bson");
let old_path = tmp.path().join("qmFinancials-old.bson");
let fil_path = tmp.path().join("qmFilings.bson");
fs::write(&fin_path, concat_docs(&fin_docs)).unwrap();
fs::write(&old_path, concat_docs(&old_docs)).unwrap();
fs::write(&fil_path, concat_docs(&fil_docs)).unwrap();
for with_old in [false, true] {
let out_file = tmp.path().join(format!("out_file_{with_old}"));
let out_mongo = tmp.path().join(format!("out_mongo_{with_old}"));
let mut file_args = CurateFundamentalsArgs::with_verified_defaults(
fin_path.clone(),
fil_path.clone(),
map_path.clone(),
ven_path.clone(),
out_file.clone(),
"currency",
Some("revenue".to_string()),
None,
None,
None,
None,
None,
CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly),
"formType",
4,
);
if with_old {
file_args.qm_financials_old = Some(old_path.clone());
}
let file_rep = run_curate_fundamentals(&file_args).expect("file-mode fundamentals");
let mongo_args = CurateFundamentalsMongoArgs {
mongo: MongoCliOptions::default(),
with_qm_financials_old: with_old,
provider_mapping: map_path.clone(),
listing_venues: ven_path.clone(),
out_dir: out_mongo.clone(),
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: "currency".to_string(),
financials_revenue_field: Some("revenue".to_string()),
financials_net_income_field: None,
financials_operating_cash_flow_field: None,
financials_total_assets_field: None,
financials_total_equity_field: None,
financials_shares_outstanding_field: None,
fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly),
filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(),
filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(),
filings_form_type_field: "formType".to_string(),
filings_filing_id_field: None,
filings_url_field: None,
mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(),
k: 4,
};
let fin_slices: Vec<&[u8]> = fin_docs.iter().map(Vec::as_slice).collect();
let fin_reader = CappedRead::new(
RawBsonCursorReader::new(SliceRawDocumentSource::new(&fin_slices)),
7,
);
let old_reader = with_old.then(|| {
CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(old_docs.clone())),
13,
)
});
let fil_reader = CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(fil_docs.clone())),
11,
);
let mongo_rep = run_curate_fundamentals_mongo_with_readers(
&mongo_args,
fin_reader,
old_reader,
fil_reader,
)
.expect("mongo-cursor fundamentals");
assert_eq!(mongo_rep.curate_stats, file_rep.curate_stats);
assert_eq!(mongo_rep.write_stats, file_rep.write_stats);
assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file));
}
}
#[test]
fn parity_curate_posts_mongo_cursor_matches_file_mode_byte_for_byte() {
let tmp = TempDirGuard::new("parity-posts");
let map_path = tmp.path().join("provider_mapping.tsv");
fs::write(&map_path, "ceo\t5001\t2020-01-01\t\t202\n").unwrap();
let mut d1 = RawDocumentBuf::new();
d1.append(cstr!("ceoId"), "5001");
d1.append(cstr!("spielId"), "p1");
d1.append(cstr!("timestamp"), 1_710_000_000_i64);
d1.append(cstr!("edited"), 1_710_003_600_i64);
d1.append(cstr!("bot"), "0");
d1.append(cstr!("userId"), "u1");
d1.append(cstr!("spiel"), "edited post body");
let mut d2 = RawDocumentBuf::new();
d2.append(cstr!("ceoId"), "5001");
d2.append(cstr!("spielId"), "p2");
d2.append(cstr!("timestamp"), 1_710_010_000_i64);
d2.append(cstr!("edited"), false);
d2.append(cstr!("bot"), "1");
d2.append(cstr!("userId"), "bot");
d2.append(cstr!("spiel"), "newswire release");
let docs = vec![d1.into_bytes(), d2.into_bytes()];
let bson_path = tmp.path().join("ceoPosts.bson");
fs::write(&bson_path, concat_docs(&docs)).unwrap();
let out_file = tmp.path().join("out_file");
let out_mongo = tmp.path().join("out_mongo");
let file_rep = run_curate_posts(&CuratePostsArgs {
ceo_posts: bson_path,
provider_mapping: map_path.clone(),
out_dir: out_file.clone(),
timestamp_unit: CeoPostsTimestampUnit::Seconds,
key_field: DEFAULT_KEY_FIELD.to_string(),
spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(),
timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(),
edited_field: DEFAULT_EDITED_FIELD.to_string(),
bot_field: DEFAULT_BOT_FIELD.to_string(),
user_id_field: DEFAULT_USER_ID_FIELD.to_string(),
text_field: DEFAULT_TEXT_FIELD.to_string(),
mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(),
})
.expect("file-mode posts");
let mongo_args = CuratePostsMongoArgs {
mongo: MongoCliOptions::default(),
provider_mapping: map_path,
out_dir: out_mongo.clone(),
timestamp_unit: CeoPostsTimestampUnit::Seconds,
key_field: DEFAULT_KEY_FIELD.to_string(),
spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(),
timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(),
edited_field: DEFAULT_EDITED_FIELD.to_string(),
bot_field: DEFAULT_BOT_FIELD.to_string(),
user_id_field: DEFAULT_USER_ID_FIELD.to_string(),
text_field: DEFAULT_TEXT_FIELD.to_string(),
mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(),
};
let reader = CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(docs)),
5,
);
let mongo_rep = run_curate_posts_mongo_with_reader(&mongo_args, reader).expect("mongo posts");
assert_eq!(mongo_rep.curate_stats, file_rep.curate_stats);
assert_eq!(mongo_rep.write_stats, file_rep.write_stats);
assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file));
}
#[test]
fn parity_curate_macro_mongo_cursor_matches_file_mode_byte_for_byte() {
let tmp = TempDirGuard::new("parity-macro");
let map_path = tmp.path().join("series_map.tsv");
fs::write(
&map_path,
format!(
"{MACRO_SERIES_MAP_HEADER}\nUS_CPI\tUnited States\tInflation Rate\tUS\tcpi_yoy\tmonthly_release\n"
),
)
.unwrap();
let mut pt = RawDocumentBuf::new();
pt.append(cstr!("d"), "2024-01-31");
pt.append(cstr!("v"), 3.1_f64);
let mut data_arr = RawArrayBuf::new();
data_arr.push(pt);
let mut fpt = RawDocumentBuf::new();
fpt.append(cstr!("d"), "2025-01-31");
fpt.append(cstr!("v"), 9.9_f64);
let mut forecast_arr = RawArrayBuf::new();
forecast_arr.push(fpt);
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("teSymbol"), "US_CPI");
doc.append(cstr!("country"), "United States");
doc.append(cstr!("category"), "Inflation Rate");
doc.append(cstr!("data"), data_arr);
doc.append(cstr!("forecast"), forecast_arr);
let docs = vec![doc.into_bytes()];
let bson_path = tmp.path().join("teData.bson");
fs::write(&bson_path, concat_docs(&docs)).unwrap();
let out_file = tmp.path().join("out_file");
let out_mongo = tmp.path().join("out_mongo");
let file_rep = run_curate_macro(&CurateMacroArgs {
te_data: bson_path,
series_map: map_path.clone(),
out_dir: out_file.clone(),
})
.expect("file-mode macro");
let mongo_args = CurateMacroMongoArgs {
mongo: MongoCliOptions::default(),
series_map: map_path,
out_dir: out_mongo.clone(),
};
let reader = CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(docs)),
7,
);
let mongo_rep = run_curate_macro_mongo_with_reader(&mongo_args, reader).expect("mongo macro");
assert_eq!(mongo_rep, file_rep);
assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file));
}
#[test]
fn parity_curate_1m_ilp_mongo_cursors_match_file_mode_byte_for_byte() {
let tmp = TempDirGuard::new("parity-1m-ilp");
let map_path = tmp.path().join("provider_mapping.tsv");
fs::write(
&map_path,
"eod\tNVDA.US\t2020-01-01\t\t301\nqm\tNVDA:US\t2020-01-01\t\t301\n",
)
.unwrap();
// qmSplits: 10:1 forward split on 2024-06-10 (QuoteMedia stores splitratio = old / new = 0.1)
let mut sp = RawDocumentBuf::new();
sp.append(cstr!("qmSearchCode"), "NVDA:US");
sp.append(cstr!("date"), "2024-06-10");
sp.append(cstr!("forfactor"), 1.0_f64);
sp.append(cstr!("tofactor"), 10.0_f64);
sp.append(cstr!("splitratio"), 0.1_f64);
let split_docs = vec![sp.into_bytes()];
// eodIntraday1M: equity bar + CAD.FOREX bar
let mut b_eq = RawDocumentBuf::new();
b_eq.append(cstr!("eodSearchCode"), "NVDA.US");
b_eq.append(cstr!("timestamp"), 1_717_767_000_i64); // 2024-06-07 13:30:00Z (09:30 ET)
b_eq.append(cstr!("open"), 120.0_f64);
b_eq.append(cstr!("high"), 121.0_f64);
b_eq.append(cstr!("low"), 119.0_f64);
b_eq.append(cstr!("close"), 120.5_f64);
b_eq.append(cstr!("volume"), 1000.0_f64);
let mut b_fx = RawDocumentBuf::new();
b_fx.append(cstr!("eodSearchCode"), "CAD.FOREX");
b_fx.append(cstr!("timestamp"), 1_717_767_000_i64);
b_fx.append(cstr!("open"), 1.3700_f64);
b_fx.append(cstr!("high"), 1.3710_f64);
b_fx.append(cstr!("low"), 1.3690_f64);
b_fx.append(cstr!("close"), 1.3705_f64);
b_fx.append(cstr!("volume"), 0.0_f64);
let eod_1m_docs = vec![b_eq.into_bytes(), b_fx.into_bytes()];
// qmIntraday: raw bar
let mut b_qm = RawDocumentBuf::new();
b_qm.append(cstr!("qmSearchCode"), "NVDA:US");
b_qm.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000));
b_qm.append(cstr!("open"), 1200.0_f64);
b_qm.append(cstr!("high"), 1210.0_f64);
b_qm.append(cstr!("low"), 1190.0_f64);
b_qm.append(cstr!("close"), 1205.0_f64);
b_qm.append(cstr!("sharevolume"), 100.0_f64);
let qm_1m_docs = vec![b_qm.into_bytes()];
let splits_path = tmp.path().join("qmSplits.bson");
let eod_path = tmp.path().join("eodIntraday1M.bson");
let qm_path = tmp.path().join("qmIntraday.bson");
fs::write(&splits_path, concat_docs(&split_docs)).unwrap();
fs::write(&eod_path, concat_docs(&eod_1m_docs)).unwrap();
fs::write(&qm_path, concat_docs(&qm_1m_docs)).unwrap();
// Shared output dirs prove bars_1m, bars_1m_qm, and fx_1m co-exist in one --out dir.
let out_file = tmp.path().join("out_file");
let out_mongo = tmp.path().join("out_mongo");
let known_at = 1_750_000_000_000_000_i64;
// 1. curate-bars-1m
let file_b1m = run_curate_bars_1m(&CurateBars1mArgs {
intraday_path: eod_path.clone(),
splits_path,
provider_mapping_path: map_path.clone(),
out_dir: out_file.clone(),
mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: known_at,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
})
.expect("file bars_1m");
let mongo_b1m = run_curate_bars_1m_mongo_with_readers(
&CurateBars1mMongoArgs {
mongo: MongoCliOptions::default(),
provider_mapping_path: map_path.clone(),
out_dir: out_mongo.clone(),
mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: known_at,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
},
CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(eod_1m_docs.clone())),
9,
),
CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(split_docs)),
5,
),
)
.expect("mongo bars_1m");
assert_eq!(mongo_b1m.curate_stats, file_b1m.curate_stats);
assert_eq!(mongo_b1m.ilp_stats, file_b1m.ilp_stats);
// 2. curate-qm-bars-1m in the same --out dir
let file_qm1m = run_curate_qm_bars_1m(&CurateQmBars1mArgs {
intraday_path: qm_path,
provider_mapping_path: map_path.clone(),
out_dir: out_file.clone(),
mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: known_at,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
})
.expect("file qm_bars_1m");
let qm_slices: Vec<&[u8]> = qm_1m_docs.iter().map(Vec::as_slice).collect();
let mongo_qm1m = run_curate_qm_bars_1m_mongo_with_reader(
&CurateQmBars1mMongoArgs {
mongo: MongoCliOptions::default(),
provider_mapping_path: map_path,
out_dir: out_mongo.clone(),
mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: known_at,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
},
CappedRead::new(
RawBsonCursorReader::new(SliceRawDocumentSource::new(&qm_slices)),
7,
),
)
.expect("mongo qm_bars_1m");
assert_eq!(mongo_qm1m.curate_stats, file_qm1m.curate_stats);
assert_eq!(mongo_qm1m.ilp_stats, file_qm1m.ilp_stats);
// 3. curate-fx-1m in the same --out dir
let file_fx1m = run_curate_fx_1m(&CurateFx1mArgs {
intraday_path: eod_path,
out_dir: out_file.clone(),
shard_count: 2,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
})
.expect("file fx_1m");
let mongo_fx1m = run_curate_fx_1m_mongo_with_reader(
&CurateFx1mMongoArgs {
mongo: MongoCliOptions::default(),
out_dir: out_mongo.clone(),
shard_count: 2,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
},
CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(eod_1m_docs)),
11,
),
)
.expect("mongo fx_1m");
assert_eq!(mongo_fx1m.curate_stats, file_fx1m.curate_stats);
assert_eq!(mongo_fx1m.ilp_stats, file_fx1m.ilp_stats);
assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file));
}
#[test]
fn m2_mongo_read_specs_enforce_filter_types_and_key_scoping() {
let opts = MongoCliOptions {
date_gte: Some("2024-01-01".to_owned()),
date_lt: Some("2024-01-02".to_owned()),
..MongoCliOptions::default()
};
// curate-fx-1m scopes to eodSearchCode == "CAD.FOREX" + Int64 epoch seconds.
let fx_args = CurateFx1mMongoArgs {
mongo: opts.clone(),
out_dir: PathBuf::from("out"),
shard_count: 2,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
};
let fx_spec = fx_1m_read_spec(&fx_args);
let fx_doc = build_filter_document(SourceCollection::EodIntraday1M, &fx_spec).unwrap();
assert_eq!(
fx_doc.get("eodSearchCode"),
Some(&Bson::String("CAD.FOREX".to_owned()))
);
let fx_ts = fx_doc.get_document("timestamp").unwrap();
assert_eq!(fx_ts.get("$gte"), Some(&Bson::Int64(1_704_067_200)));
assert_eq!(fx_ts.get("$lt"), Some(&Bson::Int64(1_704_153_600)));
// curate-bars-1m keeps qmSplits unfiltered on dates, eodIntraday1M as Int64 epoch seconds.
let b1m_args = CurateBars1mMongoArgs {
mongo: opts.clone(),
provider_mapping_path: PathBuf::from("pm.tsv"),
out_dir: PathBuf::from("out"),
mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: 1,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
};
let (splits_spec, intraday_spec) = bars_1m_read_specs(&b1m_args);
assert!(splits_spec.date_range.is_none());
let b1m_doc = build_filter_document(SourceCollection::EodIntraday1M, &intraday_spec).unwrap();
assert_eq!(
b1m_doc.get_document("timestamp").unwrap().get("$gte"),
Some(&Bson::Int64(1_704_067_200))
);
// curate-qm-bars-1m uses Bson::DateTime millis.
let qm_args = CurateQmBars1mMongoArgs {
mongo: opts.clone(),
provider_mapping_path: PathBuf::from("pm.tsv"),
out_dir: PathBuf::from("out"),
mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: 1,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
};
let qm_spec = qm_bars_1m_read_spec(&qm_args);
let qm_doc = build_filter_document(SourceCollection::QmIntraday, &qm_spec).unwrap();
assert_eq!(
qm_doc.get_document("timestamp").unwrap().get("$gte"),
Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000)))
);
// Non-date-ranged M2 collections fail closed with DateRangeNotSupported.
let fin_args = CurateFundamentalsMongoArgs {
mongo: opts.clone(),
with_qm_financials_old: true,
provider_mapping: PathBuf::from("pm.tsv"),
listing_venues: PathBuf::from("lv.tsv"),
out_dir: PathBuf::from("out"),
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: "currency".to_string(),
financials_revenue_field: None,
financials_net_income_field: None,
financials_operating_cash_flow_field: None,
financials_total_assets_field: None,
financials_total_equity_field: None,
financials_shares_outstanding_field: None,
fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly),
filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(),
filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(),
filings_form_type_field: "formType".to_string(),
filings_filing_id_field: None,
filings_url_field: None,
mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(),
k: 4,
};
let (fin_spec, fin_old_spec, filings_spec) = fundamentals_read_specs(&fin_args);
assert!(matches!(
fin_spec.validate(SourceCollection::QmFinancials),
Err(MongoStreamError::DateRangeNotSupported {
collection: SourceCollection::QmFinancials
})
));
assert!(matches!(
fin_old_spec
.unwrap()
.validate(SourceCollection::QmFinancialsOld),
Err(MongoStreamError::DateRangeNotSupported {
collection: SourceCollection::QmFinancialsOld
})
));
assert!(filings_spec.date_range.is_none());
let posts_spec = posts_read_spec(&CuratePostsMongoArgs {
mongo: opts.clone(),
provider_mapping: PathBuf::from("pm.tsv"),
out_dir: PathBuf::from("out"),
timestamp_unit: CeoPostsTimestampUnit::Seconds,
key_field: DEFAULT_KEY_FIELD.to_string(),
spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(),
timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(),
edited_field: DEFAULT_EDITED_FIELD.to_string(),
bot_field: DEFAULT_BOT_FIELD.to_string(),
user_id_field: DEFAULT_USER_ID_FIELD.to_string(),
text_field: DEFAULT_TEXT_FIELD.to_string(),
mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(),
});
assert!(matches!(
posts_spec.validate(SourceCollection::CeoPosts),
Err(MongoStreamError::DateRangeNotSupported {
collection: SourceCollection::CeoPosts
})
));
let macro_spec = macro_read_spec(&CurateMacroMongoArgs {
mongo: opts,
series_map: PathBuf::from("sm.tsv"),
out_dir: PathBuf::from("out"),
});
assert!(matches!(
macro_spec.validate(SourceCollection::TeData),
Err(MongoStreamError::DateRangeNotSupported {
collection: SourceCollection::TeData
})
));
}
#[test]
fn m2_mongo_runners_fail_closed_on_trading_admin_and_unauthenticated_qa_uris() {
let tmp = TempDirGuard::new("mongo-safety-m2");
let secret = "S3CR3T_ADMIN_PASS_999";
let bad_uris = [
format!("mongodb://trading_admin:{secret}@localhost:27017/stock?authSource=admin"),
"mongodb://localhost:27017/stock".to_string(),
];
for (idx, uri) in bad_uris.iter().enumerate() {
let mongo = MongoCliOptions {
uri_source: MongoUriSource::Literal(uri.clone()),
..MongoCliOptions::default()
};
let out_fin = tmp.path().join(format!("fin_{idx}"));
let err = run_curate_fundamentals_mongo(&CurateFundamentalsMongoArgs {
mongo: mongo.clone(),
with_qm_financials_old: true,
provider_mapping: tmp.path().join("pm.tsv"),
listing_venues: tmp.path().join("lv.tsv"),
out_dir: out_fin.clone(),
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: "currency".to_string(),
financials_revenue_field: None,
financials_net_income_field: None,
financials_operating_cash_flow_field: None,
financials_total_assets_field: None,
financials_total_equity_field: None,
financials_shares_outstanding_field: None,
fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly),
filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(),
filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(),
filings_form_type_field: "formType".to_string(),
filings_filing_id_field: None,
filings_url_field: None,
mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(),
k: 4,
})
.expect_err("unsafe URI must fail closed");
assert!(matches!(err, RunMongoCurateError::Mongo(_)));
assert!(!err.to_string().contains(secret));
assert!(!out_fin.exists());
let out_posts = tmp.path().join(format!("posts_{idx}"));
let err = run_curate_posts_mongo(&CuratePostsMongoArgs {
mongo: mongo.clone(),
provider_mapping: tmp.path().join("pm.tsv"),
out_dir: out_posts.clone(),
timestamp_unit: CeoPostsTimestampUnit::Seconds,
key_field: DEFAULT_KEY_FIELD.to_string(),
spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(),
timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(),
edited_field: DEFAULT_EDITED_FIELD.to_string(),
bot_field: DEFAULT_BOT_FIELD.to_string(),
user_id_field: DEFAULT_USER_ID_FIELD.to_string(),
text_field: DEFAULT_TEXT_FIELD.to_string(),
mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(),
})
.expect_err("unsafe URI must fail closed");
assert!(matches!(err, RunMongoCurateError::Mongo(_)));
assert!(!err.to_string().contains(secret));
assert!(!out_posts.exists());
let out_macro = tmp.path().join(format!("macro_{idx}"));
let err = run_curate_macro_mongo(&CurateMacroMongoArgs {
mongo: mongo.clone(),
series_map: tmp.path().join("sm.tsv"),
out_dir: out_macro.clone(),
})
.expect_err("unsafe URI must fail closed");
assert!(matches!(err, RunMongoCurateError::Mongo(_)));
assert!(!err.to_string().contains(secret));
assert!(!out_macro.exists());
let out_b1m = tmp.path().join(format!("b1m_{idx}"));
let err = run_curate_bars_1m_mongo(&CurateBars1mMongoArgs {
mongo: mongo.clone(),
provider_mapping_path: tmp.path().join("pm.tsv"),
out_dir: out_b1m.clone(),
mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: 1,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
})
.expect_err("unsafe URI must fail closed");
assert!(matches!(err, RunMongoCurateError::Mongo(_)));
assert!(!err.to_string().contains(secret));
assert!(!out_b1m.exists());
let out_qm1m = tmp.path().join(format!("qm1m_{idx}"));
let err = run_curate_qm_bars_1m_mongo(&CurateQmBars1mMongoArgs {
mongo: mongo.clone(),
provider_mapping_path: tmp.path().join("pm.tsv"),
out_dir: out_qm1m.clone(),
mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: 1,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
})
.expect_err("unsafe URI must fail closed");
assert!(matches!(err, RunMongoCurateError::Mongo(_)));
assert!(!err.to_string().contains(secret));
assert!(!out_qm1m.exists());
let out_fx1m = tmp.path().join(format!("fx1m_{idx}"));
let err = run_curate_fx_1m_mongo(&CurateFx1mMongoArgs {
mongo,
out_dir: out_fx1m.clone(),
shard_count: 2,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
})
.expect_err("unsafe URI must fail closed");
assert!(matches!(err, RunMongoCurateError::Mongo(_)));
assert!(!err.to_string().contains(secret));
assert!(!out_fx1m.exists());
}
}
#[derive(Debug, Clone, PartialEq)]
struct FundamentalsPitSummaryRow {
effective_known_at: i64,
known_at_source: String,
has_estimated_lag: bool,
ttm_revenue: Option<f64>,
}
fn read_fundamentals_pit_summary_rows(path: &Path) -> Vec<FundamentalsPitSummaryRow> {
let file = File::open(path).expect("open fundamentals parquet");
let reader = SerializedFileReader::new(file).expect("open parquet reader");
let meta = reader.metadata();
let schema_descr = meta.file_metadata().schema_descr();
let mut col_idx_by_name: HashMap<&str, usize> = HashMap::new();
for (idx, col) in schema_descr.columns().iter().enumerate() {
col_idx_by_name.insert(col.name(), idx);
}
let col_idx = |name: &str| -> usize {
*col_idx_by_name
.get(name)
.unwrap_or_else(|| panic!("missing Parquet column '{name}'"))
};
let mut out = Vec::new();
for rg_idx in 0..meta.num_row_groups() {
let rg_rows = meta.row_group(rg_idx).num_rows() as usize;
let rg_reader = reader.get_row_group(rg_idx).expect("row group reader");
let mut known_at = Vec::with_capacity(rg_rows);
match rg_reader
.get_column_reader(col_idx("effective_known_at"))
.unwrap()
{
ColumnReader::Int64ColumnReader(mut typed) => {
let mut read = 0;
while read < rg_rows {
let (n, _, _) = typed
.read_records(rg_rows - read, None, None, &mut known_at)
.unwrap();
assert!(n > 0);
read += n;
}
}
_ => panic!("expected INT64 for effective_known_at"),
}
let mut sources = Vec::with_capacity(rg_rows);
match rg_reader
.get_column_reader(col_idx("known_at_source"))
.unwrap()
{
ColumnReader::ByteArrayColumnReader(mut typed) => {
let mut read = 0;
while read < rg_rows {
let (n, _, _) = typed
.read_records(rg_rows - read, None, None, &mut sources)
.unwrap();
assert!(n > 0);
read += n;
}
}
_ => panic!("expected BYTE_ARRAY for known_at_source"),
}
let mut estimated = Vec::with_capacity(rg_rows);
match rg_reader
.get_column_reader(col_idx("has_estimated_lag"))
.unwrap()
{
ColumnReader::BoolColumnReader(mut typed) => {
let mut read = 0;
while read < rg_rows {
let (n, _, _) = typed
.read_records(rg_rows - read, None, None, &mut estimated)
.unwrap();
assert!(n > 0);
read += n;
}
}
_ => panic!("expected BOOLEAN for has_estimated_lag"),
}
let mut ttm_vals = Vec::with_capacity(rg_rows);
let mut ttm_defs = Vec::with_capacity(rg_rows);
match rg_reader
.get_column_reader(col_idx("ttm_revenue"))
.unwrap()
{
ColumnReader::DoubleColumnReader(mut typed) => {
let mut read = 0;
while read < rg_rows {
let (n, _, _) = typed
.read_records(rg_rows - read, Some(&mut ttm_defs), None, &mut ttm_vals)
.unwrap();
assert!(n > 0);
read += n;
}
}
_ => panic!("expected DOUBLE for ttm_revenue"),
}
let mut vi = 0usize;
let ttm_revenues: Vec<Option<f64>> = ttm_defs
.into_iter()
.map(|d| {
if d == 1 {
let v = ttm_vals[vi];
vi += 1;
Some(v)
} else {
assert_eq!(d, 0);
None
}
})
.collect();
for i in 0..rg_rows {
out.push(FundamentalsPitSummaryRow {
effective_known_at: known_at[i],
known_at_source: String::from_utf8(sources[i].data().to_vec()).unwrap(),
has_estimated_lag: estimated[i],
ttm_revenue: ttm_revenues[i],
});
}
}
out
}
fn apply_doc_limit(docs: &[Vec<u8>], limit: Option<u64>) -> Vec<Vec<u8>> {
match limit {
Some(n) => docs.iter().take(n as usize).cloned().collect(),
None => docs.to_vec(),
}
}
#[test]
fn curate_fundamentals_mongo_limit_preserves_unbounded_filings_and_restated_ttm() {
let tmp = TempDirGuard::new("fundamentals-limit-unbounded-filings");
let map_path = tmp.path().join("provider_mapping.tsv");
let ven_path = tmp.path().join("listing_venues.tsv");
fs::write(&map_path, "qm\tACME:US\t2020-01-01\t\t101\n").unwrap();
fs::write(&ven_path, "101\tus_tsx\n").unwrap();
let fin_docs = vec![
make_fin_doc("ACME:US", "2024-06-30", "2024-08-05", "Q2", 130.0),
make_fin_doc("ACME:US", "2024-03-31", "2024-09-10", "Q1", 125.0),
];
let old_docs = vec![
make_fin_doc("ACME:US", "2023-09-30", "2023-11-05", "Q3", 100.0),
make_fin_doc("ACME:US", "2023-12-31", "2024-02-20", "Q4", 110.0),
make_fin_doc("ACME:US", "2024-03-31", "2024-05-05", "Q1", 120.0),
];
// Place 8 unrelated filings ahead of ACME's filings so any `--limit 5` cap on `qmFilings`
// would cut off ACME's filing evidence (including the 2024-09-10 Q1 amendment).
let mut fil_docs: Vec<Vec<u8>> = (0..8)
.map(|_| make_filing_doc("OTHER:US", "2023-01-15T16:30:00 EST", "10-Q"))
.collect();
fil_docs.extend([
make_filing_doc("ACME:US", "2023-11-05T16:30:00 EST", "10-Q"),
make_filing_doc("ACME:US", "2024-02-20T16:30:00 EST", "10-Q"),
make_filing_doc("ACME:US", "2024-05-05T16:30:00 EDT", "10-Q"),
make_filing_doc("ACME:US", "2024-08-05T16:30:00 EDT", "10-Q"),
make_filing_doc("ACME:US", "2024-09-10T16:30:00 EDT", "10-Q/A"),
]);
let out_unbounded_filings = tmp.path().join("out_unbounded_filings");
let mongo_args = CurateFundamentalsMongoArgs {
mongo: MongoCliOptions {
limit: Some(5),
..MongoCliOptions::default()
},
with_qm_financials_old: true,
provider_mapping: map_path.clone(),
listing_venues: ven_path.clone(),
out_dir: out_unbounded_filings.clone(),
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: "currency".to_string(),
financials_revenue_field: Some("revenue".to_string()),
financials_net_income_field: None,
financials_operating_cash_flow_field: None,
financials_total_assets_field: None,
financials_total_equity_field: None,
financials_shares_outstanding_field: None,
fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly),
filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(),
filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(),
filings_form_type_field: "formType".to_string(),
filings_filing_id_field: None,
filings_url_field: None,
mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(),
k: 4,
};
let (fin_spec, fin_old_spec, filings_spec) = fundamentals_read_specs(&mongo_args);
assert_eq!(fin_spec.limit, Some(5));
assert_eq!(fin_old_spec.as_ref().unwrap().limit, Some(5));
assert!(
filings_spec.limit.is_none(),
"qmFilings must stay uncapped under --limit"
);
assert!(filings_spec.date_range.is_none());
let fin_cursor = RawBsonCursorReader::new(VecRawDocumentSource::new(apply_doc_limit(
&fin_docs,
fin_spec.limit,
)));
let old_cursor = RawBsonCursorReader::new(VecRawDocumentSource::new(apply_doc_limit(
&old_docs,
fin_old_spec.unwrap().limit,
)));
let fil_cursor = RawBsonCursorReader::new(VecRawDocumentSource::new(apply_doc_limit(
&fil_docs,
filings_spec.limit,
)));
run_curate_fundamentals_mongo_with_readers(&mongo_args, fin_cursor, Some(old_cursor), fil_cursor)
.expect("fundamentals run under --limit");
let rows_2024 = read_fundamentals_pit_summary_rows(
&out_unbounded_filings
.join("fundamentals_pit")
.join("year=2024")
.join("part.parquet"),
);
let expected_amendment_micros =
et_to_utc_micros(ymd_to_epoch_days(2024, 9, 10).unwrap(), 16, 30, 0).unwrap();
let amendment_row = rows_2024
.iter()
.find(|r| r.effective_known_at == expected_amendment_micros)
.expect("retained Q1 amendment must keep its 2024-09-10 filing timestamp under --limit");
assert_eq!(
amendment_row.known_at_source,
KNOWN_AT_SOURCE_FILING_TIMESTAMP
);
assert!(!amendment_row.has_estimated_lag);
assert_eq!(amendment_row.ttm_revenue, Some(465.0));
// Negative control: if `qmFilings` had been capped by `--limit 5`, the amendment would lose
// its filing and drop as unanchored, leaving TTM stale.
let out_capped_filings = tmp.path().join("out_capped_filings");
let mut capped_args = mongo_args;
capped_args.out_dir = out_capped_filings.clone();
run_curate_fundamentals_mongo_with_readers(
&capped_args,
RawBsonCursorReader::new(VecRawDocumentSource::new(apply_doc_limit(
&fin_docs,
Some(5),
))),
Some(RawBsonCursorReader::new(VecRawDocumentSource::new(
apply_doc_limit(&old_docs, Some(5)),
))),
RawBsonCursorReader::new(VecRawDocumentSource::new(apply_doc_limit(
&fil_docs,
Some(5),
))),
)
.expect("negative-control run");
let capped_rows = read_fundamentals_pit_summary_rows(
&out_capped_filings
.join("fundamentals_pit")
.join("year=2024")
.join("part.parquet"),
);
assert!(
!capped_rows
.iter()
.any(|r| r.effective_known_at == expected_amendment_micros),
"capping qmFilings would drop the unanchored amendment"
);
assert!(!capped_rows.iter().any(|r| r.ttm_revenue == Some(465.0)));
}
fn make_eod_1m_doc(
code: &str,
ts_secs: i64,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), code);
doc.append(cstr!("timestamp"), ts_secs);
doc.append(cstr!("open"), open);
doc.append(cstr!("high"), high);
doc.append(cstr!("low"), low);
doc.append(cstr!("close"), close);
doc.append(cstr!("volume"), volume);
doc.into_bytes()
}
fn make_qm_1m_doc(
code: &str,
ts_secs: i64,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("timestamp"), DateTime::from_millis(ts_secs * 1_000));
doc.append(cstr!("open"), open);
doc.append(cstr!("high"), high);
doc.append(cstr!("low"), low);
doc.append(cstr!("close"), close);
doc.append(cstr!("sharevolume"), volume);
doc.into_bytes()
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct EconomicBar1mRow {
listing_id: i32,
ts: i64,
source: String,
open_bits: u64,
high_bits: u64,
low_bits: u64,
close_bits: u64,
volume_bits: u64,
known_at: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct EconomicFx1mRow {
pair: String,
source: String,
ts: i64,
open_bits: u64,
high_bits: u64,
low_bits: u64,
close_bits: u64,
}
fn read_ilp_bin_f64_bits(data: &[u8], pos: &mut usize, name: &str) -> u64 {
let prefix = format!("{name}==");
assert!(
data[*pos..].starts_with(prefix.as_bytes()),
"expected ILP field '{prefix}' at offset {}",
*pos
);
*pos += prefix.len();
assert_eq!(data[*pos], ILP_V2_DOUBLE_TYPE);
*pos += 1;
let bytes: [u8; 8] = data[*pos..*pos + 8].try_into().expect("8-byte f64");
*pos += 8;
f64::from_le_bytes(bytes).to_bits()
}
fn collect_ilp_bars_1m_rows(out_dir: &Path, prefix: &str) -> BTreeSet<EconomicBar1mRow> {
let mut rows = BTreeSet::new();
for entry in fs::read_dir(out_dir).expect("read ilp out_dir") {
let path = entry.expect("dir entry").path();
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if !(name.starts_with(prefix) && name.ends_with(".ilp")) {
continue;
}
let data = fs::read(&path).expect("read ilp shard");
let mut i = 0usize;
while i < data.len() {
let tag_start = i;
while i < data.len() {
match data[i] {
b'\\' => i += 2,
b' ' => break,
_ => i += 1,
}
}
let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("utf8 tag set");
i += 1;
let mut tags = tag_str.split(',');
assert_eq!(tags.next(), Some(TABLE_BARS_1M));
let listing_id: i32 = tags
.next()
.unwrap()
.strip_prefix("listing_id=")
.unwrap()
.parse()
.unwrap();
let _session = tags.next().unwrap();
let source = tags
.next()
.unwrap()
.strip_prefix("source=")
.unwrap()
.to_owned();
assert!(tags.next().is_none());
let open_bits = read_ilp_bin_f64_bits(&data, &mut i, "open");
assert_eq!(data[i], b',');
i += 1;
let high_bits = read_ilp_bin_f64_bits(&data, &mut i, "high");
assert_eq!(data[i], b',');
i += 1;
let low_bits = read_ilp_bin_f64_bits(&data, &mut i, "low");
assert_eq!(data[i], b',');
i += 1;
let close_bits = read_ilp_bin_f64_bits(&data, &mut i, "close");
assert_eq!(data[i], b',');
i += 1;
let volume_bits = read_ilp_bin_f64_bits(&data, &mut i, "volume");
assert!(data[i..].starts_with(b",known_at="));
i += b",known_at=".len();
let ka_start = i;
while data[i] != b't' {
i += 1;
}
let known_at: i64 = std::str::from_utf8(&data[ka_start..i])
.unwrap()
.parse()
.unwrap();
assert!(data[i..].starts_with(b"t "));
i += 2;
let ts_start = i;
while data[i] != b't' {
i += 1;
}
let ts: i64 = std::str::from_utf8(&data[ts_start..i])
.unwrap()
.parse()
.unwrap();
assert!(data[i..].starts_with(b"t\n"));
i += 2;
rows.insert(EconomicBar1mRow {
listing_id,
ts,
source,
open_bits,
high_bits,
low_bits,
close_bits,
volume_bits,
known_at,
});
}
}
rows
}
fn collect_ilp_fx_1m_rows(out_dir: &Path, prefix: &str) -> BTreeSet<EconomicFx1mRow> {
let mut rows = BTreeSet::new();
for entry in fs::read_dir(out_dir).expect("read ilp out_dir") {
let path = entry.expect("dir entry").path();
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if !(name.starts_with(prefix) && name.ends_with(".ilp")) {
continue;
}
let data = fs::read(&path).expect("read ilp shard");
let mut i = 0usize;
while i < data.len() {
let tag_start = i;
while i < data.len() {
match data[i] {
b'\\' => i += 2,
b' ' => break,
_ => i += 1,
}
}
let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("utf8 tag set");
i += 1;
let mut tags = tag_str.split(',');
assert_eq!(tags.next(), Some(TABLE_FX_1M));
let pair = tags
.next()
.unwrap()
.strip_prefix("pair=")
.unwrap()
.to_owned();
let source = tags
.next()
.unwrap()
.strip_prefix("source=")
.unwrap()
.to_owned();
assert!(tags.next().is_none());
let open_bits = read_ilp_bin_f64_bits(&data, &mut i, "open");
assert_eq!(data[i], b',');
i += 1;
let high_bits = read_ilp_bin_f64_bits(&data, &mut i, "high");
assert_eq!(data[i], b',');
i += 1;
let low_bits = read_ilp_bin_f64_bits(&data, &mut i, "low");
assert_eq!(data[i], b',');
i += 1;
let close_bits = read_ilp_bin_f64_bits(&data, &mut i, "close");
assert_eq!(data[i], b' ');
i += 1;
let ts_start = i;
while data[i] != b't' {
i += 1;
}
let ts: i64 = std::str::from_utf8(&data[ts_start..i])
.unwrap()
.parse()
.unwrap();
assert!(data[i..].starts_with(b"t\n"));
i += 2;
rows.insert(EconomicFx1mRow {
pair,
source,
ts,
open_bits,
high_bits,
low_bits,
close_bits,
});
}
}
rows
}
#[test]
fn parity_curate_1m_ilp_filtered_multi_key_cross_chunk_matches_economic_rows_and_pinned_bytes() {
let tmp = TempDirGuard::new("parity-1m-ilp-filtered-cross-chunk");
let map_path = tmp.path().join("provider_mapping.tsv");
fs::write(
&map_path,
"eod\tNVDA.US\t2020-01-01\t\t301\n\
eod\tAAPL.US\t2020-01-01\t\t302\n\
qm\tNVDA:US\t2020-01-01\t\t301\n\
qm\tAAPL:US\t2020-01-01\t\t302\n",
)
.unwrap();
// 10:1 forward split for NVDA (listing 301) on 2024-06-10 (QuoteMedia stores
// `splitratio = forfactor / tofactor = old_shares / new_shares = 0.1`); AAPL has no split.
let mut sp = RawDocumentBuf::new();
sp.append(cstr!("qmSearchCode"), "NVDA:US");
sp.append(cstr!("date"), "2024-06-10");
sp.append(cstr!("forfactor"), 1.0_f64);
sp.append(cstr!("tofactor"), 10.0_f64);
sp.append(cstr!("splitratio"), 0.1_f64);
let split_docs = vec![sp.into_bytes()];
let splits_path = tmp.path().join("qmSplits.bson");
fs::write(&splits_path, concat_docs(&split_docs)).unwrap();
// Window: [2024-06-07, 2024-06-08) -> [1_717_718_400, 1_717_804_800) UTC seconds.
let ts_before = 1_717_680_600_i64; // 2024-06-06 13:30:00Z
let ts_1330 = 1_717_767_000_i64; // 2024-06-07 13:30:00Z
let ts_1331 = 1_717_767_060_i64; // 2024-06-07 13:31:00Z
let ts_after = 1_717_853_400_i64; // 2024-06-08 13:30:00Z
let eod_corpus: Vec<(&str, i64, Vec<u8>)> = vec![
// Out-of-window and unmapped rows excluded by production Mongo filters.
(
"NVDA.US",
ts_before,
make_eod_1m_doc("NVDA.US", ts_before, 118.0, 119.0, 117.0, 118.5, 500.0),
),
(
"UNMAPPED.US",
ts_1330,
make_eod_1m_doc("UNMAPPED.US", ts_1330, 50.0, 51.0, 49.0, 50.5, 100.0),
),
(
"AAPL.US",
ts_after,
make_eod_1m_doc("AAPL.US", ts_after, 199.0, 200.0, 198.0, 199.5, 400.0),
),
(
"CAD.FOREX",
ts_before,
make_eod_1m_doc("CAD.FOREX", ts_before, 1.365, 1.366, 1.364, 1.3655, 0.0),
),
// In-window multi-key equity rows + exact duplicate to exercise per-chunk dedup.
(
"NVDA.US",
ts_1330,
make_eod_1m_doc("NVDA.US", ts_1330, 120.0, 121.0, 119.0, 120.5, 1000.0),
),
(
"AAPL.US",
ts_1330,
make_eod_1m_doc("AAPL.US", ts_1330, 195.0, 196.0, 194.0, 195.5, 800.0),
),
(
"NVDA.US",
ts_1330,
make_eod_1m_doc("NVDA.US", ts_1330, 120.0, 121.0, 119.0, 120.5, 1000.0),
),
(
"NVDA.US",
ts_1331,
make_eod_1m_doc("NVDA.US", ts_1331, 121.0, 122.0, 120.0, 121.5, 1100.0),
),
(
"AAPL.US",
ts_1331,
make_eod_1m_doc("AAPL.US", ts_1331, 196.0, 197.0, 195.0, 196.5, 900.0),
),
// In-window CAD.FOREX rows (including a cross-chunk duplicate at ts_1330).
(
"CAD.FOREX",
ts_1330,
make_eod_1m_doc("CAD.FOREX", ts_1330, 1.370, 1.371, 1.369, 1.3705, 0.0),
),
(
"CAD.FOREX",
ts_1331,
make_eod_1m_doc("CAD.FOREX", ts_1331, 1.371, 1.372, 1.370, 1.3715, 0.0),
),
(
"CAD.FOREX",
ts_1330,
make_eod_1m_doc("CAD.FOREX", ts_1330, 1.370, 1.371, 1.369, 1.3705, 0.0),
),
];
let qm_corpus: Vec<(&str, i64, Vec<u8>)> = vec![
(
"UNMAPPED:US",
ts_1330,
make_qm_1m_doc("UNMAPPED:US", ts_1330, 50.0, 51.0, 49.0, 50.5, 100.0),
),
(
"NVDA:US",
ts_before,
make_qm_1m_doc("NVDA:US", ts_before, 1180.0, 1190.0, 1170.0, 1185.0, 50.0),
),
(
"NVDA:US",
ts_1330,
make_qm_1m_doc("NVDA:US", ts_1330, 1200.0, 1210.0, 1190.0, 1205.0, 100.0),
),
(
"AAPL:US",
ts_1330,
make_qm_1m_doc("AAPL:US", ts_1330, 195.0, 196.0, 194.0, 195.5, 800.0),
),
(
"NVDA:US",
ts_1331,
make_qm_1m_doc("NVDA:US", ts_1331, 1210.0, 1220.0, 1200.0, 1215.0, 110.0),
),
(
"AAPL:US",
ts_1331,
make_qm_1m_doc("AAPL:US", ts_1331, 196.0, 197.0, 195.0, 196.5, 900.0),
),
// Cross-chunk duplicate for NVDA:US at ts_1330.
(
"NVDA:US",
ts_1330,
make_qm_1m_doc("NVDA:US", ts_1330, 1200.0, 1210.0, 1190.0, 1205.0, 100.0),
),
];
let date_opts = MongoCliOptions {
date_gte: Some("2024-06-07".to_owned()),
date_lt: Some("2024-06-08".to_owned()),
..MongoCliOptions::default()
};
// Small chunk capacity (~2 docs/chunk) forces multi-key streams across BSON chunk boundaries.
let small_chunks = BsonStreamOptions {
chunk_capacity_bytes: 280,
max_doc_bytes: 1024 * 1024,
};
let known_at = 1_750_000_000_000_000_i64;
// 1. bars_1m: apply production `$in` eod key filter + Int64 epoch-second date filter.
let b1m_mongo_args = CurateBars1mMongoArgs {
mongo: date_opts.clone(),
provider_mapping_path: map_path.clone(),
out_dir: tmp.path().join("b1m_mongo_pinned"),
mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: known_at,
stream_options: small_chunks,
ilp_options: IlpWriterOptions::default(),
};
let (_splits_spec, b1m_spec) = bars_1m_read_specs(&b1m_mongo_args);
let b1m_filter = build_filter_document(SourceCollection::EodIntraday1M, &b1m_spec).unwrap();
let b1m_gte = b1m_filter
.get_document("timestamp")
.unwrap()
.get_i64("$gte")
.unwrap();
let b1m_lt = b1m_filter
.get_document("timestamp")
.unwrap()
.get_i64("$lt")
.unwrap();
let eod_keys: BTreeSet<String> =
unique_mapping_keys_for_source(&map_path, DEFAULT_BARS_1M_MAPPING_SOURCE)
.unwrap()
.into_iter()
.collect();
let b1m_filtered_pinned: Vec<Vec<u8>> = eod_corpus
.iter()
.filter(|(k, ts, _)| eod_keys.contains(*k) && *ts >= b1m_gte && *ts < b1m_lt)
.map(|(_, _, b)| b.clone())
.collect();
assert_eq!(b1m_filtered_pinned.len(), 5);
assert!(
concat_docs(&b1m_filtered_pinned).len() > small_chunks.chunk_capacity_bytes,
"filtered bars_1m fixture must cross a BSON chunk boundary"
);
let b1m_filtered_path = tmp.path().join("eodIntraday1M_filtered.bson");
fs::write(&b1m_filtered_path, concat_docs(&b1m_filtered_pinned)).unwrap();
let b1m_file_out = tmp.path().join("b1m_file_pinned");
let b1m_file_rep = run_curate_bars_1m(&CurateBars1mArgs {
intraday_path: b1m_filtered_path,
splits_path,
provider_mapping_path: map_path.clone(),
out_dir: b1m_file_out.clone(),
mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: known_at,
stream_options: small_chunks,
ilp_options: IlpWriterOptions::default(),
})
.expect("file bars_1m pinned");
let b1m_pinned_rep = run_curate_bars_1m_mongo_with_readers(
&b1m_mongo_args,
CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(b1m_filtered_pinned.clone())),
19,
),
RawBsonCursorReader::new(VecRawDocumentSource::new(split_docs.clone())),
)
.expect("mongo bars_1m pinned");
assert_eq!(b1m_pinned_rep.rows_written, 4);
assert_eq!(b1m_pinned_rep.curate_stats, b1m_file_rep.curate_stats);
assert_eq!(b1m_pinned_rep.ilp_stats, b1m_file_rep.ilp_stats);
assert_eq!(
snapshot_files(&b1m_mongo_args.out_dir),
snapshot_files(&b1m_file_out)
);
// Reordered `$in` key-grouped cursor order (all AAPL docs before NVDA docs, reversed ts)
// with duplicates straddling BSON chunk boundaries must produce byte-identical shards and
// identical row counts.
let mut b1m_reordered: Vec<(&str, i64, Vec<u8>)> = eod_corpus
.iter()
.filter(|(k, ts, _)| eod_keys.contains(*k) && *ts >= b1m_gte && *ts < b1m_lt)
.cloned()
.collect();
b1m_reordered.sort_by(|a, b| a.0.cmp(b.0).then_with(|| b.1.cmp(&a.1)));
let b1m_reordered_docs: Vec<Vec<u8>> = b1m_reordered.into_iter().map(|(_, _, b)| b).collect();
let mut b1m_reordered_args = b1m_mongo_args;
b1m_reordered_args.out_dir = tmp.path().join("b1m_mongo_reordered");
let b1m_reordered_rep = run_curate_bars_1m_mongo_with_readers(
&b1m_reordered_args,
CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(b1m_reordered_docs)),
17,
),
RawBsonCursorReader::new(VecRawDocumentSource::new(split_docs)),
)
.expect("mongo bars_1m reordered");
assert!(b1m_reordered_rep.chunks > 1);
assert_eq!(b1m_reordered_rep.rows_written, b1m_file_rep.rows_written);
assert_eq!(b1m_reordered_rep.rows_written, 4);
assert_eq!(b1m_reordered_rep.curate_stats, b1m_file_rep.curate_stats);
assert_eq!(b1m_reordered_rep.ilp_stats, b1m_file_rep.ilp_stats);
assert_eq!(
snapshot_files(&b1m_reordered_args.out_dir),
snapshot_files(&b1m_file_out)
);
let b1m_file_rows = collect_ilp_bars_1m_rows(&b1m_file_out, "bars_1m.shard-");
let b1m_reordered_rows = collect_ilp_bars_1m_rows(&b1m_reordered_args.out_dir, "bars_1m.shard-");
assert_eq!(b1m_reordered_rows, b1m_file_rows);
assert_eq!(b1m_reordered_rows.len(), 4);
assert!(b1m_reordered_rows.iter().any(|r| {
r.listing_id == 301
&& r.ts == ts_1330 * 1_000_000
&& f64::from_bits(r.open_bits) == 1200.0
&& r.known_at == known_at
}));
assert!(b1m_reordered_rows.iter().any(|r| {
r.listing_id == 302
&& r.ts == ts_1330 * 1_000_000
&& f64::from_bits(r.open_bits) == 195.0
&& r.known_at == known_at
}));
// 2. qm_bars_1m: apply production `$in` qm key filter + DateTime millisecond date filter.
let qm_mongo_args = CurateQmBars1mMongoArgs {
mongo: date_opts.clone(),
provider_mapping_path: map_path.clone(),
out_dir: tmp.path().join("qm_mongo_pinned"),
mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: known_at,
stream_options: small_chunks,
ilp_options: IlpWriterOptions::default(),
};
let qm_spec = qm_bars_1m_read_spec(&qm_mongo_args);
let qm_filter = build_filter_document(SourceCollection::QmIntraday, &qm_spec).unwrap();
let qm_gte_ms = qm_filter
.get_document("timestamp")
.unwrap()
.get_datetime("$gte")
.unwrap()
.timestamp_millis();
let qm_lt_ms = qm_filter
.get_document("timestamp")
.unwrap()
.get_datetime("$lt")
.unwrap()
.timestamp_millis();
let qm_keys: BTreeSet<String> =
unique_mapping_keys_for_source(&map_path, DEFAULT_QM_BARS_1M_MAPPING_SOURCE)
.unwrap()
.into_iter()
.collect();
let qm_filtered_pinned: Vec<Vec<u8>> = qm_corpus
.iter()
.filter(|(k, ts, _)| {
qm_keys.contains(*k) && (*ts * 1_000) >= qm_gte_ms && (*ts * 1_000) < qm_lt_ms
})
.map(|(_, _, b)| b.clone())
.collect();
assert_eq!(qm_filtered_pinned.len(), 5);
assert!(
concat_docs(&qm_filtered_pinned).len() > small_chunks.chunk_capacity_bytes,
"filtered qm_bars_1m fixture must cross a BSON chunk boundary"
);
let qm_filtered_path = tmp.path().join("qmIntraday_filtered.bson");
fs::write(&qm_filtered_path, concat_docs(&qm_filtered_pinned)).unwrap();
let qm_file_out = tmp.path().join("qm_file_pinned");
let qm_file_rep = run_curate_qm_bars_1m(&CurateQmBars1mArgs {
intraday_path: qm_filtered_path,
provider_mapping_path: map_path,
out_dir: qm_file_out.clone(),
mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 2,
known_at_micros: known_at,
stream_options: small_chunks,
ilp_options: IlpWriterOptions::default(),
})
.expect("file qm_bars_1m pinned");
let qm_pinned_rep = run_curate_qm_bars_1m_mongo_with_reader(
&qm_mongo_args,
CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(qm_filtered_pinned)),
13,
),
)
.expect("mongo qm_bars_1m pinned");
assert_eq!(qm_pinned_rep.rows_written, 4);
assert_eq!(qm_pinned_rep.curate_stats, qm_file_rep.curate_stats);
assert_eq!(qm_pinned_rep.ilp_stats, qm_file_rep.ilp_stats);
assert_eq!(
snapshot_files(&qm_mongo_args.out_dir),
snapshot_files(&qm_file_out)
);
let mut qm_reordered: Vec<(&str, i64, Vec<u8>)> = qm_corpus
.iter()
.filter(|(k, ts, _)| {
qm_keys.contains(*k) && (*ts * 1_000) >= qm_gte_ms && (*ts * 1_000) < qm_lt_ms
})
.cloned()
.collect();
qm_reordered.sort_by(|a, b| a.0.cmp(b.0).then_with(|| b.1.cmp(&a.1)));
let mut qm_reordered_args = qm_mongo_args;
qm_reordered_args.out_dir = tmp.path().join("qm_mongo_reordered");
let qm_reordered_rep = run_curate_qm_bars_1m_mongo_with_reader(
&qm_reordered_args,
CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(
qm_reordered.into_iter().map(|(_, _, b)| b).collect(),
)),
11,
),
)
.expect("mongo qm_bars_1m reordered");
assert!(qm_reordered_rep.chunks > 1);
assert_eq!(qm_reordered_rep.rows_written, qm_file_rep.rows_written);
assert_eq!(qm_reordered_rep.rows_written, 4);
assert_eq!(qm_reordered_rep.curate_stats, qm_file_rep.curate_stats);
assert_eq!(qm_reordered_rep.ilp_stats, qm_file_rep.ilp_stats);
assert_eq!(
snapshot_files(&qm_reordered_args.out_dir),
snapshot_files(&qm_file_out)
);
let qm_file_rows = collect_ilp_bars_1m_rows(&qm_file_out, "bars_1m_qm.shard-");
let qm_reordered_rows =
collect_ilp_bars_1m_rows(&qm_reordered_args.out_dir, "bars_1m_qm.shard-");
assert_eq!(qm_reordered_rows, qm_file_rows);
assert_eq!(qm_reordered_rows.len(), 4);
assert!(qm_reordered_rows
.iter()
.all(|r| r.source == "qm_raw" && r.known_at == known_at));
// 3. fx_1m: apply production `eodSearchCode == "CAD.FOREX"` + epoch-second date filter.
let fx_mongo_args = CurateFx1mMongoArgs {
mongo: date_opts,
out_dir: tmp.path().join("fx_mongo_pinned"),
shard_count: 2,
stream_options: BsonStreamOptions {
chunk_capacity_bytes: 160,
max_doc_bytes: 1024 * 1024,
},
ilp_options: IlpWriterOptions::default(),
};
let fx_spec = fx_1m_read_spec(&fx_mongo_args);
let fx_filter = build_filter_document(SourceCollection::EodIntraday1M, &fx_spec).unwrap();
let fx_key = fx_filter.get_str("eodSearchCode").unwrap();
let fx_gte = fx_filter
.get_document("timestamp")
.unwrap()
.get_i64("$gte")
.unwrap();
let fx_lt = fx_filter
.get_document("timestamp")
.unwrap()
.get_i64("$lt")
.unwrap();
let fx_filtered_pinned: Vec<Vec<u8>> = eod_corpus
.iter()
.filter(|(k, ts, _)| *k == fx_key && *ts >= fx_gte && *ts < fx_lt)
.map(|(_, _, b)| b.clone())
.collect();
assert_eq!(fx_filtered_pinned.len(), 3);
assert!(
concat_docs(&fx_filtered_pinned).len() > fx_mongo_args.stream_options.chunk_capacity_bytes,
"filtered fx_1m fixture must cross a BSON chunk boundary"
);
let fx_filtered_path = tmp.path().join("fx_filtered.bson");
fs::write(&fx_filtered_path, concat_docs(&fx_filtered_pinned)).unwrap();
let fx_file_out = tmp.path().join("fx_file_pinned");
let fx_file_rep = run_curate_fx_1m(&CurateFx1mArgs {
intraday_path: fx_filtered_path,
out_dir: fx_file_out.clone(),
shard_count: 2,
stream_options: fx_mongo_args.stream_options,
ilp_options: IlpWriterOptions::default(),
})
.expect("file fx_1m pinned");
let fx_pinned_rep = run_curate_fx_1m_mongo_with_reader(
&fx_mongo_args,
CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(fx_filtered_pinned.clone())),
11,
),
)
.expect("mongo fx_1m pinned");
assert_eq!(fx_pinned_rep.rows_written, 2);
assert_eq!(fx_pinned_rep.curate_stats, fx_file_rep.curate_stats);
assert_eq!(fx_pinned_rep.ilp_stats, fx_file_rep.ilp_stats);
assert_eq!(
snapshot_files(&fx_mongo_args.out_dir),
snapshot_files(&fx_file_out)
);
let mut fx_reversed = fx_filtered_pinned;
fx_reversed.reverse();
let mut fx_reordered_args = fx_mongo_args;
fx_reordered_args.out_dir = tmp.path().join("fx_mongo_reordered");
let fx_reordered_rep = run_curate_fx_1m_mongo_with_reader(
&fx_reordered_args,
CappedRead::new(
RawBsonCursorReader::new(VecRawDocumentSource::new(fx_reversed)),
7,
),
)
.expect("mongo fx_1m reordered");
assert_eq!(fx_reordered_rep.rows_written, fx_file_rep.rows_written);
assert_eq!(fx_reordered_rep.rows_written, 2);
assert_eq!(fx_reordered_rep.curate_stats, fx_file_rep.curate_stats);
assert_eq!(fx_reordered_rep.ilp_stats, fx_file_rep.ilp_stats);
assert_eq!(
snapshot_files(&fx_reordered_args.out_dir),
snapshot_files(&fx_file_out)
);
let fx_file_rows = collect_ilp_fx_1m_rows(&fx_file_out, "fx_1m.shard-");
let fx_reordered_rows = collect_ilp_fx_1m_rows(&fx_reordered_args.out_dir, "fx_1m.shard-");
assert_eq!(fx_reordered_rows, fx_file_rows);
assert_eq!(fx_reordered_rows.len(), 2);
assert!(fx_reordered_rows
.iter()
.all(|r| r.pair == "USDCAD" && r.source == "eod"));
}