grafeo-core 0.5.35

Core graph models, indexes, and execution primitives for Grafeo
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
//! Generic collector trait for parallel aggregation.
//!
//! Collectors provide a clean separation between what data to aggregate
//! and how to execute the aggregation in parallel. The pattern is inspired
//! by Tantivy's collector architecture.
//!
//! # Pattern
//!
//! 1. Create partition-local collectors (one per worker thread)
//! 2. Each collector processes its partition independently (no shared state)
//! 3. Merge all partition results into a final result
//!
//! # Example
//!
//! ```no_run
//! use grafeo_core::execution::collector::{Collector, PartitionCollector, CountCollector};
//! use grafeo_core::execution::DataChunk;
//!
//! # fn example(partitions: Vec<Vec<DataChunk>>) -> Result<(), grafeo_core::execution::operators::OperatorError> {
//! let collector = CountCollector;
//!
//! // In parallel execution:
//! let mut partition_collectors: Vec<_> = (0..4)
//!     .map(|id| collector.for_partition(id))
//!     .collect();
//!
//! // Each partition processes its chunks
//! for (partition, chunks) in partitions.into_iter().enumerate() {
//!     for chunk in chunks {
//!         partition_collectors[partition].collect(&chunk)?;
//!     }
//! }
//!
//! // Merge results
//! let fruits: Vec<_> = partition_collectors.into_iter()
//!     .map(|c| c.harvest())
//!     .collect();
//! let total = collector.merge(fruits);
//! # Ok(())
//! # }
//! ```

use super::chunk::DataChunk;
use super::operators::OperatorError;

/// A collector that aggregates results from parallel execution.
///
/// Pattern: Create partition-local collectors, process independently,
/// then merge results. No shared mutable state during collection.
pub trait Collector: Sync {
    /// Final result type after merging all partitions.
    type Fruit: Send;

    /// Partition-local collector type.
    type PartitionCollector: PartitionCollector<Fruit = Self::Fruit>;

    /// Creates a collector for a single partition (called per-thread).
    fn for_partition(&self, partition_id: usize) -> Self::PartitionCollector;

    /// Merges results from all partitions (called once at the end).
    fn merge(&self, fruits: Vec<Self::Fruit>) -> Self::Fruit;
}

/// Per-partition collector - processes chunks locally.
///
/// Each partition collector is created by [`Collector::for_partition`]
/// and processes data independently. This enables lock-free parallel
/// execution.
pub trait PartitionCollector: Send {
    /// Result type produced by this partition.
    type Fruit: Send;

    /// Processes a batch of data.
    ///
    /// Called repeatedly with chunks from this partition.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the chunk cannot be processed (e.g., type mismatch).
    fn collect(&mut self, chunk: &DataChunk) -> Result<(), OperatorError>;

    /// Finalizes and returns the result for this partition.
    ///
    /// Called once after all chunks have been processed.
    fn harvest(self) -> Self::Fruit;
}

// ============================================================================
// Built-in Collectors
// ============================================================================

/// Counts rows across all partitions.
///
/// # Example
///
/// ```no_run
/// use grafeo_core::execution::collector::{Collector, PartitionCollector, CountCollector};
/// use grafeo_core::execution::DataChunk;
///
/// # fn example(chunk1: DataChunk, chunk2: DataChunk) -> Result<(), grafeo_core::execution::operators::OperatorError> {
/// let collector = CountCollector;
/// let mut pc = collector.for_partition(0);
///
/// pc.collect(&chunk1)?;
/// pc.collect(&chunk2)?;
///
/// let count = pc.harvest();
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct CountCollector;

impl Collector for CountCollector {
    type Fruit = u64;
    type PartitionCollector = CountPartitionCollector;

    fn for_partition(&self, _partition_id: usize) -> Self::PartitionCollector {
        CountPartitionCollector { count: 0 }
    }

    fn merge(&self, fruits: Vec<u64>) -> u64 {
        fruits.into_iter().sum()
    }
}

/// Partition-local counter.
pub struct CountPartitionCollector {
    count: u64,
}

impl PartitionCollector for CountPartitionCollector {
    type Fruit = u64;

    fn collect(&mut self, chunk: &DataChunk) -> Result<(), OperatorError> {
        self.count += chunk.len() as u64;
        Ok(())
    }

    fn harvest(self) -> u64 {
        self.count
    }
}

/// Collects all chunks (materializes the entire result).
///
/// Use this when you need all the data, not just an aggregate.
/// Be careful with large datasets - this can consume significant memory.
#[derive(Debug, Clone, Default)]
pub struct MaterializeCollector;

impl Collector for MaterializeCollector {
    type Fruit = Vec<DataChunk>;
    type PartitionCollector = MaterializePartitionCollector;

    fn for_partition(&self, _partition_id: usize) -> Self::PartitionCollector {
        MaterializePartitionCollector { chunks: Vec::new() }
    }

    fn merge(&self, mut fruits: Vec<Vec<DataChunk>>) -> Vec<DataChunk> {
        let total_chunks: usize = fruits.iter().map(|f| f.len()).sum();
        let mut result = Vec::with_capacity(total_chunks);
        for fruit in &mut fruits {
            result.append(fruit);
        }
        result
    }
}

/// Partition-local materializer.
pub struct MaterializePartitionCollector {
    chunks: Vec<DataChunk>,
}

impl PartitionCollector for MaterializePartitionCollector {
    type Fruit = Vec<DataChunk>;

    fn collect(&mut self, chunk: &DataChunk) -> Result<(), OperatorError> {
        self.chunks.push(chunk.clone());
        Ok(())
    }

    fn harvest(self) -> Vec<DataChunk> {
        self.chunks
    }
}

/// Collects first N rows across all partitions.
///
/// Stops collecting once the limit is reached (per partition).
/// Final merge ensures exactly `limit` rows are returned.
#[derive(Debug, Clone)]
pub struct LimitCollector {
    limit: usize,
}

impl LimitCollector {
    /// Creates a collector that limits output to `limit` rows.
    #[must_use]
    pub fn new(limit: usize) -> Self {
        Self { limit }
    }
}

impl Collector for LimitCollector {
    type Fruit = (Vec<DataChunk>, usize);
    type PartitionCollector = LimitPartitionCollector;

    fn for_partition(&self, _partition_id: usize) -> Self::PartitionCollector {
        LimitPartitionCollector {
            chunks: Vec::new(),
            limit: self.limit,
            collected: 0,
        }
    }

    fn merge(&self, fruits: Vec<(Vec<DataChunk>, usize)>) -> (Vec<DataChunk>, usize) {
        let mut result = Vec::new();
        let mut total = 0;

        for (chunks, _) in fruits {
            for chunk in chunks {
                if total >= self.limit {
                    break;
                }
                let take = (self.limit - total).min(chunk.len());
                if take < chunk.len() {
                    result.push(chunk.slice(0, take));
                } else {
                    result.push(chunk);
                }
                total += take;
            }
            if total >= self.limit {
                break;
            }
        }

        (result, total)
    }
}

/// Partition-local limiter.
pub struct LimitPartitionCollector {
    chunks: Vec<DataChunk>,
    limit: usize,
    collected: usize,
}

impl PartitionCollector for LimitPartitionCollector {
    type Fruit = (Vec<DataChunk>, usize);

    fn collect(&mut self, chunk: &DataChunk) -> Result<(), OperatorError> {
        if self.collected >= self.limit {
            return Ok(());
        }

        let take = (self.limit - self.collected).min(chunk.len());
        if take < chunk.len() {
            self.chunks.push(chunk.slice(0, take));
        } else {
            self.chunks.push(chunk.clone());
        }
        self.collected += take;

        Ok(())
    }

    fn harvest(self) -> (Vec<DataChunk>, usize) {
        (self.chunks, self.collected)
    }
}

/// Collects statistics (count, sum, min, max) for a column.
#[derive(Debug, Clone)]
pub struct StatsCollector {
    column_idx: usize,
}

impl StatsCollector {
    /// Creates a collector that computes statistics for the given column.
    #[must_use]
    pub fn new(column_idx: usize) -> Self {
        Self { column_idx }
    }
}

/// Statistics result from [`StatsCollector`].
#[derive(Debug, Clone, Default)]
pub struct CollectorStats {
    /// Number of non-null values.
    pub count: u64,
    /// Sum of values (if numeric).
    pub sum: f64,
    /// Minimum value (if ordered).
    pub min: Option<f64>,
    /// Maximum value (if ordered).
    pub max: Option<f64>,
}

impl CollectorStats {
    /// Merges another stats into this one.
    pub fn merge(&mut self, other: CollectorStats) {
        self.count += other.count;
        self.sum += other.sum;
        self.min = match (self.min, other.min) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (Some(v), None) | (None, Some(v)) => Some(v),
            (None, None) => None,
        };
        self.max = match (self.max, other.max) {
            (Some(a), Some(b)) => Some(a.max(b)),
            (Some(v), None) | (None, Some(v)) => Some(v),
            (None, None) => None,
        };
    }

    /// Computes the average (mean) value.
    #[must_use]
    pub fn avg(&self) -> Option<f64> {
        if self.count > 0 {
            Some(self.sum / self.count as f64)
        } else {
            None
        }
    }
}

impl Collector for StatsCollector {
    type Fruit = CollectorStats;
    type PartitionCollector = StatsPartitionCollector;

    fn for_partition(&self, _partition_id: usize) -> Self::PartitionCollector {
        StatsPartitionCollector {
            column_idx: self.column_idx,
            stats: CollectorStats::default(),
        }
    }

    fn merge(&self, fruits: Vec<CollectorStats>) -> CollectorStats {
        let mut result = CollectorStats::default();
        for fruit in fruits {
            result.merge(fruit);
        }
        result
    }
}

/// Partition-local stats collector.
pub struct StatsPartitionCollector {
    column_idx: usize,
    stats: CollectorStats,
}

impl PartitionCollector for StatsPartitionCollector {
    type Fruit = CollectorStats;

    fn collect(&mut self, chunk: &DataChunk) -> Result<(), OperatorError> {
        let column = chunk.column(self.column_idx).ok_or_else(|| {
            OperatorError::ColumnNotFound(format!(
                "column index {} out of bounds (width={})",
                self.column_idx,
                chunk.column_count()
            ))
        })?;

        for i in 0..chunk.len() {
            // Try typed access first (for specialized vectors), then fall back to generic
            let val = if let Some(f) = column.get_float64(i) {
                Some(f)
            } else if let Some(i) = column.get_int64(i) {
                Some(i as f64)
            } else if let Some(value) = column.get_value(i) {
                // Handle Generic vectors - extract numeric value
                match value {
                    grafeo_common::types::Value::Int64(i) => Some(i as f64),
                    grafeo_common::types::Value::Float64(f) => Some(f),
                    _ => None,
                }
            } else {
                None
            };

            if let Some(v) = val {
                self.stats.count += 1;
                self.stats.sum += v;
                self.stats.min = Some(match self.stats.min {
                    Some(m) => m.min(v),
                    None => v,
                });
                self.stats.max = Some(match self.stats.max {
                    Some(m) => m.max(v),
                    None => v,
                });
            }
        }

        Ok(())
    }

    fn harvest(self) -> CollectorStats {
        self.stats
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::execution::ValueVector;
    use grafeo_common::types::Value;

    fn make_test_chunk(size: usize) -> DataChunk {
        let values: Vec<Value> = (0..size).map(|i| Value::from(i as i64)).collect();
        let column = ValueVector::from_values(&values);
        DataChunk::new(vec![column])
    }

    #[test]
    fn test_count_collector() {
        let collector = CountCollector;

        let mut pc = collector.for_partition(0);
        pc.collect(&make_test_chunk(10)).unwrap();
        pc.collect(&make_test_chunk(5)).unwrap();
        let count1 = pc.harvest();

        let mut pc2 = collector.for_partition(1);
        pc2.collect(&make_test_chunk(7)).unwrap();
        let count2 = pc2.harvest();

        let total = collector.merge(vec![count1, count2]);
        assert_eq!(total, 22);
    }

    #[test]
    fn test_materialize_collector() {
        let collector = MaterializeCollector;

        let mut pc = collector.for_partition(0);
        pc.collect(&make_test_chunk(10)).unwrap();
        pc.collect(&make_test_chunk(5)).unwrap();
        let chunks1 = pc.harvest();

        let mut pc2 = collector.for_partition(1);
        pc2.collect(&make_test_chunk(7)).unwrap();
        let chunks2 = pc2.harvest();

        let result = collector.merge(vec![chunks1, chunks2]);
        assert_eq!(result.len(), 3);
        assert_eq!(result.iter().map(|c| c.len()).sum::<usize>(), 22);
    }

    #[test]
    fn test_limit_collector() {
        let collector = LimitCollector::new(12);

        let mut pc = collector.for_partition(0);
        pc.collect(&make_test_chunk(10)).unwrap();
        pc.collect(&make_test_chunk(5)).unwrap(); // Only 2 more should be taken
        let result1 = pc.harvest();

        let mut pc2 = collector.for_partition(1);
        pc2.collect(&make_test_chunk(20)).unwrap();
        let result2 = pc2.harvest();

        let (chunks, total) = collector.merge(vec![result1, result2]);
        assert_eq!(total, 12);

        let actual_rows: usize = chunks.iter().map(|c| c.len()).sum();
        assert_eq!(actual_rows, 12);
    }

    #[test]
    fn test_stats_collector() {
        let collector = StatsCollector::new(0);

        let mut pc = collector.for_partition(0);

        // Create chunk with values 0..10
        let values: Vec<Value> = (0..10).map(|i| Value::from(i as i64)).collect();
        let column = ValueVector::from_values(&values);
        let chunk = DataChunk::new(vec![column]);

        pc.collect(&chunk).unwrap();
        let stats = pc.harvest();

        assert_eq!(stats.count, 10);
        assert!((stats.sum - 45.0).abs() < 0.001); // 0+1+2+...+9 = 45
        assert!((stats.min.unwrap() - 0.0).abs() < 0.001);
        assert!((stats.max.unwrap() - 9.0).abs() < 0.001);
        assert!((stats.avg().unwrap() - 4.5).abs() < 0.001);
    }

    #[test]
    fn test_stats_merge() {
        let collector = StatsCollector::new(0);

        // Partition 1: values 0..5
        let mut pc1 = collector.for_partition(0);
        let values1: Vec<Value> = (0..5).map(|i| Value::from(i as i64)).collect();
        let chunk1 = DataChunk::new(vec![ValueVector::from_values(&values1)]);
        pc1.collect(&chunk1).unwrap();

        // Partition 2: values 5..10
        let mut pc2 = collector.for_partition(1);
        let values2: Vec<Value> = (5..10).map(|i| Value::from(i as i64)).collect();
        let chunk2 = DataChunk::new(vec![ValueVector::from_values(&values2)]);
        pc2.collect(&chunk2).unwrap();

        let stats = collector.merge(vec![pc1.harvest(), pc2.harvest()]);

        assert_eq!(stats.count, 10);
        assert!((stats.min.unwrap() - 0.0).abs() < 0.001);
        assert!((stats.max.unwrap() - 9.0).abs() < 0.001);
    }
}