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