diff --git a/tools/curate-etl/src/ilp.rs b/tools/curate-etl/src/ilp.rs index 54a5691e..6130adfa 100644 --- a/tools/curate-etl/src/ilp.rs +++ b/tools/curate-etl/src/ilp.rs @@ -458,6 +458,13 @@ impl IlpShardedWriter { self.shards.len() } + /// Returns `(flushed_rows, pending_rows)` across all shards. + #[inline] + pub(crate) fn row_counts(&self) -> (usize, usize) { + let pending = self.shards.iter().map(|s| s.pending_rows).sum(); + (self.rows_written, pending) + } + /// Encodes and buffers one `bars_1m` row on the shard determined by `row.key`. pub fn write_bar_1m( &mut self, diff --git a/tools/curate-etl/src/parquet_publish.rs b/tools/curate-etl/src/parquet_publish.rs index 00d6f1a4..358bbf27 100644 --- a/tools/curate-etl/src/parquet_publish.rs +++ b/tools/curate-etl/src/parquet_publish.rs @@ -310,6 +310,10 @@ impl StagingFileGuard { pub(crate) fn disarm(&mut self) { self.path = None; } + + pub(crate) fn is_armed(&self) -> bool { + self.path.is_some() + } } impl Drop for StagingFileGuard { diff --git a/tools/curate-etl/src/run_curate_bars_1m.rs b/tools/curate-etl/src/run_curate_bars_1m.rs index f30e8e19..2b2a781f 100644 --- a/tools/curate-etl/src/run_curate_bars_1m.rs +++ b/tools/curate-etl/src/run_curate_bars_1m.rs @@ -656,7 +656,7 @@ pub(crate) fn create_exclusive_shard_tmp_file_for_table( pub(crate) fn publish_staged_shards_for_table( out_dir: &Path, table: &str, - mut staged: Vec<(PathBuf, StagingFileGuard)>, + staged: &mut [(PathBuf, StagingFileGuard)], mut before_link: F, ) -> Result<(), ShardPublishError> where @@ -757,7 +757,7 @@ where let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateBars1mError::Ilp)?; let report = stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)?; - publish_staged_shards_for_table(&args.out_dir, TABLE_BARS_1M, staged, before_link)?; + publish_staged_shards_for_table(&args.out_dir, TABLE_BARS_1M, &mut staged, before_link)?; Ok(report) } diff --git a/tools/curate-etl/src/run_curate_fx_1m.rs b/tools/curate-etl/src/run_curate_fx_1m.rs index bda78712..35cb3f3a 100644 --- a/tools/curate-etl/src/run_curate_fx_1m.rs +++ b/tools/curate-etl/src/run_curate_fx_1m.rs @@ -101,6 +101,11 @@ pub enum RunCurateFx1mError { ZeroShardCount, /// Caller-supplied `IlpShardedWriter` shard count did not match `args.shard_count`. ShardCountMismatch { expected: usize, actual: usize }, + /// Caller-supplied `IlpShardedWriter` already had queued or flushed rows before the run. + NonEmptyWriter { + flushed_rows: usize, + pending_rows: usize, + }, /// `out_dir` exists and is not a directory. InvalidOutDir { path: PathBuf, detail: String }, /// A final shard output file (`fx_1m.shard-.ilp`) already existed. @@ -121,7 +126,7 @@ pub enum RunCurateFx1mError { Ilp(IlpWriterError), /// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files. Io { path: PathBuf, source: io::Error }, - /// Publication failed and rolling back one or more already-published shards also failed. + /// Publication or failure cleanup failed and removing one or more final or staging files also failed. RollbackFailed { cause: Box, failures: Vec, @@ -152,6 +157,13 @@ impl fmt::Display for RunCurateFx1mError { f, "ILP writer shard count mismatch: expected {expected}, got {actual}" ), + Self::NonEmptyWriter { + flushed_rows, + pending_rows, + } => write!( + f, + "ILP writer must be fresh before running fx_1m (found {flushed_rows} flushed and {pending_rows} pending rows)" + ), Self::InvalidOutDir { path, detail } => { write!(f, "invalid out_dir '{}': {detail}", path.display()) } @@ -197,6 +209,7 @@ impl Error for RunCurateFx1mError { Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), Self::ZeroShardCount | Self::ShardCountMismatch { .. } + | Self::NonEmptyWriter { .. } | Self::InvalidOutDir { .. } | Self::OutputFileExists { .. } => None, } @@ -266,9 +279,10 @@ where /// Runs the `fx_1m` curation pipeline from an arbitrary [`io::Read`] stream into a caller-owned /// [`IlpShardedWriter`]. /// -/// Validates `args` and writer shard-count agreement, calls [`curate_and_write_fx_1m_from_bson`] -/// once over the entire stream for global sort and `ts` deduplication, and calls -/// [`IlpShardedWriter::finish`] exactly once after clean EOF. +/// Validates `args`, writer shard-count agreement, and that `writer` is fresh (zero queued or +/// flushed rows) before reading `intraday`. Calls [`curate_and_write_fx_1m_from_bson`] once over +/// the entire stream for global sort and `ts` deduplication, and calls [`IlpShardedWriter::finish`] +/// exactly once after clean EOF. pub fn run_curate_fx_1m_with_readers( args: &CurateFx1mArgs, intraday: R, @@ -286,24 +300,91 @@ where actual: writer.shard_count(), }); } + let (flushed_rows, pending_rows) = writer.row_counts(); + if flushed_rows > 0 || pending_rows > 0 { + return Err(RunCurateFx1mError::NonEmptyWriter { + flushed_rows, + pending_rows, + }); + } run_curate_fx_1m_with_readers_inner(args, intraday, writer, start) } -/// Private file-mode seam accepting an injected reader, sink factory, and pre-link hook so tests -/// can exercise staging, writer failure, and post-preflight publication rollback through the exact -/// file publication path. -fn run_curate_fx_1m_to_dir_with_hooks( +fn cleanup_armed_staged_shards( + staged: &mut [(PathBuf, StagingFileGuard)], + remove_file: &mut RF, +) -> Vec +where + RF: FnMut(&Path) -> io::Result<()>, +{ + let mut failures = Vec::new(); + for (tmp_path, guard) in staged.iter_mut() { + if !guard.is_armed() { + continue; + } + match remove_file(tmp_path) { + Ok(()) => guard.disarm(), + Err(err) if err.kind() == io::ErrorKind::NotFound => guard.disarm(), + Err(source) => { + guard.disarm(); + failures.push(RollbackFailure { + final_path: tmp_path.clone(), + backup_path: None, + source, + }); + } + } + } + failures +} + +fn fail_with_staging_cleanup( + cause: RunCurateFx1mError, + staged: &mut [(PathBuf, StagingFileGuard)], + remove_file: &mut RF, +) -> RunCurateFx1mError +where + RF: FnMut(&Path) -> io::Result<()>, +{ + let staging_failures = cleanup_armed_staged_shards(staged, remove_file); + if staging_failures.is_empty() { + return cause; + } + match cause { + RunCurateFx1mError::RollbackFailed { + cause: inner_cause, + mut failures, + } => { + failures.extend(staging_failures); + RunCurateFx1mError::RollbackFailed { + cause: inner_cause, + failures, + } + } + other => RunCurateFx1mError::RollbackFailed { + cause: Box::new(other), + failures: staging_failures, + }, + } +} + +/// Private file-mode seam accepting an injected reader, sink factory, pre-link hook, and staging +/// unlink hook so tests can exercise staging, writer failure, publication rollback, and staging +/// unlink failure reporting deterministically. +fn run_curate_fx_1m_to_dir_with_cleanup_hook( args: &CurateFx1mArgs, intraday: R, mut make_sink: SF, before_link: BL, + mut remove_staged_file: RF, ) -> Result where R: io::Read, W: Write + Send, SF: FnMut(usize, File) -> W, BL: FnMut(usize, &Path), + RF: FnMut(&Path) -> io::Result<()>, { let start = Instant::now(); validate_file_mode_args(args)?; @@ -317,24 +398,84 @@ where let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count); let mut sinks: Vec = Vec::with_capacity(args.shard_count); for shard_idx in 0..args.shard_count { - let (tmp_path, file) = create_exclusive_shard_tmp_file_for_table( + let (tmp_path, file) = match create_exclusive_shard_tmp_file_for_table( &args.out_dir, TABLE_FX_1M, shard_idx, &run_id, - )?; + ) { + Ok(pair) => pair, + Err(err) => { + drop(sinks); + return Err(fail_with_staging_cleanup( + err.into(), + &mut staged, + &mut remove_staged_file, + )); + } + }; let guard = StagingFileGuard::new(tmp_path.clone()); staged.push((tmp_path, guard)); sinks.push(make_sink(shard_idx, file)); } - let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateFx1mError::Ilp)?; - let report = run_curate_fx_1m_with_readers_inner(args, intraday, writer, start)?; + let writer = match IlpShardedWriter::new(sinks, args.ilp_options) { + Ok(writer) => writer, + Err(err) => { + return Err(fail_with_staging_cleanup( + RunCurateFx1mError::Ilp(err), + &mut staged, + &mut remove_staged_file, + )); + } + }; + let report = match run_curate_fx_1m_with_readers_inner(args, intraday, writer, start) { + Ok(report) => report, + Err(err) => { + return Err(fail_with_staging_cleanup( + err, + &mut staged, + &mut remove_staged_file, + )); + } + }; - publish_staged_shards_for_table(&args.out_dir, TABLE_FX_1M, staged, before_link)?; + if let Err(err) = + publish_staged_shards_for_table(&args.out_dir, TABLE_FX_1M, &mut staged, before_link) + { + return Err(fail_with_staging_cleanup( + err.into(), + &mut staged, + &mut remove_staged_file, + )); + } Ok(report) } +/// Private file-mode seam accepting an injected reader, sink factory, and pre-link hook so tests +/// can exercise staging, writer failure, and post-preflight publication rollback through the exact +/// file publication path. +fn run_curate_fx_1m_to_dir_with_hooks( + args: &CurateFx1mArgs, + intraday: R, + make_sink: SF, + before_link: BL, +) -> Result +where + R: io::Read, + W: Write + Send, + SF: FnMut(usize, File) -> W, + BL: FnMut(usize, &Path), +{ + run_curate_fx_1m_to_dir_with_cleanup_hook( + args, + intraday, + make_sink, + before_link, + |path| fs::remove_file(path), + ) +} + /// Runs the file-to-file `fx_1m` curation pipeline, publishing exactly `args.shard_count` QuestDB /// ILP v2 files (`/fx_1m.shard-.ilp`). pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result { diff --git a/tools/curate-etl/src/run_curate_fx_1m_tests.rs b/tools/curate-etl/src/run_curate_fx_1m_tests.rs index 807605dd..16c2db4f 100644 --- a/tools/curate-etl/src/run_curate_fx_1m_tests.rs +++ b/tools/curate-etl/src/run_curate_fx_1m_tests.rs @@ -1102,3 +1102,210 @@ fn format_curate_fx_1m_report_includes_every_counter_and_isolates_timing() { assert!(!line.contains("elapsed_secs"), "timing leaked into: {line}"); } } + +struct PanicOnRead; + +impl io::Read for PanicOnRead { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + panic!("intraday reader must not be read when writer preflight fails"); + } +} + +#[test] +fn with_readers_rejects_preloaded_writer_with_queued_or_flushed_rows_before_reading() { + use crate::bson_eod_intraday::RawEodIntradayBar; + + let make_bar = |ts_sec: i64| RawEodIntradayBar { + eod_search_code: EOD_CAD_FOREX_CODE, + ts: ts_sec * 1_000_000, + open: 1.3700, + high: 1.3710, + low: 1.3690, + close: 1.3705, + volume: 0.0, + }; + + let args = make_args( + PathBuf::from("preloaded-check.bson"), + PathBuf::from("unused-out"), + 1, + BsonStreamOptions::default(), + ); + + // Case 1: queued-only row (buffered, not yet flushed). + { + let mut sink = Vec::new(); + let mut writer = + IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + curate_and_write_fx_1m([make_bar(1_718_500_000)], &mut writer).unwrap(); + + let err = run_curate_fx_1m_with_readers(&args, PanicOnRead, writer).unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::NonEmptyWriter { + flushed_rows: 0, + pending_rows: 1 + } + ), + "{err:?}" + ); + assert!(err.source().is_none()); + let msg = err.to_string(); + assert!(msg.contains("0 flushed") && msg.contains("1 pending"), "{msg}"); + } + + // Case 2: flushed-only row (max_batch_rows = 1 flushes immediately, pending == 0). + { + let mut sink = Vec::new(); + let mut writer = IlpShardedWriter::new( + vec![&mut sink], + IlpWriterOptions { + max_batch_rows: 1, + ..IlpWriterOptions::default() + }, + ) + .unwrap(); + curate_and_write_fx_1m([make_bar(1_718_500_000)], &mut writer).unwrap(); + + let err = run_curate_fx_1m_with_readers(&args, PanicOnRead, writer).unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::NonEmptyWriter { + flushed_rows: 1, + pending_rows: 0 + } + ), + "{err:?}" + ); + } + + // Case 3: both flushed and queued rows (max_batch_rows = 2 with 3 bars -> 2 flushed, 1 pending). + { + let mut sink = Vec::new(); + let mut writer = IlpShardedWriter::new( + vec![&mut sink], + IlpWriterOptions { + max_batch_rows: 2, + ..IlpWriterOptions::default() + }, + ) + .unwrap(); + curate_and_write_fx_1m( + [ + make_bar(1_718_500_000), + make_bar(1_718_500_060), + make_bar(1_718_500_120), + ], + &mut writer, + ) + .unwrap(); + + let err = run_curate_fx_1m_with_readers(&args, PanicOnRead, writer).unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::NonEmptyWriter { + flushed_rows: 2, + pending_rows: 1 + } + ), + "{err:?}" + ); + } +} + +#[test] +fn file_mode_reports_staging_unlink_failures_with_paths_on_flush_error() { + let dir = TempDirGuard::new("fx1m-staging-unlink-fail"); + let valid_doc = + make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_600_000, 1.3700, 1.3710, 1.3690, 1.3705, 0.0); + let out_dir = dir.path().join("out"); + let args = make_args( + dir.path().join("in-memory.bson"), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + ); + + let err = run_curate_fx_1m_to_dir_with_cleanup_hook( + &args, + Cursor::new(concat_docs(&[valid_doc])), + |shard_idx, file| { + if shard_idx == 0 { + Box::new(FailingWriteSink { + fail_on_write: false, + fail_on_flush: true, + }) as Box + } else { + Box::new(SyncedBufFile::new(file)) as Box + } + }, + |_shard_idx, _final_path| {}, + |tmp_path| { + let name = tmp_path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); + if name.starts_with(".fx_1m.shard-01.") { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "injected staging unlink failure", + )) + } else { + fs::remove_file(tmp_path) + } + }, + ) + .unwrap_err(); + + let rendered = err.to_string(); + assert!(err.source().is_some(), "RollbackFailed must expose original cause"); + + match err { + RunCurateFx1mError::RollbackFailed { cause, failures } => { + assert!( + matches!( + cause.as_ref(), + RunCurateFx1mError::Ilp(IlpWriterError::Io { shard: 0, .. }) + ), + "unexpected original cause: {cause:?}" + ); + assert_eq!(failures.len(), 1, "expected 1 staging unlink failure: {failures:?}"); + let failure = &failures[0]; + assert!(failure.backup_path.is_none()); + assert_eq!(failure.source.kind(), io::ErrorKind::PermissionDenied); + + let surviving_name = failure + .final_path + .file_name() + .and_then(|n| n.to_str()) + .expect("staging file name"); + assert!( + surviving_name.starts_with(".fx_1m.shard-01.") && surviving_name.ends_with(".tmp"), + "unexpected surviving staging name: {surviving_name}" + ); + assert!( + failure.final_path.exists(), + "surviving staging file should still exist on disk" + ); + // Shard 0's staging file was cleaned up and zero final shard files were created. + assert_eq!(list_dir_names(&out_dir), vec![surviving_name]); + + assert!( + rendered.contains("injected flush failure"), + "rendered error missing original flush cause: {rendered}" + ); + assert!( + rendered.contains(&failure.final_path.display().to_string()), + "rendered error missing surviving staging path: {rendered}" + ); + assert!( + rendered.contains("injected staging unlink failure"), + "rendered error missing unlink failure detail: {rendered}" + ); + } + other => panic!("expected RollbackFailed, got {other:?}"), + } +}