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)]
581#[non_exhaustive]
582pub enum ReoptimizationDecision {
583 Continue,
585 Reoptimize {
587 trigger: String,
589 corrections: HashMap<String, f64>,
591 },
592 Abort {
594 reason: String,
596 },
597}
598
599#[must_use]
601pub fn evaluate_reoptimization(ctx: &AdaptiveContext) -> ReoptimizationDecision {
602 let summary = ctx.summary();
603
604 if !summary.reoptimization_triggered {
606 return ReoptimizationDecision::Continue;
607 }
608
609 if summary.max_deviation_ratio > 100.0 {
611 return ReoptimizationDecision::Abort {
612 reason: format!(
613 "Catastrophic cardinality misestimate: {}x deviation",
614 summary.max_deviation_ratio
615 ),
616 };
617 }
618
619 let corrections: HashMap<String, f64> = ctx
621 .all_checkpoints()
622 .iter()
623 .filter(|(_, cp)| cp.recorded)
624 .map(|(id, cp)| (id.clone(), cp.deviation_ratio()))
625 .collect();
626
627 ReoptimizationDecision::Reoptimize {
628 trigger: summary.trigger_operator.unwrap_or_default(),
629 corrections,
630 }
631}
632
633pub type PlanFactory = Box<dyn Fn(&AdaptiveContext) -> Vec<Box<dyn PushOperator>> + Send + Sync>;
639
640#[derive(Debug, Clone)]
642pub struct AdaptivePipelineConfig {
643 pub check_interval: u64,
645 pub reoptimization_threshold: f64,
647 pub min_rows_for_reoptimization: u64,
649 pub max_reoptimizations: usize,
651}
652
653impl Default for AdaptivePipelineConfig {
654 fn default() -> Self {
655 Self {
656 check_interval: 10_000,
657 reoptimization_threshold: DEFAULT_REOPTIMIZATION_THRESHOLD,
658 min_rows_for_reoptimization: MIN_ROWS_FOR_REOPTIMIZATION,
659 max_reoptimizations: 3,
660 }
661 }
662}
663
664impl AdaptivePipelineConfig {
665 #[must_use]
667 pub fn new(check_interval: u64, threshold: f64, min_rows: u64) -> Self {
668 Self {
669 check_interval,
670 reoptimization_threshold: threshold,
671 min_rows_for_reoptimization: min_rows,
672 max_reoptimizations: 3,
673 }
674 }
675
676 #[must_use]
678 pub fn with_max_reoptimizations(mut self, max: usize) -> Self {
679 self.max_reoptimizations = max;
680 self
681 }
682}
683
684#[derive(Debug, Clone)]
686pub struct AdaptiveExecutionResult {
687 pub total_rows: u64,
689 pub reoptimization_count: usize,
691 pub triggers: Vec<String>,
693 pub final_context: AdaptiveSummary,
695}
696
697#[derive(Debug)]
702pub struct AdaptiveCheckpoint {
703 pub id: String,
705 pub after_operator: usize,
707 pub estimated_cardinality: f64,
709 pub actual_rows: u64,
711 pub triggered: bool,
713}
714
715impl AdaptiveCheckpoint {
716 #[must_use]
718 pub fn new(id: &str, after_operator: usize, estimated: f64) -> Self {
719 Self {
720 id: id.to_string(),
721 after_operator,
722 estimated_cardinality: estimated,
723 actual_rows: 0,
724 triggered: false,
725 }
726 }
727
728 pub fn record_rows(&mut self, count: u64) {
730 self.actual_rows += count;
731 }
732
733 #[must_use]
735 pub fn exceeds_threshold(&self, threshold: f64, min_rows: u64) -> bool {
736 if self.actual_rows < min_rows {
737 return false;
738 }
739 if self.estimated_cardinality <= 0.0 {
740 return self.actual_rows > 0;
741 }
742 let ratio = self.actual_rows as f64 / self.estimated_cardinality;
743 ratio > threshold || ratio < 1.0 / threshold
744 }
745}
746
747#[derive(Debug, Clone)]
749#[non_exhaustive]
750pub enum AdaptiveEvent {
751 CheckpointReached {
753 id: String,
755 actual_rows: u64,
757 estimated: f64,
759 },
760 ReoptimizationTriggered {
762 checkpoint_id: String,
764 deviation_ratio: f64,
766 },
767 PlanSwitched {
769 old_operator_count: usize,
771 new_operator_count: usize,
773 },
774 ExecutionCompleted {
776 total_rows: u64,
778 },
779}
780
781pub type AdaptiveEventCallback = Box<dyn Fn(AdaptiveEvent) + Send + Sync>;
783
784pub struct AdaptivePipelineBuilder {
786 checkpoints: Vec<AdaptiveCheckpoint>,
787 config: AdaptivePipelineConfig,
788 context: AdaptiveContext,
789 event_callback: Option<AdaptiveEventCallback>,
790}
791
792impl AdaptivePipelineBuilder {
793 #[must_use]
795 pub fn new() -> Self {
796 Self {
797 checkpoints: Vec::new(),
798 config: AdaptivePipelineConfig::default(),
799 context: AdaptiveContext::new(),
800 event_callback: None,
801 }
802 }
803
804 #[must_use]
806 pub fn with_config(mut self, config: AdaptivePipelineConfig) -> Self {
807 self.config = config;
808 self
809 }
810
811 #[must_use]
813 pub fn with_checkpoint(mut self, id: &str, after_operator: usize, estimated: f64) -> Self {
814 self.checkpoints
815 .push(AdaptiveCheckpoint::new(id, after_operator, estimated));
816 self.context.set_estimate(id, estimated);
817 self
818 }
819
820 #[must_use]
822 pub fn with_event_callback(mut self, callback: AdaptiveEventCallback) -> Self {
823 self.event_callback = Some(callback);
824 self
825 }
826
827 #[must_use]
829 pub fn with_context(mut self, context: AdaptiveContext) -> Self {
830 self.context = context;
831 self
832 }
833
834 #[must_use]
836 pub fn build(self) -> AdaptiveExecutionConfig {
837 AdaptiveExecutionConfig {
838 checkpoints: self.checkpoints,
839 config: self.config,
840 context: self.context,
841 event_callback: self.event_callback,
842 }
843 }
844}
845
846impl Default for AdaptivePipelineBuilder {
847 fn default() -> Self {
848 Self::new()
849 }
850}
851
852pub struct AdaptiveExecutionConfig {
854 pub checkpoints: Vec<AdaptiveCheckpoint>,
856 pub config: AdaptivePipelineConfig,
858 pub context: AdaptiveContext,
860 pub event_callback: Option<AdaptiveEventCallback>,
862}
863
864impl AdaptiveExecutionConfig {
865 #[must_use]
867 pub fn summary(&self) -> AdaptiveSummary {
868 self.context.summary()
869 }
870
871 pub fn record_checkpoint(&mut self, checkpoint_id: &str, actual: u64) {
873 self.context.record_actual(checkpoint_id, actual);
874
875 if let Some(cp) = self.checkpoints.iter_mut().find(|c| c.id == checkpoint_id) {
876 cp.actual_rows = actual;
877 }
878
879 if let Some(ref callback) = self.event_callback {
880 let estimated = self
881 .context
882 .get_checkpoint(checkpoint_id)
883 .map_or(0.0, |cp| cp.estimated);
884 callback(AdaptiveEvent::CheckpointReached {
885 id: checkpoint_id.to_string(),
886 actual_rows: actual,
887 estimated,
888 });
889 }
890 }
891
892 #[must_use]
894 pub fn should_reoptimize(&self) -> Option<&AdaptiveCheckpoint> {
895 self.checkpoints.iter().find(|cp| {
896 !cp.triggered
897 && cp.exceeds_threshold(
898 self.config.reoptimization_threshold,
899 self.config.min_rows_for_reoptimization,
900 )
901 })
902 }
903
904 pub fn mark_triggered(&mut self, checkpoint_id: &str) {
906 if let Some(cp) = self.checkpoints.iter_mut().find(|c| c.id == checkpoint_id) {
907 cp.triggered = true;
908 }
909
910 if let Some(ref callback) = self.event_callback {
911 let ratio = self
912 .context
913 .get_checkpoint(checkpoint_id)
914 .filter(|cp| cp.recorded)
915 .map_or(1.0, |cp| cp.deviation_ratio());
916 callback(AdaptiveEvent::ReoptimizationTriggered {
917 checkpoint_id: checkpoint_id.to_string(),
918 deviation_ratio: ratio,
919 });
920 }
921 }
922}
923
924use super::operators::{Operator, OperatorResult}; pub struct CardinalityTrackingWrapper {
934 inner: Box<dyn Operator>,
936 operator_id: String,
938 row_count: u64,
940 context: SharedAdaptiveContext,
942 finalized: bool,
944}
945
946impl CardinalityTrackingWrapper {
947 pub fn new(
949 inner: Box<dyn Operator>,
950 operator_id: &str,
951 context: SharedAdaptiveContext,
952 ) -> Self {
953 Self {
954 inner,
955 operator_id: operator_id.to_string(),
956 row_count: 0,
957 context,
958 finalized: false,
959 }
960 }
961
962 #[must_use]
964 pub fn current_count(&self) -> u64 {
965 self.row_count
966 }
967
968 fn report_final(&mut self) {
970 if !self.finalized {
971 self.context
972 .record_actual(&self.operator_id, self.row_count);
973 self.finalized = true;
974 }
975 }
976}
977
978impl Operator for CardinalityTrackingWrapper {
979 fn next(&mut self) -> OperatorResult {
980 match self.inner.next() {
981 Ok(Some(chunk)) => {
982 self.row_count += chunk.row_count() as u64;
984 Ok(Some(chunk))
985 }
986 Ok(None) => {
987 self.report_final();
989 Ok(None)
990 }
991 Err(e) => {
992 self.report_final();
994 Err(e)
995 }
996 }
997 }
998
999 fn reset(&mut self) {
1000 self.row_count = 0;
1001 self.finalized = false;
1002 self.inner.reset();
1003 }
1004
1005 fn name(&self) -> &'static str {
1006 self.inner.name()
1007 }
1008}
1009
1010impl Drop for CardinalityTrackingWrapper {
1011 fn drop(&mut self) {
1012 self.report_final();
1014 }
1015}
1016
1017use super::pipeline::{DEFAULT_CHUNK_SIZE, Source}; use super::sink::CollectorSink;
1021use super::source::OperatorSource;
1022
1023pub struct AdaptivePipelineExecutor {
1043 source: OperatorSource,
1044 context: SharedAdaptiveContext,
1045 config: AdaptivePipelineConfig,
1046}
1047
1048impl AdaptivePipelineExecutor {
1049 pub fn new(operator: Box<dyn Operator>, context: AdaptiveContext) -> Self {
1056 Self {
1057 source: OperatorSource::new(operator),
1058 context: SharedAdaptiveContext::from_context(context),
1059 config: AdaptivePipelineConfig::default(),
1060 }
1061 }
1062
1063 pub fn with_config(
1065 operator: Box<dyn Operator>,
1066 context: AdaptiveContext,
1067 config: AdaptivePipelineConfig,
1068 ) -> Self {
1069 Self {
1070 source: OperatorSource::new(operator),
1071 context: SharedAdaptiveContext::from_context(context),
1072 config,
1073 }
1074 }
1075
1076 pub fn execute(mut self) -> Result<(Vec<DataChunk>, AdaptiveSummary), OperatorError> {
1086 let mut sink = CardinalityTrackingSink::new(
1087 Box::new(CollectorSink::new()),
1088 "output",
1089 self.context.clone(),
1090 );
1091
1092 let chunk_size = DEFAULT_CHUNK_SIZE;
1093 let mut total_rows: u64 = 0;
1094 let check_interval = self.config.check_interval;
1095
1096 while let Some(chunk) = self.source.next_chunk(chunk_size)? {
1098 let chunk_rows = chunk.len() as u64;
1099 total_rows += chunk_rows;
1100
1101 let continue_exec = sink.consume(chunk)?;
1103 if !continue_exec {
1104 break;
1105 }
1106
1107 if total_rows >= check_interval
1109 && total_rows.is_multiple_of(check_interval)
1110 && self.context.should_reoptimize()
1111 {
1112 }
1115 }
1116
1117 sink.finalize()?;
1119
1120 let summary = self
1122 .context
1123 .snapshot()
1124 .map(|ctx| ctx.summary())
1125 .unwrap_or_default();
1126
1127 Ok((Vec::new(), summary))
1131 }
1132
1133 pub fn execute_collecting(
1141 mut self,
1142 ) -> Result<(Vec<DataChunk>, AdaptiveSummary), OperatorError> {
1143 let mut chunks = Vec::new();
1144 let chunk_size = DEFAULT_CHUNK_SIZE;
1145 let mut total_rows: u64 = 0;
1146 let check_interval = self.config.check_interval;
1147
1148 while let Some(chunk) = self.source.next_chunk(chunk_size)? {
1150 let chunk_rows = chunk.len() as u64;
1151 total_rows += chunk_rows;
1152
1153 self.context.record_actual("root", total_rows);
1155
1156 if !chunk.is_empty() {
1158 chunks.push(chunk);
1159 }
1160
1161 if total_rows >= check_interval && total_rows.is_multiple_of(check_interval) {
1163 let _ = self.context.should_reoptimize();
1164 }
1165 }
1166
1167 let summary = self
1168 .context
1169 .snapshot()
1170 .map(|ctx| ctx.summary())
1171 .unwrap_or_default();
1172
1173 Ok((chunks, summary))
1174 }
1175
1176 pub fn context(&self) -> &SharedAdaptiveContext {
1178 &self.context
1179 }
1180}
1181
1182pub fn execute_adaptive(
1200 operator: Box<dyn Operator>,
1201 context: Option<AdaptiveContext>,
1202 config: Option<AdaptivePipelineConfig>,
1203) -> Result<(Vec<DataChunk>, Option<AdaptiveSummary>), OperatorError> {
1204 let ctx = context.unwrap_or_default();
1205 let cfg = config.unwrap_or_default();
1206
1207 let executor = AdaptivePipelineExecutor::with_config(operator, ctx, cfg);
1208 let (chunks, summary) = executor.execute_collecting()?;
1209
1210 Ok((chunks, Some(summary)))
1211}
1212
1213#[cfg(test)]
1214mod tests {
1215 use super::*;
1216
1217 #[test]
1218 fn test_checkpoint_deviation_ratio() {
1219 let mut cp = CardinalityCheckpoint::new("test", 100.0);
1220 cp.record(200);
1221
1222 assert!((cp.deviation_ratio() - 2.0).abs() < 0.001);
1224 }
1225
1226 #[test]
1227 fn test_checkpoint_underestimate() {
1228 let mut cp = CardinalityCheckpoint::new("test", 100.0);
1229 cp.record(500);
1230
1231 assert!((cp.deviation_ratio() - 5.0).abs() < 0.001);
1233 assert!(cp.is_significant_deviation(3.0));
1234 }
1235
1236 #[test]
1237 fn test_checkpoint_overestimate() {
1238 let mut cp = CardinalityCheckpoint::new("test", 100.0);
1239 cp.record(20);
1240
1241 assert!((cp.deviation_ratio() - 0.2).abs() < 0.001);
1243 assert!(cp.is_significant_deviation(3.0)); }
1245
1246 #[test]
1247 fn test_checkpoint_accurate() {
1248 let mut cp = CardinalityCheckpoint::new("test", 100.0);
1249 cp.record(110);
1250
1251 assert!((cp.deviation_ratio() - 1.1).abs() < 0.001);
1253 assert!(!cp.is_significant_deviation(3.0)); }
1255
1256 #[test]
1257 fn test_checkpoint_zero_estimate() {
1258 let mut cp = CardinalityCheckpoint::new("test", 0.0);
1259 cp.record(100);
1260
1261 assert!(cp.deviation_ratio().is_infinite());
1263 }
1264
1265 #[test]
1266 fn test_checkpoint_zero_both() {
1267 let mut cp = CardinalityCheckpoint::new("test", 0.0);
1268 cp.record(0);
1269
1270 assert!((cp.deviation_ratio() - 1.0).abs() < 0.001);
1272 }
1273
1274 #[test]
1275 fn test_feedback_collection() {
1276 let mut feedback = CardinalityFeedback::new();
1277 feedback.record("scan_1", 1000);
1278 feedback.record("filter_1", 100);
1279
1280 assert_eq!(feedback.get("scan_1"), Some(1000));
1281 assert_eq!(feedback.get("filter_1"), Some(100));
1282 assert_eq!(feedback.get("unknown"), None);
1283 }
1284
1285 #[test]
1286 fn test_feedback_running_counter() {
1287 let mut feedback = CardinalityFeedback::new();
1288 feedback.init_counter("op_1");
1289
1290 feedback.add_rows("op_1", 100);
1291 feedback.add_rows("op_1", 200);
1292 feedback.add_rows("op_1", 50);
1293
1294 assert_eq!(feedback.get_running("op_1"), Some(350));
1295
1296 feedback.finalize_counter("op_1");
1297 assert_eq!(feedback.get("op_1"), Some(350));
1298 }
1299
1300 #[test]
1301 fn test_adaptive_context_basic() {
1302 let mut ctx = AdaptiveContext::new();
1303 ctx.set_estimate("scan", 1000.0);
1304 ctx.set_estimate("filter", 100.0);
1305
1306 ctx.record_actual("scan", 1000);
1307 ctx.record_actual("filter", 500); let cp = ctx.get_checkpoint("filter").unwrap();
1310 assert!((cp.deviation_ratio() - 5.0).abs() < 0.001);
1311 }
1312
1313 #[test]
1314 fn test_adaptive_context_should_reoptimize() {
1315 let mut ctx = AdaptiveContext::with_thresholds(2.0, 100);
1316 ctx.set_estimate("scan", 10000.0);
1317 ctx.set_estimate("filter", 1000.0);
1318
1319 ctx.record_actual("scan", 10000);
1320 ctx.record_actual("filter", 5000); assert!(ctx.should_reoptimize());
1323 assert_eq!(ctx.trigger_operator(), Some("filter"));
1324
1325 assert!(!ctx.should_reoptimize());
1327 }
1328
1329 #[test]
1330 fn test_adaptive_context_min_rows() {
1331 let mut ctx = AdaptiveContext::with_thresholds(2.0, 1000);
1332 ctx.set_estimate("filter", 100.0);
1333 ctx.record_actual("filter", 500); assert!(!ctx.should_reoptimize());
1337 }
1338
1339 #[test]
1340 fn test_adaptive_context_no_deviation() {
1341 let mut ctx = AdaptiveContext::new();
1342 ctx.set_estimate("scan", 1000.0);
1343 ctx.record_actual("scan", 1100); assert!(!ctx.has_significant_deviation());
1346 assert!(!ctx.should_reoptimize());
1347 }
1348
1349 #[test]
1350 fn test_adaptive_context_correction_factor() {
1351 let mut ctx = AdaptiveContext::new();
1352 ctx.set_estimate("filter", 100.0);
1353 ctx.record_actual("filter", 300);
1354
1355 assert!((ctx.correction_factor("filter") - 3.0).abs() < 0.001);
1356 assert!((ctx.correction_factor("unknown") - 1.0).abs() < 0.001);
1357 }
1358
1359 #[test]
1360 fn test_adaptive_context_apply_feedback() {
1361 let mut ctx = AdaptiveContext::new();
1362 ctx.set_estimate("scan", 1000.0);
1363 ctx.set_estimate("filter", 100.0);
1364
1365 let mut feedback = CardinalityFeedback::new();
1366 feedback.record("scan", 1000);
1367 feedback.record("filter", 500);
1368
1369 ctx.apply_feedback(&feedback);
1370
1371 assert_eq!(ctx.get_checkpoint("scan").unwrap().actual, 1000);
1372 assert_eq!(ctx.get_checkpoint("filter").unwrap().actual, 500);
1373 }
1374
1375 #[test]
1376 fn test_adaptive_summary() {
1377 let mut ctx = AdaptiveContext::with_thresholds(2.0, 0);
1378 ctx.set_estimate("op1", 100.0);
1379 ctx.set_estimate("op2", 200.0);
1380 ctx.set_estimate("op3", 300.0);
1381
1382 ctx.record_actual("op1", 100); ctx.record_actual("op2", 600); let _ = ctx.should_reoptimize();
1387
1388 let summary = ctx.summary();
1389 assert_eq!(summary.checkpoint_count, 3);
1390 assert_eq!(summary.recorded_count, 2);
1391 assert_eq!(summary.deviation_count, 1);
1392 assert!(summary.reoptimization_triggered);
1393 }
1394
1395 #[test]
1396 fn test_adaptive_context_reset() {
1397 let mut ctx = AdaptiveContext::new();
1398 ctx.set_estimate("scan", 1000.0);
1399 ctx.record_actual("scan", 5000);
1400 let _ = ctx.should_reoptimize(); assert!(ctx.reoptimization_triggered);
1403
1404 ctx.reset();
1405
1406 assert!(!ctx.reoptimization_triggered);
1407 assert_eq!(ctx.get_checkpoint("scan").unwrap().actual, 0);
1408 assert!(!ctx.get_checkpoint("scan").unwrap().recorded);
1409 assert!((ctx.get_checkpoint("scan").unwrap().estimated - 1000.0).abs() < 0.001);
1411 }
1412
1413 #[test]
1414 fn test_shared_context() {
1415 let ctx = SharedAdaptiveContext::new();
1416
1417 ctx.record_actual("op1", 1000);
1418
1419 let snapshot = ctx.snapshot().unwrap();
1420 assert_eq!(snapshot.get_checkpoint("op1").unwrap().actual, 1000);
1421 }
1422
1423 #[test]
1424 fn test_reoptimization_decision_continue() {
1425 let mut ctx = AdaptiveContext::new();
1426 ctx.set_estimate("scan", 1000.0);
1427 ctx.record_actual("scan", 1100);
1428
1429 let decision = evaluate_reoptimization(&ctx);
1430 assert_eq!(decision, ReoptimizationDecision::Continue);
1431 }
1432
1433 #[test]
1434 fn test_reoptimization_decision_reoptimize() {
1435 let mut ctx = AdaptiveContext::with_thresholds(2.0, 0);
1436 ctx.set_estimate("filter", 100.0);
1437 ctx.record_actual("filter", 500);
1438 let _ = ctx.should_reoptimize(); let decision = evaluate_reoptimization(&ctx);
1441
1442 if let ReoptimizationDecision::Reoptimize {
1443 trigger,
1444 corrections,
1445 } = decision
1446 {
1447 assert_eq!(trigger, "filter");
1448 assert!((corrections.get("filter").copied().unwrap_or(0.0) - 5.0).abs() < 0.001);
1449 } else {
1450 panic!("Expected Reoptimize decision");
1451 }
1452 }
1453
1454 #[test]
1455 fn test_reoptimization_decision_abort() {
1456 let mut ctx = AdaptiveContext::with_thresholds(2.0, 0);
1457 ctx.set_estimate("filter", 1.0);
1458 ctx.record_actual("filter", 1000); let _ = ctx.should_reoptimize();
1460
1461 let decision = evaluate_reoptimization(&ctx);
1462
1463 if let ReoptimizationDecision::Abort { reason } = decision {
1464 assert!(reason.contains("Catastrophic"));
1465 } else {
1466 panic!("Expected Abort decision");
1467 }
1468 }
1469
1470 #[test]
1471 fn test_absolute_deviation() {
1472 let mut cp = CardinalityCheckpoint::new("test", 100.0);
1473 cp.record(150);
1474
1475 assert!((cp.absolute_deviation() - 50.0).abs() < 0.001);
1476 }
1477
1478 #[test]
1481 fn test_adaptive_checkpoint_basic() {
1482 let mut cp = AdaptiveCheckpoint::new("filter_1", 0, 100.0);
1483 assert_eq!(cp.actual_rows, 0);
1484 assert!(!cp.triggered);
1485
1486 cp.record_rows(50);
1487 assert_eq!(cp.actual_rows, 50);
1488
1489 cp.record_rows(100);
1490 assert_eq!(cp.actual_rows, 150);
1491 }
1492
1493 #[test]
1494 fn test_adaptive_checkpoint_exceeds_threshold() {
1495 let mut cp = AdaptiveCheckpoint::new("filter", 0, 100.0);
1496
1497 cp.record_rows(50);
1499 assert!(!cp.exceeds_threshold(2.0, 100));
1500
1501 cp.record_rows(50);
1503 assert!(!cp.exceeds_threshold(2.0, 100)); cp.actual_rows = 0;
1507 cp.record_rows(500);
1508 assert!(cp.exceeds_threshold(2.0, 100)); let mut cp2 = AdaptiveCheckpoint::new("filter2", 0, 1000.0);
1512 cp2.record_rows(200);
1513 assert!(cp2.exceeds_threshold(2.0, 100)); }
1515
1516 #[test]
1517 fn test_adaptive_pipeline_config_default() {
1518 let config = AdaptivePipelineConfig::default();
1519
1520 assert_eq!(config.check_interval, 10_000);
1521 assert!((config.reoptimization_threshold - DEFAULT_REOPTIMIZATION_THRESHOLD).abs() < 0.001);
1522 assert_eq!(
1523 config.min_rows_for_reoptimization,
1524 MIN_ROWS_FOR_REOPTIMIZATION
1525 );
1526 assert_eq!(config.max_reoptimizations, 3);
1527 }
1528
1529 #[test]
1530 fn test_adaptive_pipeline_config_custom() {
1531 let config = AdaptivePipelineConfig::new(5000, 2.0, 500).with_max_reoptimizations(5);
1532
1533 assert_eq!(config.check_interval, 5000);
1534 assert!((config.reoptimization_threshold - 2.0).abs() < 0.001);
1535 assert_eq!(config.min_rows_for_reoptimization, 500);
1536 assert_eq!(config.max_reoptimizations, 5);
1537 }
1538
1539 #[test]
1540 fn test_adaptive_pipeline_builder() {
1541 let config = AdaptivePipelineBuilder::new()
1542 .with_config(AdaptivePipelineConfig::new(1000, 2.0, 100))
1543 .with_checkpoint("scan", 0, 10000.0)
1544 .with_checkpoint("filter", 1, 1000.0)
1545 .build();
1546
1547 assert_eq!(config.checkpoints.len(), 2);
1548 assert_eq!(config.checkpoints[0].id, "scan");
1549 assert!((config.checkpoints[0].estimated_cardinality - 10000.0).abs() < 0.001);
1550 assert_eq!(config.checkpoints[1].id, "filter");
1551 assert!((config.checkpoints[1].estimated_cardinality - 1000.0).abs() < 0.001);
1552 }
1553
1554 #[test]
1555 fn test_adaptive_execution_config_record_checkpoint() {
1556 let mut config = AdaptivePipelineBuilder::new()
1557 .with_checkpoint("filter", 0, 100.0)
1558 .build();
1559
1560 config.record_checkpoint("filter", 500);
1561
1562 let cp = config.context.get_checkpoint("filter").unwrap();
1564 assert_eq!(cp.actual, 500);
1565 assert!(cp.recorded);
1566
1567 let acp = config
1569 .checkpoints
1570 .iter()
1571 .find(|c| c.id == "filter")
1572 .unwrap();
1573 assert_eq!(acp.actual_rows, 500);
1574 }
1575
1576 #[test]
1577 fn test_adaptive_execution_config_should_reoptimize() {
1578 let mut config = AdaptivePipelineBuilder::new()
1579 .with_config(AdaptivePipelineConfig::new(1000, 2.0, 100))
1580 .with_checkpoint("filter", 0, 100.0)
1581 .build();
1582
1583 assert!(config.should_reoptimize().is_none());
1585
1586 config.record_checkpoint("filter", 150);
1588 assert!(config.should_reoptimize().is_none()); config.checkpoints[0].actual_rows = 0; config.record_checkpoint("filter", 500);
1593 config.checkpoints[0].actual_rows = 500;
1594
1595 let trigger = config.should_reoptimize();
1596 assert!(trigger.is_some());
1597 assert_eq!(trigger.unwrap().id, "filter");
1598 }
1599
1600 #[test]
1601 fn test_adaptive_execution_config_mark_triggered() {
1602 let mut config = AdaptivePipelineBuilder::new()
1603 .with_checkpoint("filter", 0, 100.0)
1604 .build();
1605
1606 assert!(!config.checkpoints[0].triggered);
1607
1608 config.mark_triggered("filter");
1609
1610 assert!(config.checkpoints[0].triggered);
1611 }
1612
1613 #[test]
1614 fn test_adaptive_event_callback() {
1615 use std::sync::atomic::AtomicUsize;
1616
1617 let event_count = Arc::new(AtomicUsize::new(0));
1618 let counter = event_count.clone();
1619
1620 let mut config = AdaptivePipelineBuilder::new()
1621 .with_checkpoint("filter", 0, 100.0)
1622 .with_event_callback(Box::new(move |_event| {
1623 counter.fetch_add(1, Ordering::Relaxed);
1624 }))
1625 .build();
1626
1627 config.record_checkpoint("filter", 500);
1628
1629 assert_eq!(event_count.load(Ordering::Relaxed), 1);
1631
1632 config.mark_triggered("filter");
1633
1634 assert_eq!(event_count.load(Ordering::Relaxed), 2);
1636 }
1637
1638 #[test]
1639 fn test_adaptive_checkpoint_with_zero_estimate() {
1640 let mut cp = AdaptiveCheckpoint::new("test", 0, 0.0);
1641 cp.record_rows(100);
1642
1643 assert!(cp.exceeds_threshold(2.0, 50));
1645 }
1646}