T-212: M2.3t — Add --qm-financials-old merge and Option B --from-mongo streaming for M2 collections in curate-etl
This commit is contained in:
parent
b1d0941605
commit
1505a001d2
2 changed files with 1055 additions and 107 deletions
|
|
@ -377,6 +377,20 @@ fn connect_and_validate_specs(
|
|||
mongo.uri_source.connect().map_err(RunMongoCurateError::Mongo)
|
||||
}
|
||||
|
||||
fn with_mongo_client<T, F>(
|
||||
mongo: &MongoCliOptions,
|
||||
checks: &[(SourceCollection, MongoReadSpec)],
|
||||
f: F,
|
||||
) -> Result<T, RunMongoCurateError>
|
||||
where
|
||||
F: FnOnce(&ReadOnlyMongoClient) -> Result<T, RunMongoCurateError>,
|
||||
{
|
||||
let client = connect_and_validate_specs(mongo, checks)?;
|
||||
let result = f(&client);
|
||||
client.shutdown();
|
||||
result
|
||||
}
|
||||
|
||||
fn unique_mapping_keys_for_source(
|
||||
provider_mapping_path: &Path,
|
||||
source: &str,
|
||||
|
|
@ -720,7 +734,6 @@ pub(crate) fn fundamentals_read_specs(
|
|||
});
|
||||
let filings_spec = MongoReadSpec {
|
||||
batch_size: args.mongo.batch_size,
|
||||
limit: args.mongo.limit,
|
||||
..MongoReadSpec::default()
|
||||
};
|
||||
(fin_spec, fin_old_spec, filings_spec)
|
||||
|
|
@ -744,6 +757,10 @@ pub(crate) fn run_curate_fundamentals_mongo_with_readers<RF: io::Read, RO: io::R
|
|||
|
||||
/// Streams `qmFinancials`, optional `qmFinancials-old`, and `qmFilings` directly from read-only
|
||||
/// MongoDB into `fundamentals_pit/year=YYYY/part.parquet`.
|
||||
///
|
||||
/// `qmFilings` is always read without date-range or `--limit` caps so retained financial
|
||||
/// observations (including restatements) never lose their matching filing timestamps when
|
||||
/// `--limit` samples `qmFinancials` / `qmFinancials-old`.
|
||||
pub fn run_curate_fundamentals_mongo(
|
||||
args: &CurateFundamentalsMongoArgs,
|
||||
) -> Result<CurateFundamentalsRunReport, RunMongoCurateError> {
|
||||
|
|
@ -755,9 +772,7 @@ pub fn run_curate_fundamentals_mongo(
|
|||
if let Some(old_spec) = &fin_old_spec {
|
||||
checks.push((SourceCollection::QmFinancialsOld, old_spec.clone()));
|
||||
}
|
||||
let client = connect_and_validate_specs(&args.mongo, &checks)?;
|
||||
|
||||
let result = {
|
||||
with_mongo_client(&args.mongo, &checks, |client| {
|
||||
let fin_reader = client
|
||||
.open_raw_cursor(SourceCollection::QmFinancials, &fin_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
|
|
@ -774,10 +789,7 @@ pub fn run_curate_fundamentals_mongo(
|
|||
.open_raw_cursor(SourceCollection::QmFilings, &filings_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_fundamentals_mongo_with_readers(args, fin_reader, fin_old_reader, filings_reader)
|
||||
};
|
||||
|
||||
client.shutdown();
|
||||
result
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn posts_read_spec(args: &CuratePostsMongoArgs) -> MongoReadSpec {
|
||||
|
|
@ -815,20 +827,16 @@ pub fn run_curate_posts_mongo(
|
|||
args: &CuratePostsMongoArgs,
|
||||
) -> Result<CuratePostsRunReport, RunMongoCurateError> {
|
||||
let posts_spec = posts_read_spec(args);
|
||||
let client = connect_and_validate_specs(
|
||||
with_mongo_client(
|
||||
&args.mongo,
|
||||
&[(SourceCollection::CeoPosts, posts_spec.clone())],
|
||||
)?;
|
||||
|
||||
let result = {
|
||||
let posts_reader = client
|
||||
.open_raw_cursor(SourceCollection::CeoPosts, &posts_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_posts_mongo_with_reader(args, posts_reader)
|
||||
};
|
||||
|
||||
client.shutdown();
|
||||
result
|
||||
|client| {
|
||||
let posts_reader = client
|
||||
.open_raw_cursor(SourceCollection::CeoPosts, &posts_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_posts_mongo_with_reader(args, posts_reader)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn macro_read_spec(args: &CurateMacroMongoArgs) -> MongoReadSpec {
|
||||
|
|
@ -851,18 +859,16 @@ pub fn run_curate_macro_mongo(
|
|||
args: &CurateMacroMongoArgs,
|
||||
) -> Result<CurateMacroRunReport, RunMongoCurateError> {
|
||||
let te_spec = macro_read_spec(args);
|
||||
let client =
|
||||
connect_and_validate_specs(&args.mongo, &[(SourceCollection::TeData, te_spec.clone())])?;
|
||||
|
||||
let result = {
|
||||
let te_reader = client
|
||||
.open_raw_cursor(SourceCollection::TeData, &te_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_macro_mongo_with_reader(args, te_reader)
|
||||
};
|
||||
|
||||
client.shutdown();
|
||||
result
|
||||
with_mongo_client(
|
||||
&args.mongo,
|
||||
&[(SourceCollection::TeData, te_spec.clone())],
|
||||
|client| {
|
||||
let te_reader = client
|
||||
.open_raw_cursor(SourceCollection::TeData, &te_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_macro_mongo_with_reader(args, te_reader)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn bars_1m_read_specs(args: &CurateBars1mMongoArgs) -> (MongoReadSpec, MongoReadSpec) {
|
||||
|
|
@ -896,46 +902,42 @@ pub fn run_curate_bars_1m_mongo(
|
|||
args: &CurateBars1mMongoArgs,
|
||||
) -> Result<CurateBars1mRunReport, RunMongoCurateError> {
|
||||
let (splits_spec, intraday_spec) = bars_1m_read_specs(args);
|
||||
let client = connect_and_validate_specs(
|
||||
with_mongo_client(
|
||||
&args.mongo,
|
||||
&[
|
||||
(SourceCollection::QmSplits, splits_spec.clone()),
|
||||
(SourceCollection::EodIntraday1M, intraday_spec.clone()),
|
||||
],
|
||||
)?;
|
||||
|client| {
|
||||
let use_key_chunks = args.mongo.limit.is_none();
|
||||
let eod_keys = if use_key_chunks {
|
||||
unique_mapping_keys_for_source(&args.provider_mapping_path, &args.mapping_source)
|
||||
.map_err(|e| RunMongoCurateError::Bars1m(RunCurateBars1mError::LoadReference(e)))?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let use_key_chunks = args.mongo.limit.is_none();
|
||||
let eod_keys = if use_key_chunks {
|
||||
unique_mapping_keys_for_source(&args.provider_mapping_path, &args.mapping_source)
|
||||
.map_err(|e| RunMongoCurateError::Bars1m(RunCurateBars1mError::LoadReference(e)))?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let result = {
|
||||
let splits_reader = client
|
||||
.open_raw_cursor(SourceCollection::QmSplits, &splits_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
if use_key_chunks {
|
||||
let intraday_reader = client
|
||||
.open_raw_cursor_for_keys(
|
||||
SourceCollection::EodIntraday1M,
|
||||
&intraday_spec,
|
||||
&eod_keys,
|
||||
250,
|
||||
)
|
||||
let splits_reader = client
|
||||
.open_raw_cursor(SourceCollection::QmSplits, &splits_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_bars_1m_mongo_with_readers(args, intraday_reader, splits_reader)
|
||||
} else {
|
||||
let intraday_reader = client
|
||||
.open_raw_cursor(SourceCollection::EodIntraday1M, &intraday_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_bars_1m_mongo_with_readers(args, intraday_reader, splits_reader)
|
||||
}
|
||||
};
|
||||
|
||||
client.shutdown();
|
||||
result
|
||||
if use_key_chunks {
|
||||
let intraday_reader = client
|
||||
.open_raw_cursor_for_keys(
|
||||
SourceCollection::EodIntraday1M,
|
||||
&intraday_spec,
|
||||
&eod_keys,
|
||||
250,
|
||||
)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_bars_1m_mongo_with_readers(args, intraday_reader, splits_reader)
|
||||
} else {
|
||||
let intraday_reader = client
|
||||
.open_raw_cursor(SourceCollection::EodIntraday1M, &intraday_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_bars_1m_mongo_with_readers(args, intraday_reader, splits_reader)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn qm_bars_1m_read_spec(args: &CurateQmBars1mMongoArgs) -> MongoReadSpec {
|
||||
|
|
@ -961,33 +963,38 @@ pub fn run_curate_qm_bars_1m_mongo(
|
|||
args: &CurateQmBars1mMongoArgs,
|
||||
) -> Result<CurateQmBars1mRunReport, RunMongoCurateError> {
|
||||
let intraday_spec = qm_bars_1m_read_spec(args);
|
||||
let client = connect_and_validate_specs(
|
||||
with_mongo_client(
|
||||
&args.mongo,
|
||||
&[(SourceCollection::QmIntraday, intraday_spec.clone())],
|
||||
)?;
|
||||
|client| {
|
||||
let use_key_chunks = args.mongo.limit.is_none();
|
||||
let qm_keys = if use_key_chunks {
|
||||
unique_mapping_keys_for_source(&args.provider_mapping_path, &args.mapping_source)
|
||||
.map_err(|e| {
|
||||
RunMongoCurateError::QmBars1m(RunCurateQmBars1mError::LoadReference(e))
|
||||
})?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let use_key_chunks = args.mongo.limit.is_none();
|
||||
let qm_keys = if use_key_chunks {
|
||||
unique_mapping_keys_for_source(&args.provider_mapping_path, &args.mapping_source)
|
||||
.map_err(|e| RunMongoCurateError::QmBars1m(RunCurateQmBars1mError::LoadReference(e)))?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let result = if use_key_chunks {
|
||||
let intraday_reader = client
|
||||
.open_raw_cursor_for_keys(SourceCollection::QmIntraday, &intraday_spec, &qm_keys, 250)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_qm_bars_1m_mongo_with_reader(args, intraday_reader)
|
||||
} else {
|
||||
let intraday_reader = client
|
||||
.open_raw_cursor(SourceCollection::QmIntraday, &intraday_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_qm_bars_1m_mongo_with_reader(args, intraday_reader)
|
||||
};
|
||||
|
||||
client.shutdown();
|
||||
result
|
||||
if use_key_chunks {
|
||||
let intraday_reader = client
|
||||
.open_raw_cursor_for_keys(
|
||||
SourceCollection::QmIntraday,
|
||||
&intraday_spec,
|
||||
&qm_keys,
|
||||
250,
|
||||
)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_qm_bars_1m_mongo_with_reader(args, intraday_reader)
|
||||
} else {
|
||||
let intraday_reader = client
|
||||
.open_raw_cursor(SourceCollection::QmIntraday, &intraday_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_qm_bars_1m_mongo_with_reader(args, intraday_reader)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn fx_1m_read_spec(args: &CurateFx1mMongoArgs) -> MongoReadSpec {
|
||||
|
|
@ -1013,20 +1020,16 @@ pub fn run_curate_fx_1m_mongo(
|
|||
args: &CurateFx1mMongoArgs,
|
||||
) -> Result<CurateFx1mRunReport, RunMongoCurateError> {
|
||||
let fx_spec = fx_1m_read_spec(args);
|
||||
let client = connect_and_validate_specs(
|
||||
with_mongo_client(
|
||||
&args.mongo,
|
||||
&[(SourceCollection::EodIntraday1M, fx_spec.clone())],
|
||||
)?;
|
||||
|
||||
let result = {
|
||||
let intraday_reader = client
|
||||
.open_raw_cursor(SourceCollection::EodIntraday1M, &fx_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_fx_1m_mongo_with_reader(args, intraday_reader)
|
||||
};
|
||||
|
||||
client.shutdown();
|
||||
result
|
||||
|client| {
|
||||
let intraday_reader = client
|
||||
.open_raw_cursor(SourceCollection::EodIntraday1M, &fx_spec)
|
||||
.map_err(RunMongoCurateError::Mongo)?;
|
||||
run_curate_fx_1m_mongo_with_reader(args, intraday_reader)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Formats a virtual path label for diagnostics (keeps `Path` import used cleanly).
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
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,
|
||||
|
|
@ -14,9 +16,9 @@ use super::{
|
|||
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, CurateBars1mMongoArgs, CurateFundamentalsMongoArgs,
|
||||
CurateFx1mMongoArgs, CurateMacroMongoArgs, CuratePostsMongoArgs, CurateQmBars1mMongoArgs,
|
||||
RunMongoCurateError,
|
||||
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,
|
||||
|
|
@ -28,8 +30,9 @@ use crate::bson_qm_financials::{
|
|||
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;
|
||||
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,
|
||||
|
|
@ -49,6 +52,8 @@ use crate::run_curate_posts::{
|
|||
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);
|
||||
|
||||
|
|
@ -822,3 +827,943 @@ fn m2_mongo_runners_fail_closed_on_trading_admin_and_unauthenticated_qa_uris() {
|
|||
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 split for NVDA (listing 301) on 2024-06-10; AAPL (listing 302) has no split.
|
||||
let mut sp = RawDocumentBuf::new();
|
||||
sp.append(cstr!("qmSearchCode"), "NVDA:US");
|
||||
sp.append(cstr!("date"), "2024-06-10");
|
||||
sp.append(cstr!("splitratio"), 10.0_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.
|
||||
(
|
||||
"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),
|
||||
),
|
||||
];
|
||||
|
||||
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),
|
||||
),
|
||||
];
|
||||
|
||||
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");
|
||||
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");
|
||||
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!(
|
||||
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).
|
||||
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");
|
||||
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");
|
||||
|
||||
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(), 4);
|
||||
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");
|
||||
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");
|
||||
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!(
|
||||
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");
|
||||
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");
|
||||
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(), 2);
|
||||
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");
|
||||
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");
|
||||
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!(
|
||||
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");
|
||||
run_curate_fx_1m_mongo_with_reader(
|
||||
&fx_reordered_args,
|
||||
CappedRead::new(
|
||||
RawBsonCursorReader::new(VecRawDocumentSource::new(fx_reversed)),
|
||||
7,
|
||||
),
|
||||
)
|
||||
.expect("mongo fx_1m reordered");
|
||||
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"));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue