1use std::collections::HashMap;
49use std::sync::atomic::{AtomicU64, Ordering};
50use std::sync::{Arc, RwLock};
51
52use super::chunk::DataChunk;
53use super::operators::OperatorError;
54use super::pipeline::{ChunkSizeHint, PushOperator, Sink};
55
56pub const DEFAULT_REOPTIMIZATION_THRESHOLD: f64 = 3.0;
59
60pub const MIN_ROWS_FOR_REOPTIMIZATION: u64 = 1000;
63
64#[derive(Debug, Clone)]
66pub struct CardinalityCheckpoint {
67 pub operator_id: String,
69 pub estimated: f64,
71 pub actual: u64,
73 pub recorded: bool,
75}
76
77impl CardinalityCheckpoint {
78 #[must_use]
80 pub fn new(operator_id: &str, estimated: f64) -> Self {
81 Self {
82 operator_id: operator_id.to_string(),
83 estimated,
84 actual: 0,
85 recorded: false,
86 }
87 }
88
89 pub fn record(&mut self, actual: u64) {
91 self.actual = actual;
92 self.recorded = true;
93 }
94
95 #[must_use]
100 pub fn deviation_ratio(&self) -> f64 {
101 if self.estimated <= 0.0 {
102 return if self.actual == 0 { 1.0 } else { f64::INFINITY };
103 }
104 self.actual as f64 / self.estimated
105 }
106
107 #[must_use]
109 pub fn absolute_deviation(&self) -> f64 {
110 (self.actual as f64 - self.estimated).abs()
111 }
112
113 #[must_use]
115 pub fn is_significant_deviation(&self, threshold: f64) -> bool {
116 if !self.recorded {
117 return false;
118 }
119 let ratio = self.deviation_ratio();
120 ratio > threshold || ratio < 1.0 / threshold
121 }
122}
123
124#[derive(Debug, Default)]
129pub struct CardinalityFeedback {
130 actuals: HashMap<String, u64>,
132 running_counts: HashMap<String, AtomicU64>,
134}
135
136impl CardinalityFeedback {
137 #[must_use]
139 pub fn new() -> Self {
140 Self {
141 actuals: HashMap::new(),
142 running_counts: HashMap::new(),
143 }
144 }
145
146 pub fn record(&mut self, operator_id: &str, count: u64) {
148 self.actuals.insert(operator_id.to_string(), count);
149 }
150
151 pub fn add_rows(&self, operator_id: &str, count: u64) {
153 if let Some(counter) = self.running_counts.get(operator_id) {
154 counter.fetch_add(count, Ordering::Relaxed);
155 }
156 }
157
158 pub fn init_counter(&mut self, operator_id: &str) {
160 self.running_counts
161 .insert(operator_id.to_string(), AtomicU64::new(0));
162 }
163
164 pub fn finalize_counter(&mut self, operator_id: &str) {
166 if let Some(counter) = self.running_counts.get(operator_id) {
167 let count = counter.load(Ordering::Relaxed);
168 self.actuals.insert(operator_id.to_string(), count);
169 }
170 }
171
172 #[must_use]
174 pub fn get(&self, operator_id: &str) -> Option<u64> {
175 self.actuals.get(operator_id).copied()
176 }
177
178 #[must_use]
180 pub fn get_running(&self, operator_id: &str) -> Option<u64> {
181 self.running_counts
182 .get(operator_id)
183 .map(|c| c.load(Ordering::Relaxed))
184 }
185
186 #[must_use]
188 pub fn all_actuals(&self) -> &HashMap<String, u64> {
189 &self.actuals
190 }
191}
192
193#[derive(Debug)]
198pub struct AdaptiveContext {
199 checkpoints: HashMap<String, CardinalityCheckpoint>,
201 reoptimization_threshold: f64,
203 min_rows: u64,
205 reoptimization_triggered: bool,
207 trigger_operator: Option<String>,
209}
210
211impl AdaptiveContext {
212 #[must_use]
214 pub fn new() -> Self {
215 Self {
216 checkpoints: HashMap::new(),
217 reoptimization_threshold: DEFAULT_REOPTIMIZATION_THRESHOLD,
218 min_rows: MIN_ROWS_FOR_REOPTIMIZATION,
219 reoptimization_triggered: false,
220 trigger_operator: None,
221 }
222 }
223
224 #[must_use]
226 pub fn with_thresholds(threshold: f64, min_rows: u64) -> Self {
227 Self {
228 checkpoints: HashMap::new(),
229 reoptimization_threshold: threshold,
230 min_rows,
231 reoptimization_triggered: false,
232 trigger_operator: None,
233 }
234 }
235
236 pub fn set_estimate(&mut self, operator_id: &str, estimate: f64) {
238 self.checkpoints.insert(
239 operator_id.to_string(),
240 CardinalityCheckpoint::new(operator_id, estimate),
241 );
242 }
243
244 pub fn record_actual(&mut self, operator_id: &str, actual: u64) {
246 if let Some(checkpoint) = self.checkpoints.get_mut(operator_id) {
247 checkpoint.record(actual);
248 } else {
249 let mut checkpoint = CardinalityCheckpoint::new(operator_id, 0.0);
251 checkpoint.record(actual);
252 self.checkpoints.insert(operator_id.to_string(), checkpoint);
253 }
254 }
255
256 pub fn apply_feedback(&mut self, feedback: &CardinalityFeedback) {
258 for (op_id, &actual) in feedback.all_actuals() {
259 self.record_actual(op_id, actual);
260 }
261 }
262
263 #[must_use]
265 pub fn has_significant_deviation(&self) -> bool {
266 self.checkpoints
267 .values()
268 .any(|cp| cp.is_significant_deviation(self.reoptimization_threshold))
269 }
270
271 #[must_use]
278 pub fn should_reoptimize(&mut self) -> bool {
279 if self.reoptimization_triggered {
280 return false;
281 }
282
283 for (op_id, checkpoint) in &self.checkpoints {
284 if checkpoint.actual < self.min_rows {
285 continue;
286 }
287
288 if checkpoint.is_significant_deviation(self.reoptimization_threshold) {
289 self.reoptimization_triggered = true;
290 self.trigger_operator = Some(op_id.clone());
291 return true;
292 }
293 }
294
295 false
296 }
297
298 #[must_use]
300 pub fn trigger_operator(&self) -> Option<&str> {
301 self.trigger_operator.as_deref()
302 }
303
304 #[must_use]
306 pub fn get_checkpoint(&self, operator_id: &str) -> Option<&CardinalityCheckpoint> {
307 self.checkpoints.get(operator_id)
308 }
309
310 #[must_use]
312 pub fn all_checkpoints(&self) -> &HashMap<String, CardinalityCheckpoint> {
313 &self.checkpoints
314 }
315
316 #[must_use]
320 pub fn correction_factor(&self, operator_id: &str) -> f64 {
321 self.checkpoints
322 .get(operator_id)
323 .filter(|cp| cp.recorded)
324 .map_or(1.0, CardinalityCheckpoint::deviation_ratio)
325 }
326
327 #[must_use]
329 pub fn summary(&self) -> AdaptiveSummary {
330 let recorded_count = self.checkpoints.values().filter(|cp| cp.recorded).count();
331 let deviation_count = self
332 .checkpoints
333 .values()
334 .filter(|cp| cp.is_significant_deviation(self.reoptimization_threshold))
335 .count();
336
337 let avg_deviation = if recorded_count > 0 {
338 self.checkpoints
339 .values()
340 .filter(|cp| cp.recorded)
341 .map(CardinalityCheckpoint::deviation_ratio)
342 .sum::<f64>()
343 / recorded_count as f64
344 } else {
345 1.0
346 };
347
348 let max_deviation = self
349 .checkpoints
350 .values()
351 .filter(|cp| cp.recorded)
352 .map(|cp| {
353 let ratio = cp.deviation_ratio();
354 if ratio > 1.0 { ratio } else { 1.0 / ratio }
355 })
356 .fold(1.0_f64, f64::max);
357
358 AdaptiveSummary {
359 checkpoint_count: self.checkpoints.len(),
360 recorded_count,
361 deviation_count,
362 avg_deviation_ratio: avg_deviation,
363 max_deviation_ratio: max_deviation,
364 reoptimization_triggered: self.reoptimization_triggered,
365 trigger_operator: self.trigger_operator.clone(),
366 }
367 }
368
369 pub fn reset(&mut self) {
371 for checkpoint in self.checkpoints.values_mut() {
372 checkpoint.actual = 0;
373 checkpoint.recorded = false;
374 }
375 self.reoptimization_triggered = false;
376 self.trigger_operator = None;
377 }
378}
379
380impl Default for AdaptiveContext {
381 fn default() -> Self {
382 Self::new()
383 }
384}
385
386#[derive(Debug, Clone, Default)]
388pub struct AdaptiveSummary {
389 pub checkpoint_count: usize,
391 pub recorded_count: usize,
393 pub deviation_count: usize,
395 pub avg_deviation_ratio: f64,
397 pub max_deviation_ratio: f64,
399 pub reoptimization_triggered: bool,
401 pub trigger_operator: Option<String>,
403}
404
405#[derive(Debug, Clone)]
409pub struct SharedAdaptiveContext {
410 inner: Arc<RwLock<AdaptiveContext>>,
411}
412
413impl SharedAdaptiveContext {
414 #[must_use]
416 pub fn new() -> Self {
417 Self {
418 inner: Arc::new(RwLock::new(AdaptiveContext::new())),
419 }
420 }
421
422 #[must_use]
424 pub fn from_context(ctx: AdaptiveContext) -> Self {
425 Self {
426 inner: Arc::new(RwLock::new(ctx)),
427 }
428 }
429
430 pub fn record_actual(&self, operator_id: &str, actual: u64) {
432 if let Ok(mut ctx) = self.inner.write() {
433 ctx.record_actual(operator_id, actual);
434 }
435 }
436
437 #[must_use]
439 pub fn should_reoptimize(&self) -> bool {
440 if let Ok(mut ctx) = self.inner.write() {
441 ctx.should_reoptimize()
442 } else {
443 false
444 }
445 }
446
447 #[must_use]
449 pub fn snapshot(&self) -> Option<AdaptiveContext> {
450 self.inner.read().ok().map(|guard| AdaptiveContext {
451 checkpoints: guard.checkpoints.clone(),
452 reoptimization_threshold: guard.reoptimization_threshold,
453 min_rows: guard.min_rows,
454 reoptimization_triggered: guard.reoptimization_triggered,
455 trigger_operator: guard.trigger_operator.clone(),
456 })
457 }
458}
459
460impl Default for SharedAdaptiveContext {
461 fn default() -> Self {
462 Self::new()
463 }
464}
465
466pub struct CardinalityTrackingOperator {
471 inner: Box<dyn PushOperator>,
473 operator_id: String,
475 row_count: u64,
477 context: SharedAdaptiveContext,
479}
480
481impl CardinalityTrackingOperator {
482 pub fn new(
484 inner: Box<dyn PushOperator>,
485 operator_id: &str,
486 context: SharedAdaptiveContext,
487 ) -> Self {
488 Self {
489 inner,
490 operator_id: operator_id.to_string(),
491 row_count: 0,
492 context,
493 }
494 }
495
496 #[must_use]
498 pub fn current_count(&self) -> u64 {
499 self.row_count
500 }
501}
502
503impl PushOperator for CardinalityTrackingOperator {
504 fn push(&mut self, chunk: DataChunk, sink: &mut dyn Sink) -> Result<bool, OperatorError> {
505 self.row_count += chunk.len() as u64;
507
508 self.inner.push(chunk, sink)
510 }
511
512 fn finalize(&mut self, sink: &mut dyn Sink) -> Result<(), OperatorError> {
513 self.context
515 .record_actual(&self.operator_id, self.row_count);
516
517 self.inner.finalize(sink)
519 }
520
521 fn preferred_chunk_size(&self) -> ChunkSizeHint {
522 self.inner.preferred_chunk_size()
523 }
524
525 fn name(&self) -> &'static str {
526 self.inner.name()
528 }
529}
530
531pub struct CardinalityTrackingSink {
533 inner: Box<dyn Sink>,
535 operator_id: String,
537 row_count: u64,
539 context: SharedAdaptiveContext,
541}
542
543impl CardinalityTrackingSink {
544 pub fn new(inner: Box<dyn Sink>, operator_id: &str, context: SharedAdaptiveContext) -> Self {
546 Self {
547 inner,
548 operator_id: operator_id.to_string(),
549 row_count: 0,
550 context,
551 }
552 }
553
554 #[must_use]
556 pub fn current_count(&self) -> u64 {
557 self.row_count
558 }
559}
560
561impl Sink for CardinalityTrackingSink {
562 fn consume(&mut self, chunk: DataChunk) -> Result<bool, OperatorError> {
563 self.row_count += chunk.len() as u64;
564 self.inner.consume(chunk)
565 }
566
567 fn finalize(&mut self) -> Result<(), OperatorError> {
568 self.context
570 .record_actual(&self.operator_id, self.row_count);
571 self.inner.finalize()
572 }
573
574 fn name(&self) -> &'static str {
575 self.inner.name()
576 }
577}
578
579#[derive(Debug, Clone, PartialEq)]
581pub enum ReoptimizationDecision {
582 Continue,
584 Reoptimize {
586 trigger: String,
588 corrections: HashMap<String, f64>,
590 },
591 Abort {
593 reason: String,
595 },
596}
597
598#[must_use]
600pub fn evaluate_reoptimization(ctx: &AdaptiveContext) -> ReoptimizationDecision {
601 let summary = ctx.summary();
602
603 if !summary.reoptimization_triggered {
605 return ReoptimizationDecision::Continue;
606 }
607
608 if summary.max_deviation_ratio > 100.0 {
610 return ReoptimizationDecision::Abort {
611 reason: format!(
612 "Catastrophic cardinality misestimate: {}x deviation",
613 summary.max_deviation_ratio
614 ),
615 };
616 }
617
618 let corrections: HashMap<String, f64> = ctx
620 .all_checkpoints()
621 .iter()
622 .filter(|(_, cp)| cp.recorded)
623 .map(|(id, cp)| (id.clone(), cp.deviation_ratio()))
624 .collect();
625
626 ReoptimizationDecision::Reoptimize {
627 trigger: summary.trigger_operator.unwrap_or_default(),
628 corrections,
629 }
630}
631
632pub type PlanFactory = Box<dyn Fn(&AdaptiveContext) -> Vec<Box<dyn PushOperator>> + Send + Sync>;
638
639#[derive(Debug, Clone)]
641pub struct AdaptivePipelineConfig {
642 pub check_interval: u64,
644 pub reoptimization_threshold: f64,
646 pub min_rows_for_reoptimization: u64,
648 pub max_reoptimizations: usize,
650}
651
652impl Default for AdaptivePipelineConfig {
653 fn default() -> Self {
654 Self {
655 check_interval: 10_000,
656 reoptimization_threshold: DEFAULT_REOPTIMIZATION_THRESHOLD,
657 min_rows_for_reoptimization: MIN_ROWS_FOR_REOPTIMIZATION,
658 max_reoptimizations: 3,
659 }
660 }
661}
662
663impl AdaptivePipelineConfig {
664 #[must_use]
666 pub fn new(check_interval: u64, threshold: f64, min_rows: u64) -> Self {
667 Self {
668 check_interval,
669 reoptimization_threshold: threshold,
670 min_rows_for_reoptimization: min_rows,
671 max_reoptimizations: 3,
672 }
673 }
674
675 #[must_use]
677 pub fn with_max_reoptimizations(mut self, max: usize) -> Self {
678 self.max_reoptimizations = max;
679 self
680 }
681}
682
683#[derive(Debug, Clone)]
685pub struct AdaptiveExecutionResult {
686 pub total_rows: u64,
688 pub reoptimization_count: usize,
690 pub triggers: Vec<String>,
692 pub final_context: AdaptiveSummary,
694}
695
696#[derive(Debug)]
701pub struct AdaptiveCheckpoint {
702 pub id: String,
704 pub after_operator: usize,
706 pub estimated_cardinality: f64,
708 pub actual_rows: u64,
710 pub triggered: bool,
712}
713
714impl AdaptiveCheckpoint {
715 #[must_use]
717 pub fn new(id: &str, after_operator: usize, estimated: f64) -> Self {
718 Self {
719 id: id.to_string(),
720 after_operator,
721 estimated_cardinality: estimated,
722 actual_rows: 0,
723 triggered: false,
724 }
725 }
726
727 pub fn record_rows(&mut self, count: u64) {
729 self.actual_rows += count;
730 }
731
732 #[must_use]
734 pub fn exceeds_threshold(&self, threshold: f64, min_rows: u64) -> bool {
735 if self.actual_rows < min_rows {
736 return false;
737 }
738 if self.estimated_cardinality <= 0.0 {
739 return self.actual_rows > 0;
740 }
741 let ratio = self.actual_rows as f64 / self.estimated_cardinality;
742 ratio > threshold || ratio < 1.0 / threshold
743 }
744}
745
746#[derive(Debug, Clone)]
748pub enum AdaptiveEvent {
749 CheckpointReached {
751 id: String,
753 actual_rows: u64,
755 estimated: f64,
757 },
758 ReoptimizationTriggered {
760 checkpoint_id: String,
762 deviation_ratio: f64,
764 },
765 PlanSwitched {
767 old_operator_count: usize,
769 new_operator_count: usize,
771 },
772 ExecutionCompleted {
774 total_rows: u64,
776 },
777}
778
779pub type AdaptiveEventCallback = Box<dyn Fn(AdaptiveEvent) + Send + Sync>;
781
782pub struct AdaptivePipelineBuilder {
784 checkpoints: Vec<AdaptiveCheckpoint>,
785 config: AdaptivePipelineConfig,
786 context: AdaptiveContext,
787 event_callback: Option<AdaptiveEventCallback>,
788}
789
790impl AdaptivePipelineBuilder {
791 #[must_use]
793 pub fn new() -> Self {
794 Self {
795 checkpoints: Vec::new(),
796 config: AdaptivePipelineConfig::default(),
797 context: AdaptiveContext::new(),
798 event_callback: None,
799 }
800 }
801
802 #[must_use]
804 pub fn with_config(mut self, config: AdaptivePipelineConfig) -> Self {
805 self.config = config;
806 self
807 }
808
809 #[must_use]
811 pub fn with_checkpoint(mut self, id: &str, after_operator: usize, estimated: f64) -> Self {
812 self.checkpoints
813 .push(AdaptiveCheckpoint::new(id, after_operator, estimated));
814 self.context.set_estimate(id, estimated);
815 self
816 }
817
818 #[must_use]
820 pub fn with_event_callback(mut self, callback: AdaptiveEventCallback) -> Self {
821 self.event_callback = Some(callback);
822 self
823 }
824
825 #[must_use]
827 pub fn with_context(mut self, context: AdaptiveContext) -> Self {
828 self.context = context;
829 self
830 }
831
832 #[must_use]
834 pub fn build(self) -> AdaptiveExecutionConfig {
835 AdaptiveExecutionConfig {
836 checkpoints: self.checkpoints,
837 config: self.config,
838 context: self.context,
839 event_callback: self.event_callback,
840 }
841 }
842}
843
844impl Default for AdaptivePipelineBuilder {
845 fn default() -> Self {
846 Self::new()
847 }
848}
849
850pub struct AdaptiveExecutionConfig {
852 pub checkpoints: Vec<AdaptiveCheckpoint>,
854 pub config: AdaptivePipelineConfig,
856 pub context: AdaptiveContext,
858 pub event_callback: Option<AdaptiveEventCallback>,
860}
861
862impl AdaptiveExecutionConfig {
863 #[must_use]
865 pub fn summary(&self) -> AdaptiveSummary {
866 self.context.summary()
867 }
868
869 pub fn record_checkpoint(&mut self, checkpoint_id: &str, actual: u64) {
871 self.context.record_actual(checkpoint_id, actual);
872
873 if let Some(cp) = self.checkpoints.iter_mut().find(|c| c.id == checkpoint_id) {
874 cp.actual_rows = actual;
875 }
876
877 if let Some(ref callback) = self.event_callback {
878 let estimated = self
879 .context
880 .get_checkpoint(checkpoint_id)
881 .map_or(0.0, |cp| cp.estimated);
882 callback(AdaptiveEvent::CheckpointReached {
883 id: checkpoint_id.to_string(),
884 actual_rows: actual,
885 estimated,
886 });
887 }
888 }
889
890 #[must_use]
892 pub fn should_reoptimize(&self) -> Option<&AdaptiveCheckpoint> {
893 self.checkpoints.iter().find(|cp| {
894 !cp.triggered
895 && cp.exceeds_threshold(
896 self.config.reoptimization_threshold,
897 self.config.min_rows_for_reoptimization,
898 )
899 })
900 }
901
902 pub fn mark_triggered(&mut self, checkpoint_id: &str) {
904 if let Some(cp) = self.checkpoints.iter_mut().find(|c| c.id == checkpoint_id) {
905 cp.triggered = true;
906 }
907
908 if let Some(ref callback) = self.event_callback {
909 let ratio = self
910 .context
911 .get_checkpoint(checkpoint_id)
912 .filter(|cp| cp.recorded)
913 .map_or(1.0, |cp| cp.deviation_ratio());
914 callback(AdaptiveEvent::ReoptimizationTriggered {
915 checkpoint_id: checkpoint_id.to_string(),
916 deviation_ratio: ratio,
917 });
918 }
919 }
920}
921
922use super::operators::{Operator, OperatorResult}; pub struct CardinalityTrackingWrapper {
932 inner: Box<dyn Operator>,
934 operator_id: String,
936 row_count: u64,
938 context: SharedAdaptiveContext,
940 finalized: bool,
942}
943
944impl CardinalityTrackingWrapper {
945 pub fn new(
947 inner: Box<dyn Operator>,
948 operator_id: &str,
949 context: SharedAdaptiveContext,
950 ) -> Self {
951 Self {
952 inner,
953 operator_id: operator_id.to_string(),
954 row_count: 0,
955 context,
956 finalized: false,
957 }
958 }
959
960 #[must_use]
962 pub fn current_count(&self) -> u64 {
963 self.row_count
964 }
965
966 fn report_final(&mut self) {
968 if !self.finalized {
969 self.context
970 .record_actual(&self.operator_id, self.row_count);
971 self.finalized = true;
972 }
973 }
974}
975
976impl Operator for CardinalityTrackingWrapper {
977 fn next(&mut self) -> OperatorResult {
978 match self.inner.next() {
979 Ok(Some(chunk)) => {
980 self.row_count += chunk.row_count() as u64;
982 Ok(Some(chunk))
983 }
984 Ok(None) => {
985 self.report_final();
987 Ok(None)
988 }
989 Err(e) => {
990 self.report_final();
992 Err(e)
993 }
994 }
995 }
996
997 fn reset(&mut self) {
998 self.row_count = 0;
999 self.finalized = false;
1000 self.inner.reset();
1001 }
1002
1003 fn name(&self) -> &'static str {
1004 self.inner.name()
1005 }
1006}
1007
1008impl Drop for CardinalityTrackingWrapper {
1009 fn drop(&mut self) {
1010 self.report_final();
1012 }
1013}
1014
1015use super::pipeline::{DEFAULT_CHUNK_SIZE, Source}; use super::sink::CollectorSink;
1019use super::source::OperatorSource;
1020
1021pub struct AdaptivePipelineExecutor {
1041 source: OperatorSource,
1042 context: SharedAdaptiveContext,
1043 config: AdaptivePipelineConfig,
1044}
1045
1046impl AdaptivePipelineExecutor {
1047 pub fn new(operator: Box<dyn Operator>, context: AdaptiveContext) -> Self {
1054 Self {
1055 source: OperatorSource::new(operator),
1056 context: SharedAdaptiveContext::from_context(context),
1057 config: AdaptivePipelineConfig::default(),
1058 }
1059 }
1060
1061 pub fn with_config(
1063 operator: Box<dyn Operator>,
1064 context: AdaptiveContext,
1065 config: AdaptivePipelineConfig,
1066 ) -> Self {
1067 Self {
1068 source: OperatorSource::new(operator),
1069 context: SharedAdaptiveContext::from_context(context),
1070 config,
1071 }
1072 }
1073
1074 pub fn execute(mut self) -> Result<(Vec<DataChunk>, AdaptiveSummary), OperatorError> {
1084 let mut sink = CardinalityTrackingSink::new(
1085 Box::new(CollectorSink::new()),
1086 "output",
1087 self.context.clone(),
1088 );
1089
1090 let chunk_size = DEFAULT_CHUNK_SIZE;
1091 let mut total_rows: u64 = 0;
1092 let check_interval = self.config.check_interval;
1093
1094 while let Some(chunk) = self.source.next_chunk(chunk_size)? {
1096 let chunk_rows = chunk.len() as u64;
1097 total_rows += chunk_rows;
1098
1099 let continue_exec = sink.consume(chunk)?;
1101 if !continue_exec {
1102 break;
1103 }
1104
1105 if total_rows >= check_interval
1107 && total_rows.is_multiple_of(check_interval)
1108 && self.context.should_reoptimize()
1109 {
1110 }
1113 }
1114
1115 sink.finalize()?;
1117
1118 let summary = self
1120 .context
1121 .snapshot()
1122 .map(|ctx| ctx.summary())
1123 .unwrap_or_default();
1124
1125 Ok((Vec::new(), summary))
1129 }
1130
1131 pub fn execute_collecting(
1139 mut self,
1140 ) -> Result<(Vec<DataChunk>, AdaptiveSummary), OperatorError> {
1141 let mut chunks = Vec::new();
1142 let chunk_size = DEFAULT_CHUNK_SIZE;
1143 let mut total_rows: u64 = 0;
1144 let check_interval = self.config.check_interval;
1145
1146 while let Some(chunk) = self.source.next_chunk(chunk_size)? {
1148 let chunk_rows = chunk.len() as u64;
1149 total_rows += chunk_rows;
1150
1151 self.context.record_actual("root", total_rows);
1153
1154 if !chunk.is_empty() {
1156 chunks.push(chunk);
1157 }
1158
1159 if total_rows >= check_interval && total_rows.is_multiple_of(check_interval) {
1161 let _ = self.context.should_reoptimize();
1162 }
1163 }
1164
1165 let summary = self
1166 .context
1167 .snapshot()
1168 .map(|ctx| ctx.summary())
1169 .unwrap_or_default();
1170
1171 Ok((chunks, summary))
1172 }
1173
1174 pub fn context(&self) -> &SharedAdaptiveContext {
1176 &self.context
1177 }
1178}
1179
1180pub fn execute_adaptive(
1198 operator: Box<dyn Operator>,
1199 context: Option<AdaptiveContext>,
1200 config: Option<AdaptivePipelineConfig>,
1201) -> Result<(Vec<DataChunk>, Option<AdaptiveSummary>), OperatorError> {
1202 let ctx = context.unwrap_or_default();
1203 let cfg = config.unwrap_or_default();
1204
1205 let executor = AdaptivePipelineExecutor::with_config(operator, ctx, cfg);
1206 let (chunks, summary) = executor.execute_collecting()?;
1207
1208 Ok((chunks, Some(summary)))
1209}
1210
1211#[cfg(test)]
1212mod tests {
1213 use super::*;
1214
1215 #[test]
1216 fn test_checkpoint_deviation_ratio() {
1217 let mut cp = CardinalityCheckpoint::new("test", 100.0);
1218 cp.record(200);
1219
1220 assert!((cp.deviation_ratio() - 2.0).abs() < 0.001);
1222 }
1223
1224 #[test]
1225 fn test_checkpoint_underestimate() {
1226 let mut cp = CardinalityCheckpoint::new("test", 100.0);
1227 cp.record(500);
1228
1229 assert!((cp.deviation_ratio() - 5.0).abs() < 0.001);
1231 assert!(cp.is_significant_deviation(3.0));
1232 }
1233
1234 #[test]
1235 fn test_checkpoint_overestimate() {
1236 let mut cp = CardinalityCheckpoint::new("test", 100.0);
1237 cp.record(20);
1238
1239 assert!((cp.deviation_ratio() - 0.2).abs() < 0.001);
1241 assert!(cp.is_significant_deviation(3.0)); }
1243
1244 #[test]
1245 fn test_checkpoint_accurate() {
1246 let mut cp = CardinalityCheckpoint::new("test", 100.0);
1247 cp.record(110);
1248
1249 assert!((cp.deviation_ratio() - 1.1).abs() < 0.001);
1251 assert!(!cp.is_significant_deviation(3.0)); }
1253
1254 #[test]
1255 fn test_checkpoint_zero_estimate() {
1256 let mut cp = CardinalityCheckpoint::new("test", 0.0);
1257 cp.record(100);
1258
1259 assert!(cp.deviation_ratio().is_infinite());
1261 }
1262
1263 #[test]
1264 fn test_checkpoint_zero_both() {
1265 let mut cp = CardinalityCheckpoint::new("test", 0.0);
1266 cp.record(0);
1267
1268 assert!((cp.deviation_ratio() - 1.0).abs() < 0.001);
1270 }
1271
1272 #[test]
1273 fn test_feedback_collection() {
1274 let mut feedback = CardinalityFeedback::new();
1275 feedback.record("scan_1", 1000);
1276 feedback.record("filter_1", 100);
1277
1278 assert_eq!(feedback.get("scan_1"), Some(1000));
1279 assert_eq!(feedback.get("filter_1"), Some(100));
1280 assert_eq!(feedback.get("unknown"), None);
1281 }
1282
1283 #[test]
1284 fn test_feedback_running_counter() {
1285 let mut feedback = CardinalityFeedback::new();
1286 feedback.init_counter("op_1");
1287
1288 feedback.add_rows("op_1", 100);
1289 feedback.add_rows("op_1", 200);
1290 feedback.add_rows("op_1", 50);
1291
1292 assert_eq!(feedback.get_running("op_1"), Some(350));
1293
1294 feedback.finalize_counter("op_1");
1295 assert_eq!(feedback.get("op_1"), Some(350));
1296 }
1297
1298 #[test]
1299 fn test_adaptive_context_basic() {
1300 let mut ctx = AdaptiveContext::new();
1301 ctx.set_estimate("scan", 1000.0);
1302 ctx.set_estimate("filter", 100.0);
1303
1304 ctx.record_actual("scan", 1000);
1305 ctx.record_actual("filter", 500); let cp = ctx.get_checkpoint("filter").unwrap();
1308 assert!((cp.deviation_ratio() - 5.0).abs() < 0.001);
1309 }
1310
1311 #[test]
1312 fn test_adaptive_context_should_reoptimize() {
1313 let mut ctx = AdaptiveContext::with_thresholds(2.0, 100);
1314 ctx.set_estimate("scan", 10000.0);
1315 ctx.set_estimate("filter", 1000.0);
1316
1317 ctx.record_actual("scan", 10000);
1318 ctx.record_actual("filter", 5000); assert!(ctx.should_reoptimize());
1321 assert_eq!(ctx.trigger_operator(), Some("filter"));
1322
1323 assert!(!ctx.should_reoptimize());
1325 }
1326
1327 #[test]
1328 fn test_adaptive_context_min_rows() {
1329 let mut ctx = AdaptiveContext::with_thresholds(2.0, 1000);
1330 ctx.set_estimate("filter", 100.0);
1331 ctx.record_actual("filter", 500); assert!(!ctx.should_reoptimize());
1335 }
1336
1337 #[test]
1338 fn test_adaptive_context_no_deviation() {
1339 let mut ctx = AdaptiveContext::new();
1340 ctx.set_estimate("scan", 1000.0);
1341 ctx.record_actual("scan", 1100); assert!(!ctx.has_significant_deviation());
1344 assert!(!ctx.should_reoptimize());
1345 }
1346
1347 #[test]
1348 fn test_adaptive_context_correction_factor() {
1349 let mut ctx = AdaptiveContext::new();
1350 ctx.set_estimate("filter", 100.0);
1351 ctx.record_actual("filter", 300);
1352
1353 assert!((ctx.correction_factor("filter") - 3.0).abs() < 0.001);
1354 assert!((ctx.correction_factor("unknown") - 1.0).abs() < 0.001);
1355 }
1356
1357 #[test]
1358 fn test_adaptive_context_apply_feedback() {
1359 let mut ctx = AdaptiveContext::new();
1360 ctx.set_estimate("scan", 1000.0);
1361 ctx.set_estimate("filter", 100.0);
1362
1363 let mut feedback = CardinalityFeedback::new();
1364 feedback.record("scan", 1000);
1365 feedback.record("filter", 500);
1366
1367 ctx.apply_feedback(&feedback);
1368
1369 assert_eq!(ctx.get_checkpoint("scan").unwrap().actual, 1000);
1370 assert_eq!(ctx.get_checkpoint("filter").unwrap().actual, 500);
1371 }
1372
1373 #[test]
1374 fn test_adaptive_summary() {
1375 let mut ctx = AdaptiveContext::with_thresholds(2.0, 0);
1376 ctx.set_estimate("op1", 100.0);
1377 ctx.set_estimate("op2", 200.0);
1378 ctx.set_estimate("op3", 300.0);
1379
1380 ctx.record_actual("op1", 100); ctx.record_actual("op2", 600); let _ = ctx.should_reoptimize();
1385
1386 let summary = ctx.summary();
1387 assert_eq!(summary.checkpoint_count, 3);
1388 assert_eq!(summary.recorded_count, 2);
1389 assert_eq!(summary.deviation_count, 1);
1390 assert!(summary.reoptimization_triggered);
1391 }
1392
1393 #[test]
1394 fn test_adaptive_context_reset() {
1395 let mut ctx = AdaptiveContext::new();
1396 ctx.set_estimate("scan", 1000.0);
1397 ctx.record_actual("scan", 5000);
1398 let _ = ctx.should_reoptimize(); assert!(ctx.reoptimization_triggered);
1401
1402 ctx.reset();
1403
1404 assert!(!ctx.reoptimization_triggered);
1405 assert_eq!(ctx.get_checkpoint("scan").unwrap().actual, 0);
1406 assert!(!ctx.get_checkpoint("scan").unwrap().recorded);
1407 assert!((ctx.get_checkpoint("scan").unwrap().estimated - 1000.0).abs() < 0.001);
1409 }
1410
1411 #[test]
1412 fn test_shared_context() {
1413 let ctx = SharedAdaptiveContext::new();
1414
1415 ctx.record_actual("op1", 1000);
1416
1417 let snapshot = ctx.snapshot().unwrap();
1418 assert_eq!(snapshot.get_checkpoint("op1").unwrap().actual, 1000);
1419 }
1420
1421 #[test]
1422 fn test_reoptimization_decision_continue() {
1423 let mut ctx = AdaptiveContext::new();
1424 ctx.set_estimate("scan", 1000.0);
1425 ctx.record_actual("scan", 1100);
1426
1427 let decision = evaluate_reoptimization(&ctx);
1428 assert_eq!(decision, ReoptimizationDecision::Continue);
1429 }
1430
1431 #[test]
1432 fn test_reoptimization_decision_reoptimize() {
1433 let mut ctx = AdaptiveContext::with_thresholds(2.0, 0);
1434 ctx.set_estimate("filter", 100.0);
1435 ctx.record_actual("filter", 500);
1436 let _ = ctx.should_reoptimize(); let decision = evaluate_reoptimization(&ctx);
1439
1440 if let ReoptimizationDecision::Reoptimize {
1441 trigger,
1442 corrections,
1443 } = decision
1444 {
1445 assert_eq!(trigger, "filter");
1446 assert!((corrections.get("filter").copied().unwrap_or(0.0) - 5.0).abs() < 0.001);
1447 } else {
1448 panic!("Expected Reoptimize decision");
1449 }
1450 }
1451
1452 #[test]
1453 fn test_reoptimization_decision_abort() {
1454 let mut ctx = AdaptiveContext::with_thresholds(2.0, 0);
1455 ctx.set_estimate("filter", 1.0);
1456 ctx.record_actual("filter", 1000); let _ = ctx.should_reoptimize();
1458
1459 let decision = evaluate_reoptimization(&ctx);
1460
1461 if let ReoptimizationDecision::Abort { reason } = decision {
1462 assert!(reason.contains("Catastrophic"));
1463 } else {
1464 panic!("Expected Abort decision");
1465 }
1466 }
1467
1468 #[test]
1469 fn test_absolute_deviation() {
1470 let mut cp = CardinalityCheckpoint::new("test", 100.0);
1471 cp.record(150);
1472
1473 assert!((cp.absolute_deviation() - 50.0).abs() < 0.001);
1474 }
1475
1476 #[test]
1479 fn test_adaptive_checkpoint_basic() {
1480 let mut cp = AdaptiveCheckpoint::new("filter_1", 0, 100.0);
1481 assert_eq!(cp.actual_rows, 0);
1482 assert!(!cp.triggered);
1483
1484 cp.record_rows(50);
1485 assert_eq!(cp.actual_rows, 50);
1486
1487 cp.record_rows(100);
1488 assert_eq!(cp.actual_rows, 150);
1489 }
1490
1491 #[test]
1492 fn test_adaptive_checkpoint_exceeds_threshold() {
1493 let mut cp = AdaptiveCheckpoint::new("filter", 0, 100.0);
1494
1495 cp.record_rows(50);
1497 assert!(!cp.exceeds_threshold(2.0, 100));
1498
1499 cp.record_rows(50);
1501 assert!(!cp.exceeds_threshold(2.0, 100)); cp.actual_rows = 0;
1505 cp.record_rows(500);
1506 assert!(cp.exceeds_threshold(2.0, 100)); let mut cp2 = AdaptiveCheckpoint::new("filter2", 0, 1000.0);
1510 cp2.record_rows(200);
1511 assert!(cp2.exceeds_threshold(2.0, 100)); }
1513
1514 #[test]
1515 fn test_adaptive_pipeline_config_default() {
1516 let config = AdaptivePipelineConfig::default();
1517
1518 assert_eq!(config.check_interval, 10_000);
1519 assert!((config.reoptimization_threshold - DEFAULT_REOPTIMIZATION_THRESHOLD).abs() < 0.001);
1520 assert_eq!(
1521 config.min_rows_for_reoptimization,
1522 MIN_ROWS_FOR_REOPTIMIZATION
1523 );
1524 assert_eq!(config.max_reoptimizations, 3);
1525 }
1526
1527 #[test]
1528 fn test_adaptive_pipeline_config_custom() {
1529 let config = AdaptivePipelineConfig::new(5000, 2.0, 500).with_max_reoptimizations(5);
1530
1531 assert_eq!(config.check_interval, 5000);
1532 assert!((config.reoptimization_threshold - 2.0).abs() < 0.001);
1533 assert_eq!(config.min_rows_for_reoptimization, 500);
1534 assert_eq!(config.max_reoptimizations, 5);
1535 }
1536
1537 #[test]
1538 fn test_adaptive_pipeline_builder() {
1539 let config = AdaptivePipelineBuilder::new()
1540 .with_config(AdaptivePipelineConfig::new(1000, 2.0, 100))
1541 .with_checkpoint("scan", 0, 10000.0)
1542 .with_checkpoint("filter", 1, 1000.0)
1543 .build();
1544
1545 assert_eq!(config.checkpoints.len(), 2);
1546 assert_eq!(config.checkpoints[0].id, "scan");
1547 assert!((config.checkpoints[0].estimated_cardinality - 10000.0).abs() < 0.001);
1548 assert_eq!(config.checkpoints[1].id, "filter");
1549 assert!((config.checkpoints[1].estimated_cardinality - 1000.0).abs() < 0.001);
1550 }
1551
1552 #[test]
1553 fn test_adaptive_execution_config_record_checkpoint() {
1554 let mut config = AdaptivePipelineBuilder::new()
1555 .with_checkpoint("filter", 0, 100.0)
1556 .build();
1557
1558 config.record_checkpoint("filter", 500);
1559
1560 let cp = config.context.get_checkpoint("filter").unwrap();
1562 assert_eq!(cp.actual, 500);
1563 assert!(cp.recorded);
1564
1565 let acp = config
1567 .checkpoints
1568 .iter()
1569 .find(|c| c.id == "filter")
1570 .unwrap();
1571 assert_eq!(acp.actual_rows, 500);
1572 }
1573
1574 #[test]
1575 fn test_adaptive_execution_config_should_reoptimize() {
1576 let mut config = AdaptivePipelineBuilder::new()
1577 .with_config(AdaptivePipelineConfig::new(1000, 2.0, 100))
1578 .with_checkpoint("filter", 0, 100.0)
1579 .build();
1580
1581 assert!(config.should_reoptimize().is_none());
1583
1584 config.record_checkpoint("filter", 150);
1586 assert!(config.should_reoptimize().is_none()); config.checkpoints[0].actual_rows = 0; config.record_checkpoint("filter", 500);
1591 config.checkpoints[0].actual_rows = 500;
1592
1593 let trigger = config.should_reoptimize();
1594 assert!(trigger.is_some());
1595 assert_eq!(trigger.unwrap().id, "filter");
1596 }
1597
1598 #[test]
1599 fn test_adaptive_execution_config_mark_triggered() {
1600 let mut config = AdaptivePipelineBuilder::new()
1601 .with_checkpoint("filter", 0, 100.0)
1602 .build();
1603
1604 assert!(!config.checkpoints[0].triggered);
1605
1606 config.mark_triggered("filter");
1607
1608 assert!(config.checkpoints[0].triggered);
1609 }
1610
1611 #[test]
1612 fn test_adaptive_event_callback() {
1613 use std::sync::atomic::AtomicUsize;
1614
1615 let event_count = Arc::new(AtomicUsize::new(0));
1616 let counter = event_count.clone();
1617
1618 let mut config = AdaptivePipelineBuilder::new()
1619 .with_checkpoint("filter", 0, 100.0)
1620 .with_event_callback(Box::new(move |_event| {
1621 counter.fetch_add(1, Ordering::Relaxed);
1622 }))
1623 .build();
1624
1625 config.record_checkpoint("filter", 500);
1626
1627 assert_eq!(event_count.load(Ordering::Relaxed), 1);
1629
1630 config.mark_triggered("filter");
1631
1632 assert_eq!(event_count.load(Ordering::Relaxed), 2);
1634 }
1635
1636 #[test]
1637 fn test_adaptive_checkpoint_with_zero_estimate() {
1638 let mut cp = AdaptiveCheckpoint::new("test", 0, 0.0);
1639 cp.record_rows(100);
1640
1641 assert!(cp.exceeds_threshold(2.0, 50));
1643 }
1644}