1mod aggregate;
10mod apply_cmd;
11mod cdc_job;
12pub(crate) mod chunked;
13mod cli;
14pub(crate) mod commit;
15mod finalize;
16pub(crate) mod ipc;
17mod job;
18mod keyset;
19mod manifest_reconcile;
20pub(crate) mod manifest_writer;
21mod parallel_children;
22pub(crate) mod parent_ui;
23mod partition_expand;
24mod plan_cmd;
25pub(crate) mod progress;
26mod reconcile_cmd;
27mod repair_cmd;
28pub(crate) mod report;
29mod resume_decisions;
30pub(crate) mod retry;
33mod run;
39mod run_store;
40mod schema_drift;
41mod single;
42mod sink;
43mod summary;
44mod validate;
45mod validate_cmd;
46mod validate_manifest;
47
48pub use apply_cmd::run_apply_command;
55pub use cli::{
56 reset_chunk_checkpoint, reset_chunk_checkpoints_stuck, reset_state, show_chunk_checkpoint,
57 show_files, show_journal, show_metrics, show_progression, show_state,
58};
59pub use plan_cmd::{PlanOutputFormat, run_plan_command};
60pub use reconcile_cmd::{ReconcileOutputFormat, run_reconcile_command};
61pub use repair_cmd::{RepairOutputFormat, RepairReportSource, run_repair_command};
62pub use validate_cmd::{ValidateOutputFormat, ValidateTarget, run_validate_command};
63
64pub use summary::RunSummary;
68
69pub(crate) use job::run_export_job_with_chunk_source;
72#[cfg(test)]
73#[allow(unused_imports)]
74pub(crate) use retry::is_transient;
75
76#[doc(hidden)]
91pub mod for_tests {
92 pub use super::chunked::generate_chunks;
93 pub use super::manifest_writer::{ManifestBuilder, WriteOutcome, write_manifest};
94 pub use super::report::{RunReport, report_dir, write_run_report};
95 pub use super::resume_decisions::{
96 PartDecision, QuarantineReason, ResumeDecision, ResumePlan, UntrackedDecision,
97 build_resume_plan,
98 };
99 pub use super::retry::{RetryClass, classify_error};
100 pub use super::validate::validate_output;
101 pub use super::validate_manifest::{
102 Failure as ManifestVerificationFailure, ManifestVerification, verify_at_destination,
103 };
104 pub use crate::plan::build_time_window_query;
105}
106
107#[doc(hidden)]
115#[allow(unused_imports)]
116pub use for_tests::{
117 ManifestBuilder, ManifestVerification, ManifestVerificationFailure, PartDecision,
118 QuarantineReason, ResumeDecision, ResumePlan, RetryClass, RunReport, UntrackedDecision,
119 WriteOutcome, build_resume_plan, build_time_window_query, classify_error, generate_chunks,
120 report_dir, validate_output, verify_at_destination, write_manifest, write_run_report,
121};
122
123pub use run::{RunOptions, run};
128#[allow(unused_imports)] pub(crate) use run::{multi_export_concurrent, multi_export_mode};
130
131pub(crate) fn format_bytes(b: u64) -> String {
132 if b >= 1_073_741_824 {
133 format!("{:.1} GB", b as f64 / 1_073_741_824.0)
134 } else if b >= 1_048_576 {
135 format!("{:.1} MB", b as f64 / 1_048_576.0)
136 } else if b >= 1024 {
137 format!("{:.1} KB", b as f64 / 1024.0)
138 } else {
139 format!("{} B", b)
140 }
141}
142
143pub(crate) fn strip_chunked_recovery_hint(msg: &str) -> (&str, bool) {
156 let mut pos = 0;
157 while let Some(off) = msg[pos..].find("; ") {
158 let abs = pos + off;
159 let tail = &msg[abs + 2..];
160 if tail.contains("`rivet ") {
161 return (&msg[..abs], true);
162 }
163 pos = abs + 2;
164 }
165 (msg, false)
166}
167
168pub(crate) fn clamp_line(s: &str, max_chars: usize) -> String {
174 if max_chars == 0 {
175 return String::new();
176 }
177 if s.chars().count() <= max_chars {
178 return s.to_string();
179 }
180 let keep = max_chars.saturating_sub(1);
181 let mut out: String = s.chars().take(keep).collect();
182 out.push('…');
183 out
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189 use crate::config::{SourceConfig, SourceType};
190 use crate::plan::{
191 CompressionType, DestinationConfig, DestinationType, DiagnosticLevel, ExtractionStrategy,
192 FormatType, MetaColumns, ResolvedRunPlan, validate_plan,
193 };
194 use crate::tuning::SourceTuning;
195
196 #[test]
197 fn test_format_bytes() {
198 assert_eq!(format_bytes(500), "500 B");
199 assert_eq!(format_bytes(1024), "1.0 KB");
200 assert_eq!(format_bytes(1536), "1.5 KB");
201 assert_eq!(format_bytes(1_048_576), "1.0 MB");
202 assert_eq!(format_bytes(1_073_741_824), "1.0 GB");
203 assert_eq!(format_bytes(2_684_354_560), "2.5 GB");
204 }
205
206 #[test]
207 fn strip_chunked_recovery_hint_strips_use_form() {
208 let m = "export 'users': chunk checkpoint run 'users_x' still in progress; \
209 use `rivet run --config foo.yaml --export users --resume` or \
210 `rivet state reset-chunks --config foo.yaml --export users`";
211 let (cause, hinted) = strip_chunked_recovery_hint(m);
212 assert!(hinted);
213 assert_eq!(
214 cause,
215 "export 'users': chunk checkpoint run 'users_x' still in progress"
216 );
217 }
218
219 #[test]
220 fn strip_chunked_recovery_hint_strips_fix_errors_form() {
221 let m = "export 'a': chunk checkpoint incomplete (3 tasks not completed); \
222 fix errors and `rivet run --config c.yaml --export a --resume` or \
223 `rivet state reset-chunks --config c.yaml --export a`";
224 let (cause, hinted) = strip_chunked_recovery_hint(m);
225 assert!(hinted);
226 assert_eq!(
227 cause,
228 "export 'a': chunk checkpoint incomplete (3 tasks not completed)"
229 );
230 }
231
232 #[test]
233 fn strip_chunked_recovery_hint_passthrough_when_no_hint() {
234 let m = "export 'q': source connection refused; retry exhausted";
235 let (cause, hinted) = strip_chunked_recovery_hint(m);
236 assert!(!hinted);
237 assert_eq!(cause, m);
238 }
239
240 #[test]
241 fn clamp_line_truncates_with_ellipsis() {
242 assert_eq!(clamp_line("short", 80), "short");
243 assert_eq!(clamp_line("hello world", 8), "hello w…");
244 let s = "αβγδ".repeat(50);
245 let out = clamp_line(&s, 10);
246 assert_eq!(out.chars().count(), 10);
247 assert!(out.ends_with('…'));
248 }
249
250 #[test]
251 fn format_bytes_boundary_values() {
252 assert_eq!(format_bytes(0), "0 B");
253 assert_eq!(format_bytes(1), "1 B");
254 assert_eq!(format_bytes(1023), "1023 B");
255 assert_eq!(format_bytes(1024), "1.0 KB");
256 assert_eq!(format_bytes(1025), "1.0 KB");
257 assert_eq!(format_bytes(1_048_575), "1024.0 KB");
258 assert_eq!(format_bytes(1_048_576), "1.0 MB");
259 assert_eq!(format_bytes(1_073_741_823), "1024.0 MB");
260 assert_eq!(format_bytes(1_073_741_824), "1.0 GB");
261 }
262
263 fn minimal_plan() -> ResolvedRunPlan {
264 ResolvedRunPlan {
265 export_name: "test_export".into(),
266 base_query: "SELECT 1".into(),
267 strategy: ExtractionStrategy::Snapshot,
268 format: FormatType::Parquet,
269 compression: CompressionType::default(),
270 compression_level: None,
271 max_file_size_bytes: None,
272 skip_empty: false,
273 meta_columns: MetaColumns::default(),
274 destination: DestinationConfig {
275 destination_type: DestinationType::Local,
276 path: Some("./out".into()),
277 ..Default::default()
278 },
279 quality: None,
280 tuning: SourceTuning::from_config(None),
281 tuning_profile_label: "balanced (default)".into(),
282 validate: false,
283 reconcile: false,
284 resume: false,
285 source: SourceConfig {
286 source_type: SourceType::Postgres,
287 url: Some("postgresql://localhost/test".into()),
288 url_env: None,
289 url_file: None,
290 host: None,
291 port: None,
292 user: None,
293 password: None,
294 password_env: None,
295 database: None,
296 environment: None,
297 tuning: None,
298 tls: None,
299 },
300 column_overrides: Default::default(),
301 verify: crate::config::VerifyMode::Size,
302 schema_drift_policy: Default::default(),
303 shape_drift_warn_factor: 2.0,
304 parquet: None,
305 }
306 }
307
308 #[test]
309 fn test_run_summary_fields() {
310 let plan = minimal_plan();
311 let summary = RunSummary::new(&plan);
312 assert_eq!(summary.export_name, "test_export");
313 assert_eq!(summary.status, "running");
314 assert_eq!(summary.total_rows, 0);
315 assert_eq!(summary.files_produced, 0);
316 assert_eq!(summary.tuning_profile, "balanced (default)");
317 assert_eq!(summary.batch_size, 10_000);
318 assert_eq!(summary.format, "parquet");
319 assert_eq!(summary.mode, "full");
320 assert!(
321 summary.run_id.starts_with("test_export_"),
322 "run_id should start with export name, got: {}",
323 summary.run_id
324 );
325 }
326
327 #[test]
332 fn run_summary_new_records_plan_resolved_as_first_event() {
333 let plan = minimal_plan();
334 let summary = RunSummary::new(&plan);
335
336 assert!(
337 !summary.journal.entries.is_empty(),
338 "journal must have at least one entry after RunSummary::new()"
339 );
340 assert!(
341 matches!(
342 summary.journal.entries[0].event,
343 crate::journal::RunEvent::PlanResolved(_)
344 ),
345 "first journal event must be PlanResolved, got: {:?}",
346 summary.journal.entries[0].event
347 );
348 }
349
350 #[test]
353 fn run_summary_plan_snapshot_matches_plan_fields() {
354 let plan = minimal_plan();
355 let summary = RunSummary::new(&plan);
356
357 let snap = summary
358 .journal
359 .plan_snapshot()
360 .expect("plan_snapshot() must be Some after RunSummary::new()");
361
362 assert_eq!(snap.export_name, plan.export_name);
363 assert_eq!(snap.validate, plan.validate);
364 assert_eq!(snap.reconcile, plan.reconcile);
365 assert_eq!(snap.resume, plan.resume);
366 assert_eq!(snap.batch_size, plan.tuning.batch_size);
367 }
368
369 #[test]
371 fn run_summary_journal_run_id_matches_summary_run_id() {
372 let plan = minimal_plan();
373 let summary = RunSummary::new(&plan);
374 assert_eq!(
375 summary.journal.run_id, summary.run_id,
376 "journal run_id must match summary run_id"
377 );
378 }
379
380 #[test]
391 fn rejected_plan_produces_rejected_diagnostic_blocking_run_export_job() {
392 let mut plan = minimal_plan();
393 plan.destination.destination_type = DestinationType::Stdout;
395 plan.max_file_size_bytes = Some(10 * 1024 * 1024);
396
397 let diags = validate_plan(&plan);
398 let rejected_count = diags
399 .iter()
400 .filter(|d| d.level == DiagnosticLevel::Rejected)
401 .count();
402
403 assert!(
404 rejected_count > 0,
405 "stdout + max_file_size must produce a Rejected diagnostic so that \
406 run_export_job bails before calling run_with_reconnect; got: {:?}",
407 diags
408 .iter()
409 .map(|d| (&d.rule, &d.level))
410 .collect::<Vec<_>>()
411 );
412 }
413
414 #[test]
416 fn rejected_plan_stdout_chunked_blocks_run_export_job() {
417 use crate::plan::ChunkedPlan;
418 let mut plan = minimal_plan();
419 plan.destination.destination_type = DestinationType::Stdout;
420 plan.strategy = ExtractionStrategy::Chunked(ChunkedPlan {
421 column: "id".into(),
422 chunk_size: 1000,
423 chunk_count: None,
424 parallel: 1,
425 dense: false,
426 by_days: None,
427 max_attempts: 3,
428 checkpoint: false,
429 });
430
431 let diags = validate_plan(&plan);
432 assert!(
433 diags.iter().any(|d| d.level == DiagnosticLevel::Rejected),
434 "stdout + chunked must produce a Rejected diagnostic"
435 );
436 }
437
438 #[test]
445 fn synthetic_failed_summary_carries_error_and_status() {
446 let err = anyhow::anyhow!("could not connect to source: timeout");
447 let s = job::synthetic_failed_summary("orders", &err);
448 assert_eq!(s.export_name, "orders");
449 assert_eq!(s.status, "failed");
450 assert_eq!(
451 s.error_message.as_deref(),
452 Some("could not connect to source: timeout")
453 );
454 assert!(
455 s.run_id.starts_with("orders_"),
456 "run_id must be derived from export name, got {}",
457 s.run_id
458 );
459 assert_eq!(s.total_rows, 0);
461 assert_eq!(s.files_produced, 0);
462 assert_eq!(s.bytes_written, 0);
463 assert_eq!(s.duration_ms, 0);
464 }
465
466 #[test]
470 fn aggregate_entry_from_summary_copies_observable_fields() {
471 let plan = minimal_plan();
472 let mut summary = RunSummary::new(&plan);
473 summary.status = "success".into();
474 summary.total_rows = 12_345;
475 summary.files_produced = 3;
476 summary.bytes_written = 9_876_543;
477 summary.duration_ms = 5_000;
478
479 let entry = aggregate::entry_from_summary(&summary);
480 assert_eq!(entry.export_name, summary.export_name);
481 assert_eq!(entry.status, "success");
482 assert_eq!(entry.run_id, summary.run_id);
483 assert_eq!(entry.rows, 12_345);
484 assert_eq!(entry.files, 3);
485 assert_eq!(entry.bytes, 9_876_543);
486 assert_eq!(entry.duration_ms, 5_000);
487 assert_eq!(entry.mode, summary.mode);
488 assert_eq!(entry.error_message, None);
489 }
490}