oxirs-arq 0.2.4

Jena-style SPARQL algebra with extension points and query optimization
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Streaming Query Analyzer
//!
//! This module provides comprehensive analysis and optimization for streaming query execution,
//! including memory management, spilling policies, streaming strategies, and pipeline analysis.

use crate::algebra::Algebra;
use anyhow::Result;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

/// Streaming query analyzer with advanced memory-aware optimization
#[derive(Clone)]
pub struct StreamingAnalyzer {
    config: StreamingConfig,
    current_memory_bytes: Arc<AtomicU64>,
}

/// Configuration for streaming execution
#[derive(Debug, Clone)]
pub struct StreamingConfig {
    pub enable_streaming: bool,
    pub memory_threshold_mb: usize,   // 2048 MB default
    pub spill_threshold_percent: f64, // 0.8 (80%)
    pub streaming_batch_size: usize,  // 1000 rows
}

impl Default for StreamingConfig {
    fn default() -> Self {
        Self {
            enable_streaming: true,
            memory_threshold_mb: 2048,
            spill_threshold_percent: 0.8,
            streaming_batch_size: 1000,
        }
    }
}

/// Streaming execution strategy
#[derive(Debug, Clone)]
pub struct StreamingStrategy {
    pub strategy_type: StreamingType,
    pub memory_limit: usize,
    pub batch_size: usize,
    pub spill_threshold: f64,
    pub parallelism_degree: usize,
}

/// Types of streaming strategies
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamingType {
    PipelineBreaker,
    HashJoinStreaming,
    SortMergeStreaming,
    NestedLoopStreaming,
    IndexNestedLoop,
    HybridStreaming,
}

/// Spill policy for memory management
#[derive(Debug, Clone)]
pub struct SpillPolicy {
    pub policy_type: SpillType,
    pub threshold: f64,
    pub target_operators: Vec<String>,
    pub cost_factor: f64,
}

/// Types of spill policies
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpillType {
    LeastRecentlyUsed,
    LargestFirst,
    CostBased,
    PredictiveBased,
}

/// Streaming opportunities identified in query plan
#[derive(Debug, Clone, Default)]
pub struct StreamingOpportunities {
    pub streamable_scans: Vec<OperatorId>,
    pub streamable_filters: Vec<OperatorId>,
    pub streamable_projects: Vec<OperatorId>,
    pub requires_materialization: Vec<(OperatorId, &'static str)>,
    pub pipeline_breakers: Vec<OperatorId>,
    pub estimated_memory_savings_mb: usize,
}

/// Operator identifier
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub struct OperatorId(u64);

impl OperatorId {
    fn new(id: u64) -> Self {
        Self(id)
    }
}

/// Query plan representation for streaming analysis
#[derive(Debug, Clone)]
pub struct QueryPlan {
    operators: Vec<Operator>,
    operator_id_counter: u64,
}

impl QueryPlan {
    pub fn from_algebra(algebra: &Algebra) -> Self {
        let mut plan = Self {
            operators: Vec::new(),
            operator_id_counter: 0,
        };
        plan.build_from_algebra(algebra);
        plan
    }

    fn build_from_algebra(&mut self, algebra: &Algebra) {
        match algebra {
            Algebra::Bgp(patterns) => {
                let id = self.next_id();
                self.operators.push(Operator::Scan(ScanOperator {
                    id,
                    patterns: patterns.len(),
                }));
            }
            Algebra::Filter { pattern, .. } => {
                self.build_from_algebra(pattern);
                let id = self.next_id();
                self.operators.push(Operator::Filter(FilterOperator { id }));
            }
            Algebra::Project { pattern, variables } => {
                self.build_from_algebra(pattern);
                let id = self.next_id();
                self.operators.push(Operator::Project(ProjectOperator {
                    id,
                    num_vars: variables.len(),
                }));
            }
            Algebra::Join { left, right } => {
                self.build_from_algebra(left);
                self.build_from_algebra(right);
                let id = self.next_id();
                self.operators
                    .push(Operator::HashJoin(HashJoinOperator { id }));
            }
            Algebra::LeftJoin { left, right, .. } => {
                self.build_from_algebra(left);
                self.build_from_algebra(right);
                let id = self.next_id();
                self.operators
                    .push(Operator::HashJoin(HashJoinOperator { id }));
            }
            Algebra::Union { left, right } => {
                self.build_from_algebra(left);
                self.build_from_algebra(right);
                let id = self.next_id();
                self.operators.push(Operator::Union(UnionOperator { id }));
            }
            Algebra::OrderBy { pattern, .. } => {
                self.build_from_algebra(pattern);
                let id = self.next_id();
                self.operators.push(Operator::Sort(SortOperator { id }));
            }
            Algebra::Group { pattern, .. } => {
                self.build_from_algebra(pattern);
                let id = self.next_id();
                self.operators
                    .push(Operator::Aggregation(AggregationOperator { id }));
            }
            Algebra::Distinct { pattern } => {
                self.build_from_algebra(pattern);
                let id = self.next_id();
                self.operators
                    .push(Operator::Distinct(DistinctOperator { id }));
            }
            Algebra::Slice { pattern, .. } => {
                self.build_from_algebra(pattern);
                let id = self.next_id();
                self.operators.push(Operator::Limit(LimitOperator { id }));
            }
            _ => {
                // Handle other operators generically
                let id = self.next_id();
                self.operators
                    .push(Operator::Generic(GenericOperator { id }));
            }
        }
    }

    fn next_id(&mut self) -> OperatorId {
        let id = OperatorId::new(self.operator_id_counter);
        self.operator_id_counter += 1;
        id
    }

    pub fn operators(&self) -> &[Operator] {
        &self.operators
    }
}

/// Query operators
#[derive(Debug, Clone)]
pub enum Operator {
    Scan(ScanOperator),
    Filter(FilterOperator),
    Project(ProjectOperator),
    HashJoin(HashJoinOperator),
    SortMergeJoin(SortMergeJoinOperator),
    Sort(SortOperator),
    Aggregation(AggregationOperator),
    Distinct(DistinctOperator),
    Union(UnionOperator),
    Limit(LimitOperator),
    Generic(GenericOperator),
}

impl Operator {
    pub fn id(&self) -> OperatorId {
        match self {
            Operator::Scan(op) => op.id,
            Operator::Filter(op) => op.id,
            Operator::Project(op) => op.id,
            Operator::HashJoin(op) => op.id,
            Operator::SortMergeJoin(op) => op.id,
            Operator::Sort(op) => op.id,
            Operator::Aggregation(op) => op.id,
            Operator::Distinct(op) => op.id,
            Operator::Union(op) => op.id,
            Operator::Limit(op) => op.id,
            Operator::Generic(op) => op.id,
        }
    }
}

#[derive(Debug, Clone)]
pub struct ScanOperator {
    pub id: OperatorId,
    pub patterns: usize,
}

#[derive(Debug, Clone)]
pub struct FilterOperator {
    pub id: OperatorId,
}

#[derive(Debug, Clone)]
pub struct ProjectOperator {
    pub id: OperatorId,
    pub num_vars: usize,
}

#[derive(Debug, Clone)]
pub struct HashJoinOperator {
    pub id: OperatorId,
}

#[derive(Debug, Clone)]
pub struct SortMergeJoinOperator {
    pub id: OperatorId,
}

#[derive(Debug, Clone)]
pub struct SortOperator {
    pub id: OperatorId,
}

#[derive(Debug, Clone)]
pub struct AggregationOperator {
    pub id: OperatorId,
}

#[derive(Debug, Clone)]
pub struct DistinctOperator {
    pub id: OperatorId,
}

#[derive(Debug, Clone)]
pub struct UnionOperator {
    pub id: OperatorId,
}

#[derive(Debug, Clone)]
pub struct LimitOperator {
    pub id: OperatorId,
}

#[derive(Debug, Clone)]
pub struct GenericOperator {
    pub id: OperatorId,
}

impl StreamingAnalyzer {
    /// Create a new streaming analyzer
    pub fn new(config: StreamingConfig) -> Self {
        Self {
            config,
            current_memory_bytes: Arc::new(AtomicU64::new(0)),
        }
    }

    /// Analyze query plan for streaming opportunities
    pub fn analyze(&self, plan: &QueryPlan) -> StreamingOpportunities {
        let mut opportunities = StreamingOpportunities::default();

        // Identify streaming operators
        for op in plan.operators() {
            match op {
                Operator::Scan(_) => {
                    // Always streamable
                    opportunities.streamable_scans.push(op.id());
                }
                Operator::Filter(_)
                    // Streamable if input is streamable
                    if self.is_input_streamable(op, &opportunities) => {
                        opportunities.streamable_filters.push(op.id());
                    }
                Operator::Project(_) => {
                    // Streamable projection
                    opportunities.streamable_projects.push(op.id());
                }
                Operator::HashJoin(_) => {
                    // Hash join: Build side must materialize, probe side can stream
                    opportunities
                        .requires_materialization
                        .push((op.id(), "build_side"));
                }
                Operator::SortMergeJoin(_) => {
                    // Both sides must be sorted (materialization required)
                    opportunities
                        .requires_materialization
                        .push((op.id(), "both_sides"));
                }
                Operator::Sort(_) => {
                    // Sorting requires full materialization
                    opportunities.pipeline_breakers.push(op.id());
                }
                Operator::Aggregation(_) => {
                    // Aggregation requires materialization (unless streaming aggregates)
                    opportunities.pipeline_breakers.push(op.id());
                }
                Operator::Distinct(_) => {
                    // Distinct requires materialization
                    opportunities.pipeline_breakers.push(op.id());
                }
                Operator::Union(_) => {
                    // Non-streaming union requires materialization
                    opportunities.pipeline_breakers.push(op.id());
                }
                _ => {}
            }
        }

        // Estimate memory savings
        opportunities.estimated_memory_savings_mb = self.estimate_memory_savings(&opportunities);

        opportunities
    }

    /// Check if input to operator is streamable
    fn is_input_streamable(
        &self,
        _operator: &Operator,
        opportunities: &StreamingOpportunities,
    ) -> bool {
        // Simplified: Check if most upstream operators are streamable
        !opportunities.streamable_scans.is_empty() || !opportunities.streamable_filters.is_empty()
    }

    /// Estimate memory savings from streaming
    fn estimate_memory_savings(&self, opportunities: &StreamingOpportunities) -> usize {
        // Simple heuristic: Each streamable operator saves ~100MB
        let num_streamable = opportunities.streamable_scans.len()
            + opportunities.streamable_filters.len()
            + opportunities.streamable_projects.len();
        num_streamable * 100 // MB per operator
    }

    /// Determine if operator should stream
    pub fn should_stream(&self, _operator: &Operator, estimated_size: usize) -> bool {
        if !self.config.enable_streaming {
            return false;
        }

        // Stream if estimated result size > memory threshold
        let threshold_bytes = self.config.memory_threshold_mb * 1024 * 1024;
        estimated_size > threshold_bytes
    }

    /// Identify pipeline breakers (operators that block streaming)
    pub fn find_pipeline_breakers(&self, plan: &QueryPlan) -> Vec<OperatorId> {
        let mut breakers = vec![];

        for op in plan.operators() {
            if self.is_pipeline_breaker(op) {
                breakers.push(op.id());
            }
        }

        breakers
    }

    fn is_pipeline_breaker(&self, op: &Operator) -> bool {
        matches!(
            op,
            Operator::Sort(_)
                | Operator::Aggregation(_)
                | Operator::Distinct(_)
                | Operator::Union(_)
        )
    }

    /// Convert materialized operator to streaming
    pub fn convert_to_streaming(&self, operator: &mut Operator) -> Result<()> {
        match operator {
            Operator::HashJoin(_) => {
                // Use streaming probe side
                // In a real implementation, we'd modify the operator's internal state
                Ok(())
            }
            Operator::Aggregation(_) => {
                // Convert to streaming aggregation (if grouping keys sortable)
                // Check if can stream
                Ok(())
            }
            _ => Ok(()),
        }
    }

    /// Analyze streaming potential for query
    pub fn analyze_streaming_potential(
        &self,
        algebra: &Algebra,
    ) -> Result<Option<StreamingStrategy>> {
        let plan = QueryPlan::from_algebra(algebra);
        let opportunities = self.analyze(&plan);

        // If we have streaming opportunities, return a strategy
        if !opportunities.streamable_scans.is_empty() {
            Ok(Some(StreamingStrategy {
                strategy_type: StreamingType::HashJoinStreaming,
                memory_limit: self.config.memory_threshold_mb * 1024 * 1024,
                batch_size: self.config.streaming_batch_size,
                spill_threshold: self.config.spill_threshold_percent,
                parallelism_degree: num_cpus::get(),
            }))
        } else {
            Ok(None)
        }
    }

    /// Get memory threshold
    pub fn memory_threshold(&self) -> usize {
        self.config.memory_threshold_mb * 1024 * 1024
    }

    /// Update memory threshold
    pub fn set_memory_threshold(&mut self, threshold_mb: usize) {
        self.config.memory_threshold_mb = threshold_mb;
    }

    /// Add spill policy
    pub fn add_spill_policy(&mut self, _policy: SpillPolicy) {
        // Store policy for later use
    }

    /// Get active spill policies
    pub fn spill_policies(&self) -> &[SpillPolicy] {
        // Return empty slice for now
        &[]
    }

    /// Get the count of optimizations applied
    pub fn optimizations_count(&self) -> usize {
        // Return count based on config
        if self.config.enable_streaming {
            1
        } else {
            0
        }
    }

    /// Get current memory usage
    pub fn current_memory_usage(&self) -> usize {
        self.current_memory_bytes.load(Ordering::Relaxed) as usize
    }

    /// Check if should spill to disk
    pub fn should_spill(&self) -> bool {
        let current_usage = self.current_memory_usage();
        let threshold =
            (self.memory_threshold() as f64 * self.config.spill_threshold_percent) as usize;
        current_usage > threshold
    }

    /// Analyze query complexity for streaming decision
    pub fn analyze_query_complexity(&self, algebra: &Algebra) -> QueryComplexity {
        let mut complexity = QueryComplexity::default();
        self.compute_complexity(algebra, &mut complexity);
        complexity
    }

    fn compute_complexity(&self, algebra: &Algebra, complexity: &mut QueryComplexity) {
        match algebra {
            Algebra::Bgp(patterns) => {
                complexity.num_patterns += patterns.len();
            }
            Algebra::Join { left, right }
            | Algebra::Union { left, right }
            | Algebra::LeftJoin { left, right, .. } => {
                complexity.num_joins += 1;
                self.compute_complexity(left, complexity);
                self.compute_complexity(right, complexity);
            }
            Algebra::Filter { pattern, .. } => {
                complexity.num_filters += 1;
                self.compute_complexity(pattern, complexity);
            }
            Algebra::OrderBy { pattern, .. } => {
                complexity.num_sorts += 1;
                self.compute_complexity(pattern, complexity);
            }
            Algebra::Group { pattern, .. } => {
                complexity.num_aggregations += 1;
                self.compute_complexity(pattern, complexity);
            }
            _ => {}
        }
    }
}

/// Query complexity metrics
#[derive(Debug, Clone, Default)]
pub struct QueryComplexity {
    pub num_patterns: usize,
    pub num_joins: usize,
    pub num_filters: usize,
    pub num_sorts: usize,
    pub num_aggregations: usize,
}

impl QueryComplexity {
    pub fn total_complexity(&self) -> usize {
        self.num_patterns
            + self.num_joins * 2
            + self.num_filters
            + self.num_sorts * 3
            + self.num_aggregations * 2
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_streaming_analyzer_creation() {
        let config = StreamingConfig::default();
        let analyzer = StreamingAnalyzer::new(config);
        assert_eq!(analyzer.memory_threshold(), 2048 * 1024 * 1024);
    }

    #[test]
    fn test_should_stream_decision() {
        let config = StreamingConfig {
            enable_streaming: true,
            memory_threshold_mb: 1024,
            spill_threshold_percent: 0.8,
            streaming_batch_size: 1000,
        };
        let analyzer = StreamingAnalyzer::new(config);

        // Small data should not stream
        assert!(!analyzer.should_stream(
            &Operator::Scan(ScanOperator {
                id: OperatorId::new(1),
                patterns: 1
            }),
            100 * 1024 * 1024
        ));

        // Large data should stream
        assert!(analyzer.should_stream(
            &Operator::Scan(ScanOperator {
                id: OperatorId::new(1),
                patterns: 1
            }),
            2048 * 1024 * 1024
        ));
    }

    #[test]
    fn test_pipeline_breaker_detection() {
        let config = StreamingConfig::default();
        let analyzer = StreamingAnalyzer::new(config);

        assert!(analyzer.is_pipeline_breaker(&Operator::Sort(SortOperator {
            id: OperatorId::new(1)
        })));
        assert!(
            analyzer.is_pipeline_breaker(&Operator::Aggregation(AggregationOperator {
                id: OperatorId::new(2)
            }))
        );
        assert!(
            !analyzer.is_pipeline_breaker(&Operator::Filter(FilterOperator {
                id: OperatorId::new(3)
            }))
        );
    }
}