1use chrono::{DateTime, Utc};
32use rand::RngExt;
33use rand_chacha::ChaCha8Rng;
34use serde_yaml_ng::Value;
35
36use crate::diagnostic::DiagnosticBag;
37use crate::generate::registry::{
38 ArgumentSpec, Buffering, ColumnScope, CompileContext, CompiledPlanner, Determinism,
39 PlannerDescriptor, PlannerFactory, PlannerPredicate, PredicateGuard, Verification,
40};
41use crate::generate::seed::StreamId;
42use crate::generate::value::{GenerateError, GeneratedValue};
43use crate::synthetic::model::PlannerConfig;
44use crate::synthetic::schema::{PortableColumn, PortableTable, SqlTypeFamily};
45
46const COMPLETION_BASE_SECS: i64 = 1_704_067_200;
49const COMPLETION_SPAN_SECS: i64 = 30 * 86_400;
50
51pub static WORKFLOW_PROGRESS_COUNTERS_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
53 kind: "workflow.progress_counters",
54 aliases: &[],
55 summary: "Coordinates total/processed/succeeded/failed/pending counters, status, and completion so each row's lifecycle counters agree exactly.",
56 arguments: &[
57 ArgumentSpec {
58 name: "columns",
59 required: true,
60 summary: "Maps total and optional counter, status, and completion roles to columns.",
61 },
62 ArgumentSpec {
63 name: "total",
64 required: false,
65 summary: "Configures the fixed or uniform total-count draw.",
66 },
67 ArgumentSpec {
68 name: "progress",
69 required: false,
70 summary: "Selects a fixed lifecycle state or a weighted state mixture.",
71 },
72 ArgumentSpec {
73 name: "partition",
74 required: false,
75 summary: "Selects exact or allow_unclassified counter partitioning.",
76 },
77 ArgumentSpec {
78 name: "unclassified_ratio",
79 required: false,
80 summary: "Share of processed rows left unclassified under allow_unclassified partitioning.",
81 },
82 ArgumentSpec {
83 name: "success_ratio",
84 required: false,
85 summary: "Share of classified processed rows assigned to succeeded rather than failed.",
86 },
87 ArgumentSpec {
88 name: "completed_statuses",
89 required: false,
90 summary: "Status labels available to completed rows.",
91 },
92 ArgumentSpec {
93 name: "active_statuses",
94 required: false,
95 summary: "Status labels available to active and not-started rows.",
96 },
97 ],
98 writes: ColumnScope::Configured,
99 reads: ColumnScope::None,
100 determinism: Determinism::Deterministic,
101 buffering: Buffering::Streaming,
102 verification: Verification::Supported,
103 cross_table: false,
104};
105
106pub struct ProgressCountersFactory;
108
109impl PlannerFactory for ProgressCountersFactory {
110 fn descriptor(&self) -> &'static PlannerDescriptor {
111 &WORKFLOW_PROGRESS_COUNTERS_DESCRIPTOR
112 }
113
114 fn compile(
115 &self,
116 config: &PlannerConfig,
117 context: &CompileContext<'_>,
118 ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
119 compile_progress(config, context)
120 .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
121 }
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128enum LifecycleState {
129 Complete,
131 Active,
133 NotStarted,
135}
136
137enum StateMix {
139 Fixed(LifecycleState),
141 Weighted {
143 complete: f64,
144 active: f64,
145 not_started: f64,
146 },
147}
148
149impl StateMix {
150 fn select(&self, r: f64) -> LifecycleState {
152 match self {
153 StateMix::Fixed(state) => *state,
154 StateMix::Weighted {
155 complete,
156 active,
157 not_started,
158 } => {
159 let total = complete + active + not_started;
160 let point = r * total;
161 if point < *complete {
162 LifecycleState::Complete
163 } else if point < complete + active {
164 LifecycleState::Active
165 } else {
166 LifecycleState::NotStarted
167 }
168 }
169 }
170 }
171
172 fn reachable(&self) -> (bool, bool, bool) {
174 match self {
175 StateMix::Fixed(LifecycleState::Complete) => (true, false, false),
176 StateMix::Fixed(LifecycleState::Active) => (false, true, false),
177 StateMix::Fixed(LifecycleState::NotStarted) => (false, false, true),
178 StateMix::Weighted {
179 complete,
180 active,
181 not_started,
182 } => (*complete > 0.0, *active > 0.0, *not_started > 0.0),
183 }
184 }
185}
186
187enum TotalDraw {
189 Fixed(i128),
190 Uniform { min: i128, max: i128 },
191}
192
193impl TotalDraw {
194 fn draw(&self, rng: &mut ChaCha8Rng) -> i128 {
195 match self {
196 TotalDraw::Fixed(value) => *value,
197 TotalDraw::Uniform { min, max } => {
198 if max <= min {
199 *min
200 } else {
201 rng.random_range(*min..=*max)
202 }
203 }
204 }
205 }
206
207 fn maximum(&self) -> i128 {
209 match self {
210 TotalDraw::Fixed(value) => *value,
211 TotalDraw::Uniform { max, .. } => *max,
212 }
213 }
214}
215
216#[derive(Clone, Copy)]
218enum Partition {
219 Exact,
221 AllowUnclassified { unclassified_ratio: f64 },
224}
225
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
230enum Role {
231 Total,
232 Processed,
233 Succeeded,
234 Failed,
235 Pending,
236 Status,
237 CompletedAt,
238}
239
240const ROLE_ORDER: [(&str, Role); 7] = [
242 ("total", Role::Total),
243 ("processed", Role::Processed),
244 ("succeeded", Role::Succeeded),
245 ("failed", Role::Failed),
246 ("pending", Role::Pending),
247 ("status", Role::Status),
248 ("completed_at", Role::CompletedAt),
249];
250
251struct Slot {
253 role: Role,
254 name: String,
255 family: SqlTypeFamily,
256}
257
258struct ProgressCountersPlanner {
262 writes: Vec<String>,
264 slots: Vec<Slot>,
265 total_draw: TotalDraw,
266 state_mix: StateMix,
267 partition: Partition,
268 success_ratio: f64,
270 completed_statuses: Vec<String>,
271 active_statuses: Vec<String>,
272 total_rng: ChaCha8Rng,
273 state_rng: ChaCha8Rng,
274 progress_rng: ChaCha8Rng,
275 status_rng: ChaCha8Rng,
276 completion_rng: ChaCha8Rng,
277 predicates: Vec<PlannerPredicate>,
278}
279
280struct RowCounts {
282 total: i128,
283 processed: i128,
284 succeeded: i128,
285 failed: i128,
286 pending: i128,
287 status: String,
288 completed_at: Option<String>,
289}
290
291impl CompiledPlanner for ProgressCountersPlanner {
292 fn writes(&self) -> &[String] {
293 &self.writes
294 }
295
296 fn generate_row(
297 &mut self,
298 _row_index: u64,
299 output: &mut [GeneratedValue],
300 ) -> Result<(), GenerateError> {
301 let counts = self.draw_row();
302 for (slot, cell) in self.slots.iter().zip(output.iter_mut()) {
303 *cell = match slot.role {
304 Role::Total => render_counter(counts.total, &slot.family),
305 Role::Processed => render_counter(counts.processed, &slot.family),
306 Role::Succeeded => render_counter(counts.succeeded, &slot.family),
307 Role::Failed => render_counter(counts.failed, &slot.family),
308 Role::Pending => render_counter(counts.pending, &slot.family),
309 Role::Status => render_status(&counts.status, &slot.family),
310 Role::CompletedAt => match &counts.completed_at {
311 Some(text) => render_datetime(text, &slot.family),
312 None => GeneratedValue::Null,
313 },
314 };
315 }
316 Ok(())
317 }
318
319 fn verification_predicates(&self) -> Vec<PlannerPredicate> {
320 self.predicates.clone()
321 }
322}
323
324impl ProgressCountersPlanner {
325 fn draw_row(&mut self) -> RowCounts {
329 let total = self.total_draw.draw(&mut self.total_rng).max(0);
330 let state_pick = self.state_rng.random::<f64>();
331 let progress_fraction = self.progress_rng.random::<f64>();
332 let status_pick = self.status_rng.random::<f64>();
333 let completion_offset = self.completion_rng.random::<f64>();
334
335 let state = self.state_mix.select(state_pick);
336 let processed = processed_for_state(state, total, progress_fraction);
337 let pending = total - processed;
338 let (succeeded, failed) = self.split_processed(processed);
339
340 let status = match state {
341 LifecycleState::Complete => pick(&self.completed_statuses, status_pick),
342 LifecycleState::Active | LifecycleState::NotStarted => {
343 pick(&self.active_statuses, status_pick)
344 }
345 };
346 let completed_at = match state {
347 LifecycleState::Complete => Some(completion_instant(completion_offset)),
348 _ => None,
349 };
350
351 RowCounts {
352 total,
353 processed,
354 succeeded,
355 failed,
356 pending,
357 status,
358 completed_at,
359 }
360 }
361
362 fn split_processed(&self, processed: i128) -> (i128, i128) {
366 let succeed = self.success_ratio;
367 let fail = 1.0 - self.success_ratio;
368 let parts = match self.partition {
369 Partition::Exact => largest_remainder(processed, &[succeed, fail]),
370 Partition::AllowUnclassified { unclassified_ratio } => {
371 let classified = 1.0 - unclassified_ratio;
372 largest_remainder(
373 processed,
374 &[succeed * classified, fail * classified, unclassified_ratio],
375 )
376 }
377 };
378 (parts[0], parts[1])
379 }
380}
381
382fn processed_for_state(state: LifecycleState, total: i128, progress_fraction: f64) -> i128 {
386 match state {
387 LifecycleState::Complete => total,
388 LifecycleState::NotStarted => 0,
389 LifecycleState::Active => {
390 if total <= 0 {
391 0
392 } else {
393 let raw = (progress_fraction * total as f64).floor() as i128;
394 raw.clamp(0, total - 1)
395 }
396 }
397 }
398}
399
400fn largest_remainder(amount: i128, weights: &[f64]) -> Vec<i128> {
405 let count = weights.len();
406 let weight_total: f64 = weights.iter().sum();
407 if amount <= 0 || weight_total <= 0.0 || !weight_total.is_finite() {
408 return vec![0; count];
409 }
410
411 let mut parts = Vec::with_capacity(count);
412 let mut remainders = Vec::with_capacity(count);
413 let mut allocated: i128 = 0;
414 for &weight in weights {
415 let exact = amount as f64 * (weight.max(0.0) / weight_total);
416 let floor = exact.floor();
417 let whole = floor as i128;
418 parts.push(whole);
419 remainders.push(exact - floor);
420 allocated += whole;
421 }
422
423 let mut leftover = amount - allocated;
426 let mut order: Vec<usize> = (0..count).collect();
427 order.sort_by(|&a, &b| {
428 remainders[b]
429 .partial_cmp(&remainders[a])
430 .unwrap_or(std::cmp::Ordering::Equal)
431 .then(a.cmp(&b))
432 });
433 let mut cursor = 0;
434 while leftover > 0 && !order.is_empty() {
435 parts[order[cursor % count]] += 1;
436 leftover -= 1;
437 cursor += 1;
438 }
439 parts
440}
441
442fn pick(options: &[String], r: f64) -> String {
446 if options.is_empty() {
447 return String::new();
448 }
449 let index = ((r * options.len() as f64).floor() as usize).min(options.len() - 1);
450 options[index].clone()
451}
452
453fn completion_instant(offset: f64) -> String {
455 let extra = (offset * COMPLETION_SPAN_SECS as f64).floor() as i64;
456 let secs = COMPLETION_BASE_SECS.saturating_add(extra);
457 DateTime::<Utc>::from_timestamp(secs, 0)
458 .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
459 .unwrap_or_default()
460}
461
462fn render_counter(value: i128, family: &SqlTypeFamily) -> GeneratedValue {
466 match family {
467 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => GeneratedValue::Integer(value),
468 SqlTypeFamily::Decimal => GeneratedValue::Decimal {
469 minor: value,
470 scale: 0,
471 },
472 _ => GeneratedValue::Text(value.to_string()),
473 }
474}
475
476fn render_status(status: &str, family: &SqlTypeFamily) -> GeneratedValue {
478 match family {
479 SqlTypeFamily::Text | SqlTypeFamily::Uuid | SqlTypeFamily::Other => {
480 GeneratedValue::Text(status.to_string())
481 }
482 _ => GeneratedValue::Text(status.to_string()),
483 }
484}
485
486fn render_datetime(text: &str, family: &SqlTypeFamily) -> GeneratedValue {
488 match family {
489 SqlTypeFamily::DateTime => GeneratedValue::DateTime(text.to_string()),
490 _ => GeneratedValue::Text(text.to_string()),
491 }
492}
493
494fn compile_progress(
499 config: &PlannerConfig,
500 context: &CompileContext<'_>,
501) -> Result<ProgressCountersPlanner, DiagnosticBag> {
502 let mut bag = DiagnosticBag::default();
503 let table = context.table();
504 let path = context.path();
505
506 let columns = config.args.get("columns");
507 let slots = resolve_slots(columns, table, path, &mut bag);
508 let total_draw = compile_total(config.args.get("total"), path, &mut bag);
509 let partition = compile_partition(config, path, &mut bag);
510 let state_mix = compile_state(config.args.get("progress"), partition, path, &mut bag);
511 let success_ratio = config
512 .args
513 .get("success_ratio")
514 .and_then(as_f64)
515 .unwrap_or(0.9)
516 .clamp(0.0, 1.0);
517 let completed_statuses = string_list(config.args.get("completed_statuses"));
518 let active_statuses = string_list(config.args.get("active_statuses"));
519
520 let has_role = |role: Role| slots.iter().any(|slot| slot.role == role);
522 let (complete_reachable, active_reachable, not_started_reachable) = state_mix
523 .as_ref()
524 .map_or((false, false, false), StateMix::reachable);
525
526 if let Some(draw) = &total_draw {
528 let maximum = draw.maximum();
529 for slot in &slots {
530 if is_counter(slot.role) {
531 let capacity = family_capacity(&slot.family);
532 if maximum > capacity {
533 bag.error(
534 crate::diagnostic::codes::PROGRESS_OVERFLOW.code,
535 format!("{path}.total"),
536 format!(
537 "workflow.progress_counters `total` can reach {maximum}, exceeding the capacity {capacity} of counter column `{}`",
538 slot.name
539 ),
540 );
541 }
542 }
543 }
544 }
545
546 if has_role(Role::Status) {
549 if complete_reachable && completed_statuses.is_empty() {
550 bag.error(
551 crate::diagnostic::codes::PROGRESS_STATUS_VOCABULARY.code,
552 format!("{path}.completed_statuses"),
553 "workflow.progress_counters produces completed rows but `completed_statuses` is empty; supply at least one completed status".to_string(),
554 );
555 }
556 if (active_reachable || not_started_reachable) && active_statuses.is_empty() {
557 bag.error(
558 crate::diagnostic::codes::PROGRESS_STATUS_VOCABULARY.code,
559 format!("{path}.active_statuses"),
560 "workflow.progress_counters produces active or not-started rows but `active_statuses` is empty; supply at least one active status".to_string(),
561 );
562 }
563 if let Some(shared) = completed_statuses
567 .iter()
568 .find(|status| active_statuses.contains(status))
569 {
570 bag.error(
571 crate::diagnostic::codes::PROGRESS_STATUS_VOCABULARY.code,
572 format!("{path}.active_statuses"),
573 format!(
574 "workflow.progress_counters status `{shared}` appears in both `completed_statuses` and `active_statuses`; a status must belong to only one lifecycle group"
575 ),
576 );
577 }
578 }
579
580 if let Some(slot) = slots.iter().find(|slot| slot.role == Role::CompletedAt) {
583 if (active_reachable || not_started_reachable) && !column_nullable(table, &slot.name) {
584 bag.error(
585 crate::diagnostic::codes::PROGRESS_COMPLETION.code,
586 format!("{path}.columns.completed_at"),
587 format!(
588 "workflow.progress_counters `completed_at` column `{}` is not nullable, but active and not-started rows leave completion null",
589 slot.name
590 ),
591 );
592 }
593 }
594
595 if bag.has_errors() {
596 return Err(bag);
597 }
598
599 let total_draw = total_draw.expect("total resolved without errors");
600 let state_mix = state_mix.expect("state resolved without errors");
601
602 let writes = slots.iter().map(|slot| slot.name.clone()).collect();
603 let (total_rng, state_rng, progress_rng, status_rng, completion_rng) = build_streams(context);
604 let predicates = build_predicates(&slots, partition, &completed_statuses, &active_statuses);
605
606 Ok(ProgressCountersPlanner {
607 writes,
608 slots,
609 total_draw,
610 state_mix,
611 partition,
612 success_ratio,
613 completed_statuses,
614 active_statuses,
615 total_rng,
616 state_rng,
617 progress_rng,
618 status_rng,
619 completion_rng,
620 predicates,
621 })
622}
623
624fn resolve_slots(
627 columns: Option<&Value>,
628 table: &PortableTable,
629 path: &str,
630 bag: &mut DiagnosticBag,
631) -> Vec<Slot> {
632 let mut slots = Vec::new();
633 for (role_key, role) in ROLE_ORDER {
634 let Some(name) = role_name(columns, role_key) else {
635 if role == Role::Total {
636 bag.error(
637 crate::diagnostic::codes::PROGRESS_COLUMN_MISSING.code,
638 format!("{path}.columns.total"),
639 "workflow.progress_counters requires a `total` column under `columns`"
640 .to_string(),
641 );
642 }
643 continue;
644 };
645 match find_column(table, name) {
646 Some(column) => slots.push(Slot {
647 role,
648 name: column.name.clone(),
649 family: column.family.clone(),
650 }),
651 None => {
652 bag.error(
653 crate::diagnostic::codes::PROGRESS_COLUMN_MISSING.code,
654 format!("{path}.columns.{role_key}"),
655 format!(
656 "workflow.progress_counters `{role_key}` column `{name}` does not exist on table `{}`",
657 table.name
658 ),
659 );
660 }
661 }
662 }
663 slots
664}
665
666fn compile_total(total: Option<&Value>, path: &str, bag: &mut DiagnosticBag) -> Option<TotalDraw> {
669 let kind = total.and_then(|t| t.get("kind")).and_then(Value::as_str);
670 let field = |key: &str| total.and_then(|t| t.get(key)).and_then(as_i128);
671
672 let draw = match kind {
673 Some("fixed") => {
674 let value = field("value").unwrap_or(0);
675 if value < 0 {
676 bag.error(
677 crate::diagnostic::codes::PROGRESS_TOTAL.code,
678 format!("{path}.total.value"),
679 format!("workflow.progress_counters `total.value` `{value}` is negative"),
680 );
681 return None;
682 }
683 TotalDraw::Fixed(value)
684 }
685 _ => {
687 let min = field("min").unwrap_or(0);
688 let max = field("max").unwrap_or(min);
689 if min < 0 {
690 bag.error(
691 crate::diagnostic::codes::PROGRESS_TOTAL.code,
692 format!("{path}.total.min"),
693 format!("workflow.progress_counters `total.min` `{min}` is negative"),
694 );
695 return None;
696 }
697 if max < min {
698 bag.error(
699 crate::diagnostic::codes::PROGRESS_TOTAL.code,
700 format!("{path}.total"),
701 "workflow.progress_counters `total.max` is below `total.min`".to_string(),
702 );
703 return None;
704 }
705 TotalDraw::Uniform { min, max }
706 }
707 };
708 Some(draw)
709}
710
711fn compile_partition(config: &PlannerConfig, path: &str, bag: &mut DiagnosticBag) -> Partition {
713 match config.args.get("partition").and_then(Value::as_str) {
714 Some("allow_unclassified") => {
715 let unclassified_ratio = config
716 .args
717 .get("unclassified_ratio")
718 .and_then(as_f64)
719 .unwrap_or(0.1)
720 .clamp(0.0, 1.0);
721 Partition::AllowUnclassified { unclassified_ratio }
722 }
723 Some("exact") | None => Partition::Exact,
724 Some(other) => {
725 bag.error(
726 crate::diagnostic::codes::PROGRESS_PARTITION.code,
727 format!("{path}.partition"),
728 format!(
729 "workflow.progress_counters `partition` `{other}` is not one of `exact` or `allow_unclassified`"
730 ),
731 );
732 Partition::Exact
733 }
734 }
735}
736
737fn compile_state(
741 progress: Option<&Value>,
742 partition: Partition,
743 path: &str,
744 bag: &mut DiagnosticBag,
745) -> Option<StateMix> {
746 let kind = progress
747 .and_then(|p| p.get("kind"))
748 .and_then(Value::as_str)
749 .unwrap_or("mixture");
750
751 match kind {
752 "complete" => Some(StateMix::Fixed(LifecycleState::Complete)),
753 "in_progress" => Some(StateMix::Fixed(LifecycleState::Active)),
754 "not_started" => Some(StateMix::Fixed(LifecycleState::NotStarted)),
755 "observed" => {
756 if let Partition::Exact = partition {
761 bag.error(
762 crate::diagnostic::codes::PROGRESS_OBSERVED.code,
763 format!("{path}.progress"),
764 "workflow.progress_counters `progress.kind: observed` needs observed evidence to form an exact partition, but none is available; supply explicit mixture weights or use `partition: allow_unclassified`".to_string(),
765 );
766 None
767 } else {
768 Some(default_mixture())
769 }
770 }
771 _ => compile_mixture(progress, path, bag),
773 }
774}
775
776fn default_mixture() -> StateMix {
778 StateMix::Weighted {
779 complete: 0.7,
780 active: 0.25,
781 not_started: 0.05,
782 }
783}
784
785fn compile_mixture(
788 progress: Option<&Value>,
789 path: &str,
790 bag: &mut DiagnosticBag,
791) -> Option<StateMix> {
792 let weight = |key: &str| progress.and_then(|p| p.get(key)).and_then(as_f64);
793 let complete = weight("complete_weight");
794 let active = weight("active_weight");
795 let not_started = weight("not_started_weight");
796
797 let (complete, active, not_started) =
800 if complete.is_none() && active.is_none() && not_started.is_none() {
801 (1.0, 1.0, 1.0)
802 } else {
803 (
804 complete.unwrap_or(0.0),
805 active.unwrap_or(0.0),
806 not_started.unwrap_or(0.0),
807 )
808 };
809
810 let weights = [complete, active, not_started];
811 if weights.iter().any(|w| !w.is_finite() || *w < 0.0) {
812 bag.error(
813 crate::diagnostic::codes::PROGRESS_WEIGHTS.code,
814 format!("{path}.progress"),
815 "workflow.progress_counters mixture weights must be finite and non-negative"
816 .to_string(),
817 );
818 return None;
819 }
820 let total: f64 = weights.iter().sum();
821 if total <= 0.0 {
822 bag.error(
823 crate::diagnostic::codes::PROGRESS_WEIGHTS.code,
824 format!("{path}.progress"),
825 "workflow.progress_counters mixture weights sum to zero; at least one weight must be positive".to_string(),
826 );
827 return None;
828 }
829
830 Some(StateMix::Weighted {
831 complete,
832 active,
833 not_started,
834 })
835}
836
837fn build_streams(
840 context: &CompileContext<'_>,
841) -> (ChaCha8Rng, ChaCha8Rng, ChaCha8Rng, ChaCha8Rng, ChaCha8Rng) {
842 let table = context.table().name.as_str();
843 let stream = |suffix: &str| {
844 context.rng(StreamId::operator(
845 table,
846 "workflow.progress_counters",
847 format!("workflow.progress_counters.{suffix}"),
848 ))
849 };
850 (
851 stream("total"),
852 stream("state"),
853 stream("progress"),
854 stream("status"),
855 stream("completion"),
856 )
857}
858
859fn build_predicates(
861 slots: &[Slot],
862 partition: Partition,
863 completed_statuses: &[String],
864 active_statuses: &[String],
865) -> Vec<PlannerPredicate> {
866 let name_of = |role: Role| {
867 slots
868 .iter()
869 .find(|slot| slot.role == role)
870 .map(|slot| slot.name.clone())
871 };
872 let mut predicates = Vec::new();
873
874 let total = name_of(Role::Total);
875 let processed = name_of(Role::Processed);
876 let succeeded = name_of(Role::Succeeded);
877 let failed = name_of(Role::Failed);
878 let pending = name_of(Role::Pending);
879 let status = name_of(Role::Status);
880 let completed_at = name_of(Role::CompletedAt);
881
882 if let (Partition::Exact, Some(processed), Some(succeeded), Some(failed)) =
884 (partition, &processed, &succeeded, &failed)
885 {
886 predicates.push(PlannerPredicate::CounterSum {
887 addends: vec![succeeded.clone(), failed.clone()],
888 sum: processed.clone(),
889 guard: None,
890 });
891 }
892
893 if let (Some(total), Some(processed), Some(pending)) = (&total, &processed, &pending) {
895 predicates.push(PlannerPredicate::CounterSum {
896 addends: vec![processed.clone(), pending.clone()],
897 sum: total.clone(),
898 guard: None,
899 });
900 }
901
902 let counters: Vec<String> = slots
904 .iter()
905 .filter(|slot| is_counter(slot.role))
906 .map(|slot| slot.name.clone())
907 .collect();
908 if !counters.is_empty() {
909 predicates.push(PlannerPredicate::NonNegative { columns: counters });
910 }
911
912 if let Some(status) = &status {
916 if let (Some(total), Some(processed)) = (&total, &processed) {
917 for value in completed_statuses {
918 predicates.push(PlannerPredicate::CounterSum {
919 addends: vec![processed.clone()],
920 sum: total.clone(),
921 guard: Some(PredicateGuard::Equals {
922 column: status.clone(),
923 value: value.clone(),
924 }),
925 });
926 }
927 }
928 if let Some(completed_at) = &completed_at {
929 for value in completed_statuses {
930 predicates.push(PlannerPredicate::NotNullWhen {
931 column: completed_at.clone(),
932 guard: PredicateGuard::Equals {
933 column: status.clone(),
934 value: value.clone(),
935 },
936 });
937 }
938 for value in active_statuses {
939 predicates.push(PlannerPredicate::NullWhen {
940 column: completed_at.clone(),
941 guard: PredicateGuard::Equals {
942 column: status.clone(),
943 value: value.clone(),
944 },
945 });
946 }
947 }
948 }
949
950 predicates
951}
952
953fn is_counter(role: Role) -> bool {
957 matches!(
958 role,
959 Role::Total | Role::Processed | Role::Succeeded | Role::Failed | Role::Pending
960 )
961}
962
963fn family_capacity(family: &SqlTypeFamily) -> i128 {
965 match family {
966 SqlTypeFamily::Integer => i32::MAX as i128,
967 SqlTypeFamily::BigInteger => i64::MAX as i128,
968 _ => i128::MAX,
969 }
970}
971
972fn role_name<'a>(columns: Option<&'a Value>, role: &str) -> Option<&'a str> {
974 columns?.get(role).and_then(Value::as_str)
975}
976
977fn find_column<'a>(table: &'a PortableTable, name: &str) -> Option<&'a PortableColumn> {
978 table.columns.iter().find(|column| column.name == name)
979}
980
981fn column_nullable(table: &PortableTable, name: &str) -> bool {
982 find_column(table, name).is_some_and(|column| column.nullable)
983}
984
985fn string_list(value: Option<&Value>) -> Vec<String> {
987 match value {
988 Some(Value::Sequence(items)) => items
989 .iter()
990 .filter_map(Value::as_str)
991 .map(str::to_string)
992 .collect(),
993 _ => Vec::new(),
994 }
995}
996
997fn as_i128(value: &Value) -> Option<i128> {
998 match value {
999 Value::Number(number) => number
1000 .as_i64()
1001 .map(i128::from)
1002 .or_else(|| number.as_u64().map(i128::from))
1003 .or_else(|| number.as_f64().map(|float| float as i128)),
1004 Value::String(text) => text.trim().parse::<i128>().ok(),
1005 _ => None,
1006 }
1007}
1008
1009fn as_f64(value: &Value) -> Option<f64> {
1010 match value {
1011 Value::Number(number) => number.as_f64(),
1012 Value::String(text) => text.trim().parse::<f64>().ok(),
1013 _ => None,
1014 }
1015}