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